tb_str.h 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // ================================================================================
  2. // == This file is a part of Turbo Badger. (C) 2011-2014, Emil Segerås ==
  3. // == See tb_core.h for more information. ==
  4. // ================================================================================
  5. #ifndef TB_STR_H
  6. #define TB_STR_H
  7. #include "tb_types.h"
  8. #include <string.h>
  9. namespace tb {
  10. /** Use as parameter for string length if you know the string is null terminated.
  11. Can be used in functions that support it. */
  12. #define TB_ALL_TO_TERMINATION 2147483647
  13. /** Some useful C-like functions that's missing in the standard. */
  14. const char *stristr(const char *arg1, const char *arg2);
  15. /** Simple string class that doesn't own or change the string pointer. */
  16. class TBStrC
  17. {
  18. protected:
  19. char *s;
  20. public:
  21. TBStrC(const char *str) : s(const_cast<char *>(str)) {}
  22. inline int Length() const { return (int) strlen(s); }
  23. inline bool IsEmpty() const { return s[0] == 0; }
  24. inline int Compare(const char* str) const { return strcmp(s, str); }
  25. inline bool Equals(const char* str) const { return !strcmp(s, str); }
  26. inline char operator[](int n) const { return s[n]; }
  27. inline operator const char *() const { return s; }
  28. const char *CStr() const { return s; }
  29. };
  30. /** TBStr is a simple string class.
  31. It's a compact wrapper for a char array, and doesn't do any storage magic to
  32. avoid buffer copying or remember its length. It is intended as "final storage"
  33. of strings since its buffer is compact.
  34. Serious work on strings is better done using TBTempBuffer and then set on a TBStr for
  35. final storage (since TBTempBuffer is optimized for speed rather than being compact).
  36. It is guaranteed to have a valid pointer at all times. If uninitialized, emptied or on
  37. out of memory, its storage will be a empty ("") const string.
  38. */
  39. class TBStr : public TBStrC
  40. {
  41. public:
  42. ~TBStr();
  43. TBStr();
  44. TBStr(const TBStr &str);
  45. TBStr(const char* str);
  46. TBStr(const char* str, int len);
  47. bool Set(const char* str, int len = TB_ALL_TO_TERMINATION);
  48. bool SetFormatted(const char* format, ...);
  49. void Clear();
  50. void Remove(int ofs, int len);
  51. bool Insert(int ofs, const char *ins, int ins_len = TB_ALL_TO_TERMINATION);
  52. bool Append(const char *ins, int ins_len = TB_ALL_TO_TERMINATION) { return Insert((int)strlen(s), ins, ins_len); }
  53. inline operator char *() const { return s; }
  54. char *CStr() const { return s; }
  55. const TBStr& operator = (const TBStr &str) { Set(str); return *this; }
  56. };
  57. }; // namespace tb
  58. #endif // TB_STR_H