stringbuilder.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #ifndef __STRINGBUILDER_H
  2. #define __STRINGBUILDER_H
  3. #include "datastring.h"
  4. #include "biglist.h"
  5. #include <cstdint>
  6. // stringbuilder is used to concatenate strings together.
  7. // The strings are not actually concatenated until you store
  8. // the stringbuilder into a datablock or a message.
  9. // Numbers can be appended to the string too.
  10. // When numbers are appended, the number is stored.
  11. // It's converted to a string when you call tostring().
  12. union stringbuilder_data
  13. {
  14. datastring item;
  15. int64_t number; // If is_number is true, use this number instead of item.
  16. };
  17. class stringbuilder_node
  18. {
  19. public:
  20. bool need_to_delete; // Should item.data be deleted in the clear() function?
  21. bool is_number; // Is this item a number?
  22. stringbuilder_data data;
  23. stringbuilder_node(); // This constructor is only used for fast_nodes.
  24. stringbuilder_node(datastring node,bool should_delete);
  25. stringbuilder_node(int64_t value);
  26. void clear();
  27. };
  28. class stringbuilder
  29. {
  30. public:
  31. stringbuilder();
  32. ~stringbuilder();
  33. int index;
  34. biglist<stringbuilder_node *>nodes;
  35. stringbuilder &operator+=(const char *item);
  36. stringbuilder &operator+=(datastring item);
  37. stringbuilder &operator+=(int item);
  38. stringbuilder &operator+=(int64_t item);
  39. stringbuilder &addparameter(int item); // Adds a number, then a comma.
  40. stringbuilder &addparameter(int64_t item); // Adds a number, then a comma.
  41. stringbuilder &addparameter(datastring item); // Appends the length first, then a comma, then the data.
  42. stringbuilder &append(datastring item, bool need_to_delete);
  43. stringbuilder &append(int64_t item);
  44. void print();
  45. void println();
  46. int length(); // Returns the total number of bytes in this stringbuilder.
  47. void clear(); // Clears the list and deletes any allocated items.
  48. int tostring(char *buffer); // Save this string to a buffer. Returns the number of bytes.
  49. private:
  50. // fast_nodes are used to avoid allocating memory.
  51. static const int FAST_NODE_COUNT = 40;
  52. stringbuilder_node fast_nodes[FAST_NODE_COUNT];
  53. };
  54. #endif