String.h 1.3 KB

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