String.h 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // ArduinoJson - https://arduinojson.org
  2. // Copyright © 2014-2025, Benoit BLANCHON
  3. // MIT License
  4. #pragma once
  5. #include <string>
  6. // Reproduces Arduino's String class
  7. class String {
  8. public:
  9. String() = default;
  10. String(const char* s) {
  11. if (s)
  12. str_.assign(s);
  13. }
  14. void limitCapacityTo(size_t maxCapacity) {
  15. maxCapacity_ = maxCapacity;
  16. }
  17. unsigned char concat(const char* s) {
  18. return concat(s, strlen(s));
  19. }
  20. size_t length() const {
  21. return str_.size();
  22. }
  23. const char* c_str() const {
  24. return str_.c_str();
  25. }
  26. bool operator==(const char* s) const {
  27. return str_ == s;
  28. }
  29. String& operator=(const char* s) {
  30. if (s)
  31. str_.assign(s);
  32. else
  33. str_.clear();
  34. return *this;
  35. }
  36. char operator[](unsigned int index) const {
  37. if (index >= str_.size())
  38. return 0;
  39. return str_[index];
  40. }
  41. friend std::ostream& operator<<(std::ostream& lhs, const ::String& rhs) {
  42. lhs << rhs.str_;
  43. return lhs;
  44. }
  45. protected:
  46. // This function is protected in most Arduino cores
  47. unsigned char concat(const char* s, size_t n) {
  48. if (str_.size() + n > maxCapacity_)
  49. return 0;
  50. str_.append(s, n);
  51. return 1;
  52. }
  53. private:
  54. std::string str_;
  55. size_t maxCapacity_ = 1024;
  56. };
  57. class StringSumHelper : public ::String {};
  58. inline bool operator==(const std::string& lhs, const ::String& rhs) {
  59. return lhs == rhs.c_str();
  60. }