String.h 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // ArduinoJson - https://arduinojson.org
  2. // Copyright Benoit Blanchon 2014-2021
  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. friend std::ostream& operator<<(std::ostream& lhs, const ::String& rhs) {
  27. lhs << rhs._str;
  28. return lhs;
  29. }
  30. protected:
  31. // This function is protected in most Arduino cores
  32. unsigned char concat(const char* s, size_t n) {
  33. if (_str.size() + n > _maxCapacity)
  34. return 0;
  35. _str.append(s, n);
  36. return 1;
  37. }
  38. private:
  39. std::string _str;
  40. size_t _maxCapacity;
  41. };
  42. class StringSumHelper;
  43. inline bool operator==(const std::string& lhs, const ::String& rhs) {
  44. return lhs == rhs.c_str();
  45. }