SafeString  4.1.44
SafeString is a safe, robust and debuggable replacement for string processing in Arduino
SafeString.h
Go to the documentation of this file.
1 // !!!!!!!!! WARNING in V2 substring endIdx is EXCLUSIVE !!!!!!!!!! change from V1 inclusive
2 /*
3  The SafeString class V4.1.29
4 
5 
6  ----------------- creating SafeStrings ---------------------------------
7  See the example sketches SafeString_ConstructorAndDebugging.ino and SafeStringFromCharArray.ino
8  and SafeStringFromCharPtr.ino and SafeStringFromCharPtrWithSize.ion
9 
10  createSafeString(name, size) and createSafeString(name, size, "initialText")
11  are utility macros to create an SafeString of a given name and size and optionally, an initial value
12 
13  createSafeString(str, 40); or cSF(str, 40);
14  expands in the pre-processor to
15  char str_SAFEBUFFER[40+1];
16  SafeString str(sizeof(str_SAFEBUFFER),str_SAFEBUFFER,"","str");
17 
18  createSafeString(str, 40, "test"); or cSF(str, 40, "test");
19  expands in the pre-processor to
20  char str_SAFEBUFFER[40+1];
21  SafeString str(sizeof(str_SAFEBUFFER),str_SAFEBUFFER,"test","str");
22 
23  createSafeStringFromCharArray(name, char[]); or cSFA(name, char[]);
24  wraps an existing char[] in a SafeString of the given name
25  e.g.
26  char charBuffer[15];
27  createSafeStringFromCharArray(str,charBuffer); or cSFA(str,charBuffer);
28  expands in the pre-processor to
29  SafeString str(sizeof(charBuffer),charBuffer, charBuffer, "str", true);
30 
31  createSafeStringFromCharPtrWithSize(name, char*, unsigned int); or cSFPS(name, char*, unsigned int);
32  wraps an existing char[] pointed to by char* in a SafeString of the given name.
33  The arraySize argument is the size of the char[], so the capacity is set to arraySize-1 to allow for the terminating '\0'
34  e.g.
35  char charBuffer[15]; // can hold 14 char + terminating '\0'
36  char *bufPtr = charBuffer;
37  createSafeStringFromCharPtrWithSize(str,bufPtr, 15); or cSFPS(str,bufPtr, 15);
38  expands in the pre-processor to
39  SafeString str(15,charBuffer, charBuffer, "str", true);
40  The capacity of the SafeString is set to 14, i.e. arraySize-1
41 
42  createSafeStringFromCharPtr(name, char*); or cSFP(name, char*);
43  wraps an existing char[] pointed to by char* in a SafeString of the given name
44  createSafeStringFromCharPtr(name, char* s) is the same as createSafeStringFromCharPtrWithSize(name, char* s, strlen(s)+1);
45  That is the current strlen() is used to set the SafeString capacity.
46  Note the +1 above: cSFPS sets capacity to its size argument -1, so matching cSFP's capacity of strlen(s) needs strlen(s)+1
47  e.g.
48  char charBuffer[15] = "test";
49  char *bufPtr = charBuffer;
50  createSafeStringFromCharPtr(str,bufPtr); or cSFP(str,bufPtr);
51  expands in the pre-processor to
52  SafeString str((unsigned int)-1,charBuffer, charBuffer, "str", true);
53  the -1 tells the constructor to take the capacity from strlen(charBuffer), and it cannot be increased.
54  NOTE CAREFULLY: the capacity here is 4, the strlen of "test", NOT 14. cSFP( ) uses strlen( ), not the
55  size of the array, because a char* carries no size information. The other 10 bytes of charBuffer[15]
56  are unusable through this SafeString. If you want the capacity to be 14, the array size-1, you must
57  tell SafeString the size yourself with cSFA(str,charBuffer) or cSFPS(str,bufPtr,15).
58 
59 
60  If str is a SafeString then
61  str = .. works for signed/unsigned ints, char*, char, F(".."), SafeString float, double etc
62  str.concat(..) and string.prefix(..) also works for those
63  str.stoken(..) can be used to split a string in to tokens
64 
65  SafeStrings created via createSafeString( ) are never invalid, even if called with invalid arguments.
66  SafeStrings created via createSafeStringFromBuffer( ) are valid as long at the buffer is valid.
67  Usually the only way the buffer can become invalid is if it exists in a struct that is allocated (via calloc/malloc)
68  and then freed while the SafeString wrapping it is still in use.
69 *********************************/
70 
71 /*
72  SafeString.h static memory SafeString library modified by
73  Matthew Ford
74  Mods Copyright(c)2020 Forward Computing and Control Pty. Ltd.
75  All rights reservered subject to the License below
76 
77  modified from
78  WString.h - String library for Wiring & Arduino
79  ...mostly rewritten by Paul Stoffregen...
80  Copyright (c) 2009-10 Hernando Barragan. All right reserved.
81  Copyright 2011, Paul Stoffregen, paul@pjrc.com
82 
83  This library is free software; you can redistribute it and/or
84  modify it under the terms of the GNU Lesser General Public
85  License as published by the Free Software Foundation; either
86  version 2.1 of the License, or (at your option) any later version.
87 
88  This library is distributed in the hope that it will be useful,
89  but WITHOUT ANY WARRANTY; without even the implied warranty of
90  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
91  Lesser General Public License for more details.
92 
93  You should have received a copy of the GNU Lesser General Public
94  License along with this library; if not, write to the Free Software
95  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
96 */
97 // bool versus unsigned char
98 // on UNO, ESP8266 and ESP32 sizeof(bool) == 1 i.e. same size as unsigned char
99 // but bool is safer as bool + 1 does not compile
100 // however Arduino uses unsigned char as return value so...
101 #ifndef SafeString_class_h
102 #define SafeString_class_h
103 
104 
105 #ifdef __cplusplus
106 
107 #include <stdbool.h>
108 #include <stdlib.h>
109 #include <string.h>
110 #include <ctype.h>
111 
112 #if defined(ESP_PLATFORM) || defined(ARDUINO_ARCH_ESP8266)
113 #include <pgmspace.h>
114 #elif defined(ARDUINO_ARDUINO_NANO33BLE) || defined(ARDUINO_ARCH_MBED_RP2040)|| defined(ARDUINO_ARCH_RP2040)|| defined(ARDUINO_ARCH_MBED)
115 #include <api/deprecated-avr-comp/avr/pgmspace.h>
116 #else
117 #include <avr/pgmspace.h>
118 #endif
119 
120 #include <stdint.h>
121 #include <Print.h>
122 #include <Printable.h>
123 
124 // This include handles the rename of Stream for MBED compiles
125 #if defined(ARDUINO_ARDUINO_NANO33BLE) || defined(ARDUINO_ARCH_SAMD) || defined(ARDUINO_ARCH_MBED_RP2040) || defined(ARDUINO_ARCH_RP2040) || defined(ARDUINO_ARCH_MBED)
126 #include <Stream.h>
127 #elif defined( __MBED__ ) || defined( MBED_H )
128 #include <WStream.h>
129 #define Stream WStream
130 #else
131 #include <Stream.h>
132 #endif
133 
134 // handle namespace arduino
136 
137 // removed V4.1.29 -- Add these lines back in if your board does not define the F() macro and the class __FlashStringHelper;
138 //class __FlashStringHelper;
139 //#define F(string_literal) (reinterpret_cast<const __FlashStringHelper *>(PSTR(string_literal)))
140 
141 // to remove all the error messages, comment out
142 #define SSTRING_DEBUG
143 // this saves program bytes and the ram used by the SafeString object names
144 //
145 // Usually just leave as is and use SafeString::setOutput(..) to control the error messages and debug output
146 // there will be no error messages or debug output if SafeString::setOutput(..) has not been called from your sketch
147 //
148 // SafeString.debug() is always available regardless of the SSTRING_DEBUG define setting
149 // but SafeString::setOutput() still needs to be called to set where the output should go.
150 
151 /* ----------------- creating SafeStrings ---------------------------------
152  See the example sketches SafeString_ConstructorAndDebugging.ino and SafeStringFromCharArray.ino
153  and SafeStringFromCharPtr.ino and SafeStringFromCharPtrWithSize.ion
154 
155  createSafeString(name, size) and createSafeString(name, size, "initialText")
156  are utility macros to create an SafeString of a given name and size and optionally, an initial value
157 
158  createSafeString(str, 40); or cSF(str, 40);
159  expands in the pre-processor to
160  char str_SAFEBUFFER[40+1];
161  SafeString str(sizeof(str_SAFEBUFFER),str_SAFEBUFFER,"","str");
162 
163  createSafeString(str, 40, "test"); or cSF(str, 40, "test");
164  expands in the pre-processor to
165  char str_SAFEBUFFER[40+1];
166  SafeString str(sizeof(str_SAFEBUFFER),str_SAFEBUFFER,"test","str");
167 
168  createSafeStringFromCharArray(name, char[]); or cSFA(name, char[]);
169  wraps an existing char[] in a SafeString of the given name
170  e.g.
171  char charBuffer[15];
172  createSafeStringFromCharArray(str,charBuffer); or cSFA(str,charBuffer);
173  expands in the pre-processor to
174  SafeString str(sizeof(charBuffer),charBuffer, charBuffer, "str", true);
175 
176  createSafeStringFromCharPtr(name, char*); or cSFP(name, char*);
177  wraps an existing char[] pointed to by char* in a SafeString of the given name
178  e.g.
179  char charBuffer[15];
180  char *bufPtr = charBuffer;
181  createSafeStringFromCharPtr(str,bufPtr); or cSFP(str,bufPtr);
182  expands in the pre-processor to
183  SafeString str((unsigned int)-1,charBuffer, charBuffer, "str", true);
184  and the capacity of the SafeString is set to strlen(charBuffer) and cannot be increased.
185 
186  createSafeStringFromCharPtrWithSize(name, char*, unsigned int); or cSFPS(name, char*, unsigned int);
187  wraps an existing char[] pointed to by char* in a SafeString of the given name and sets the capacity to the given size -1
188  e.g.
189  char charBuffer[15];
190  char *bufPtr = charBuffer;
191  createSafeStringFromCharPtrWithSize(str,bufPtr, 15); or cSFPS(str,bufPtr, 15);
192  expands in the pre-processor to
193  SafeString str(15,charBuffer, charBuffer, "str", true);
194  The capacity of the SafeString is set to 14.
195 
196 ****************************************************************************************/
197 /* **************************************************
198  If str is a SafeString then
199  str = .. works for signed/unsigned ints, char*, char, F(".."), SafeString float, double etc
200  str.concat(..) and string.prefix(..) also works for those
201  str.stoken(..) can be used to split a string in to tokens
202 
203  SafeStrings created via createSafeString(..) or cSF(..) are never invalid, even if called with invalid arguments.
204  SafeStrings created via createSafeStringFromCharArray(..) or cSFA(..) are valid as long at the underlying char[] is valid
205  Usually the only way the char[] can become invalid is if it exists in a struct that is allocated (via calloc/malloc)
206  and then freed while the SafeString wrapping it is still in use.
207  SafeStrings created via createSafeStringFromCharPtr(..) or cSFP(..) are valid if the char[] pointed to is validly terminated
208  SafeStrings created via createSafeStringFromCharWithSize(..) or cSFPS(..) are valid if the char[] and size specified is valid.
209  For both createSafeStringFromCharPtr() and createSafeStringFromCharWithSize()
210  the SafeStrings created remain valid as long as the underlying char[] is valid.
211  Usually the only way the char[] can become invalid is if it was allocated (via calloc/malloc)
212  and then freed while the SafeString wrapping it is still in use.
213 * ***************************************************/
214 
215 
216 #ifdef SSTRING_DEBUG
217 #define createSafeString(name, size,...) char name ## _SAFEBUFFER[(size)+1]; SafeString name(sizeof(name ## _SAFEBUFFER),name ## _SAFEBUFFER, "" __VA_ARGS__ , #name);
218 #define createSafeStringFromCharArray(name, charArray) SafeString name(sizeof(charArray),charArray, charArray, #name, true, false);
219 #define createSafeStringFromCharPtr(name, charPtr) SafeString name((unsigned int)-1,charPtr, charPtr, #name, true);
220 #define createSafeStringFromCharPtrWithSize(name, charPtr, arraySize) SafeString name((arraySize),charPtr, charPtr, #name, true);
221 #else
222 #define createSafeString(name, size,...) char name ## _SAFEBUFFER[(size)+1]; SafeString name(sizeof(name ## _SAFEBUFFER),name ## _SAFEBUFFER, "" __VA_ARGS__);
223 #define createSafeStringFromCharArray(name,charArray) SafeString name(sizeof(charArray),charArray, charArray, NULL, true, false);
224 #define createSafeStringFromCharPtr(name, charPtr) SafeString name((unsigned int)-1,charPtr, charPtr, NULL, true);
225 #define createSafeStringFromCharPtrWithSize(name, charPtr, arraySize) SafeString name((arraySize),charPtr, charPtr, NULL, true);
226 #endif
227 
228 // define typing shortcuts
229 #define cSF createSafeString
230 #define cSFA createSafeStringFromCharArray
231 #define cSFP createSafeStringFromCharPtr
232 #define cSFPS createSafeStringFromCharPtrWithSize
233 
234 
306 class SafeString : public Printable, public Print {
307 
308  public:
309 
322 // When maxLen is neither (size_t)-1 nor 0 it is the actual size of the array, and capacity == maxLen-1
323 // if _fromBuffer false (i.e. cSF(sfStr,20); ) then maxLen is the capacity+1 and the macro allocates an char[20+1], (_fromPtr ignored)
324 // if _fromBuffer true and _fromPtr false (i.e. cSFA(sfStr, strArray); ) then maxLen is the sizeof the strArray and the capacity is maxLen-1, _fromPtr is false
325 // if _fromBuffer true and _fromPtr true, then from char*, (i.e. cSFP(sfStr,strPtr) or cSFPS(sfStr,strPtr, maxLen)
326 // if maxLen == (size_t)-1 then capacity == strlen(char*) i.e. cSFP( ). This is the ONLY case that uses strlen()
327 // else if maxLen == 0 then it is an ERROR, cSFPS( ) was passed an array size of 0. capacity is set to 0
328 // else capacity == maxLen-1; i.e. cSFPS( )
329 // maxLen == 0, or (size_t)-1, when NOT from a char* (i.e. cSF( ) or cSFA( )) is an ERROR, a zero length
330 // array. capacity is set to 0. Note: cSF( ) cannot produce maxLen == 0, its macro always passes size+1
331  explicit SafeString(unsigned int maxLen, char *buf, const char* cstr, const char* _name = NULL, bool _fromBuffer = false, bool _fromPtr = true);
332  // _fromBuffer true does extra checking before each method execution for SafeStrings created from existing char[] buffers
333  // _fromPtr is not checked unless _fromBuffer is true
334  // _fromPtr true allows for any array size, if false prevents passing char* by checking sizeof(charArray) != sizeof(char*)
335 
336  // SafeString inherits virtual functions from Print/Printable so it is a polymorphic type.
337  // A virtual destructor is required to avoid -Wdelete-non-virtual-dtor warnings when
338  // deleting heap-allocated SafeString (or SafeStringReader) objects via a base-class pointer.
339  virtual ~SafeString() {}
340 
341  private: // to force compile errors if function definition of the SafeString argument is not a refernce, i.e. not SafeString&
342  SafeString(const SafeString& other ); // You must declare SafeStrings function arguments as a reference, SafeString&, e.g. void test(SafeString& strIn)
343  // NO other constructors, NO conversion constructors
344 
345  public:
346 
353  static void setOutput(Print& debugOut, bool verbose = true);
354  // static SafeString::DebugPrint Output; // a Print object controlled by setOutput() / turnOutputOff() is defined at the bottom
355 
356 
361  static void turnOutputOff(void); // call this to turn all debugging OFF, both error messages AND debug( ) method output
362 
363  // use this to control error messages verbose output
364 
369  static void setVerbose(bool verbose); // turn verbose error msgs on/off. setOutput( ) sets verbose to true
370 
371  // returns true if error detected, errors are detected even is setOutput has not been called
372  // each call to hasError() clears the errorFlag
373 
376  unsigned char hasError();
377 
378  // returns true if error detected in any SafeString object, errors are detected even is setOutput has not been called
379  // each call to errorDetected() clears the classErrorFlag
380 
383  static unsigned char errorDetected();
384 
385  // these methods print out info on this SafeString object, iff setOutput has been called
386  // setVerbose( ) does NOT effect these methods which have their own verbose argument
387  // Each of these debug( ) methods defaults to outputing the string contents. Set the optional verbose argument to false to suppress outputing string contents
388  // NOTE!! all these debug methods return a pointer to an empty string.
389  // This is so that if you add .debug() to Serial.println(str); i.e. Serial.println(str.debug()) will work as expected
390 
395  const char* debug(bool verbose = true);
396 
397 
403  const char* debug(const char* title, bool verbose = true);
404 
405 
411  const char* debug(const __FlashStringHelper *title, bool verbose = true);
412 
413 
419  const char* debug(SafeString &stitle, bool verbose = true);
420 
421 
428  virtual size_t write(uint8_t b);
429  // writes at most length chars to this SafeString,
430  // NOTE: write(cstr,length) will set hasError and optionally output errorMsg, if strlen(cstr) < length and nothing will be added to the SafeString
431 
432 
440  virtual size_t write(const uint8_t *buffer, size_t length);
441 
442 
447  size_t printTo(Print& p) const;
448 
449  // reserve returns 0 if _capacity < size
450 
455  unsigned char reserve(unsigned int size);
456 
457 
460  unsigned int length(void);
461 
462 
465  unsigned int capacity(void);
466 
467 
470  unsigned char isFull(void);
471 
472 
475  unsigned char isEmpty(void);
476 
477 
480  int availableForWrite(void);
481 
482 
488  SafeString & clear(void);
489 
490  public:
491  // support for print
492  size_t print(unsigned char, int = DEC);
493  size_t print(int, int = DEC);
494  size_t print(unsigned int, int = DEC);
495  size_t print(long, int = DEC);
496  size_t print(unsigned long, int = DEC);
497  size_t print(int64_t, int = DEC);
498  size_t print(double, int = 2);
499  size_t print(const __FlashStringHelper *);
500  size_t print(const char*);
501  size_t print(char);
502  size_t print(SafeString &str);
503 
504  size_t println(unsigned char, int = DEC);
505  size_t println(int, int = DEC);
506  size_t println(unsigned int, int = DEC);
507  size_t println(long, int = DEC);
508  size_t println(unsigned long, int = DEC);
509  size_t println(int64_t, int = DEC);
510  size_t println(double, int = 2);
511  size_t println(const __FlashStringHelper *);
512  size_t println(const char*);
513  size_t println(char);
514  size_t println(SafeString &str);
515  size_t println(void);
516 
517  // ********** special prints padding and formatting doubles (longs) **************
518  // print to SafeString a double (or long) with decs after the decimal point and padd to specified width
519  // width is a signed value, negative for left adjustment, +ve for right padding
520  // by default the + sign is not added, set forceSign argument to true to force the display of the + sign
521  //
522  // If the result exceeds abs(width), reduce the decs after the decmial point to fit into width
523  // If result with decs reduced to 0 is still > abs(width) raise an error and ,optionally, output an error msg
524  //
525  // Note decs is quietly limited in this method to 7 digits after the decimal point, i.e. if (decs > 7) decs = 7;
526 
527 
537  size_t println(double d, int decs, int width, bool forceSign = false);
538 
539 
549  size_t print(double d, int decs, int width, bool forceSign = false);
550 
551 
552 
553  // Assignment operators **********************************
554  // Set the SafeString to a char version of the assigned value.
555  // For = (const char *) the contents are copied to the SafeString buffer
556  // if the value is null or invalid,
557  // or too large to be fit in the string's internal buffer
558  // the string will be left empty
559 
560 
568 
569 
576  SafeString & operator = (unsigned char num);
577 
578 
586 
587 
594  SafeString & operator = (unsigned int num);
595 
596 
603  SafeString & operator = (long num);
604 
605 
612  SafeString & operator = (unsigned long num);
613 
614 
621  SafeString & operator = (int64_t num);
622 
623 
630  SafeString & operator = (float num);
631 
632 
639  SafeString & operator = (double num);
640 
641 
649 
650 
657  SafeString & operator = (const char *cstr);
658 
659 
666  SafeString & operator = (const __FlashStringHelper *pstr); // handle F(" .. ") values
667 
668 
677  SafeString & prefix(const char *cstr);
678  SafeString & prefix(char c);
679  SafeString & prefix(unsigned char c);
680  SafeString & prefix(int num);
681  SafeString & prefix(unsigned int num);
682  SafeString & prefix(long num);
683  SafeString & prefix(unsigned long num);
684  SafeString & prefix(int64_t num);
685  SafeString & prefix(float num);
686  SafeString & prefix(double num);
687  SafeString & prefix(const __FlashStringHelper * str);
688  SafeString & prefix(const char *cstr, size_t length);
689  SafeString & prefix(const __FlashStringHelper * str, size_t length);
690 
691 
700  SafeString & concat(const char *cstr);
701  SafeString & concat(char c);
702  SafeString & concat(unsigned char c);
703  SafeString & concat(int num);
704  SafeString & concat(unsigned int num);
705  SafeString & concat(long num);
706  SafeString & concat(unsigned long num);
707  SafeString & concat(int64_t num);
708  SafeString & concat(float num);
709  SafeString & concat(double num);
710  SafeString & concat(const __FlashStringHelper * str);
711  // ------------------------------------------------------
712  // no corresponding methods these three (3) in prefix, +=, -+
713 
714  SafeString & concat(const char *cstr, size_t length); // concat at most length chars from cstr
715  // NOTE: concat(cstr,length) will set hasError and optionally output errorMsg, if strlen(cstr) < length and nothing will be concatinated.
716 
717  SafeString & concat(const __FlashStringHelper * str, size_t length); // concat at most length chars
718 
719 
724  SafeString & newline(); // append newline \r\n same as concat("\r\n"); same a println()
725  // e.g. sfStr.concat("test").newline();
726 
727  /* prefix() operator -= ******************
728  Operator version of prefix( )
729  prefix -=
730  To cascade operators use ( )
731  e.g. (sfStr -= 'a') -= 5;
732  **/
733 
741  return prefix(rhs);
742  }
743  SafeString & operator -= (const char *cstr) {
744  return prefix(cstr);
745  }
747  return prefix(c);
748  }
749  SafeString & operator -= (unsigned char num) {
750  return prefix(num);
751  }
753  return prefix(num);
754  }
755  SafeString & operator -= (unsigned int num) {
756  return prefix(num);
757  }
758  SafeString & operator -= (long num) {
759  return prefix(num);
760  }
761  SafeString & operator -= (unsigned long num) {
762  return prefix(num);
763  }
764  SafeString & operator -= (int64_t num) {
765  return prefix(num);
766  }
767  SafeString & operator -= (float num) {
768  return prefix(num);
769  }
770  SafeString & operator -= (double num) {
771  return prefix(num);
772  }
773  SafeString & operator -= (const __FlashStringHelper *str) {
774  return prefix(str);
775  }
776 
777  /* concat() operator += ******************
778  Operator versions of concat( )
779  suffix/append +=
780  To cascade operators use ( )
781  e.g. (sfStr += 'a') += 5;
782  **/
783 
791  return concat(rhs);
792  }
793  SafeString & operator += (const char *cstr) {
794  return concat(cstr);
795  }
797  return concat(c);
798  }
799  SafeString & operator += (unsigned char num) {
800  return concat(num);
801  }
803  return concat(num);
804  }
805  SafeString & operator += (unsigned int num) {
806  return concat(num);
807  }
808  SafeString & operator += (long num) {
809  return concat(num);
810  }
811  SafeString & operator += (unsigned long num) {
812  return concat(num);
813  }
814  SafeString & operator += (int64_t num) {
815  return concat(num);
816  }
817  SafeString & operator += (float num) {
818  return concat(num);
819  }
820  SafeString & operator += (double num) {
821  return concat(num);
822  }
823  SafeString & operator += (const __FlashStringHelper *str) {
824  return concat(str);
825  }
826 
827  /* Comparision methods and operators ******************
828  comparisons only work with SafeStrings and "strings"
829  These methods used to be ... const {
830  but now with createSafeStringFromBuffer( ) the SafeString may be modified by cleanUp()
831  **/
832 
836 
839  int compareTo(const char *cstr) ;
840 
841  unsigned char equals(SafeString &s) ;
842  unsigned char equals(const char *cstr) ;
843  unsigned char equals(const char c) ;
844  unsigned char operator == (SafeString &rhs) {
845  return equals(rhs);
846  }
847  unsigned char operator == (const char *cstr) {
848  return equals(cstr);
849  }
850  unsigned char operator == (const char c) {
851  return equals(c);
852  }
853  unsigned char operator != (SafeString &rhs) {
854  return !equals(rhs);
855  }
856  unsigned char operator != (const char *cstr) {
857  return !equals(cstr);
858  }
859  unsigned char operator != (const char c) {
860  return !equals(c);
861  }
862  unsigned char operator < (SafeString &rhs) {
863  return compareTo(rhs) < 0;
864  }
865  unsigned char operator > (SafeString &rhs) {
866  return compareTo(rhs) > 0;
867  }
868  unsigned char operator <= (SafeString &rhs) {
869  return compareTo(rhs) <= 0;
870  }
871  unsigned char operator >= (SafeString &rhs) {
872  return compareTo(rhs) >= 0;
873  }
874  unsigned char operator < (const char* rhs) {
875  return compareTo(rhs) < 0;
876  }
877  unsigned char operator > (const char* rhs) {
878  return compareTo(rhs) > 0;
879  }
880  unsigned char operator <= (const char* rhs) {
881  return compareTo(rhs) <= 0;
882  }
883  unsigned char operator >= (const char* rhs) {
884  return compareTo(rhs) >= 0;
885  }
886  unsigned char equalsIgnoreCase(SafeString &s) ;
887  unsigned char equalsIgnoreCase(const char *str2) ;
888 
889  unsigned char equalsConstantTime(SafeString &s) ;
890 
891  /* startsWith methods *******************
892  The fromIndex is offset into this SafeString where check is to start
893  0 to length() and (unsigned int)(-1) are valid for fromIndex, if fromIndex == length() or -1 false is returned
894  if the argument is null or fromIndex > length(), an error is flagged and false returned
895  **/
902  unsigned char startsWith(const char c, unsigned int fromIndex = 0);
909  unsigned char startsWith( const char *str2, unsigned int fromIndex = 0) ;
916  unsigned char startsWith(SafeString &s2, unsigned int fromIndex = 0) ;
917 
924  unsigned char startsWithIgnoreCase(const char c, unsigned int fromIndex = 0);
931  unsigned char startsWithIgnoreCase( const char *str2, unsigned int fromIndex = 0) ;
938  unsigned char startsWithIgnoreCase( SafeString &s2, unsigned int fromIndex = 0) ;
939 
940  /* endsWith methods *******************/
946  unsigned char endsWith(const char c);
952  unsigned char endsWith(SafeString &suffix) ;
958  unsigned char endsWith(const char *suffix) ;
964  unsigned char endsWithCharFrom(SafeString &suffix) ;
970  unsigned char endsWithCharFrom(const char *suffix) ;
971 
972  /* character acccess methods *******************
973  NOTE: There is no access to modify the underlying char buffer directly
974  For these methods 0 to length()-1 is valid for index
975  index greater than length() -1 will return 0 and set the error flag and will print errors if debug enabled
976  **/
984  char charAt(unsigned int index) ; // if index >= length() returns 0 and prints a error msg
992  char operator [] (unsigned int index) ; // if index >= length() returns 0 and prints a error msg
993 
994  // setting a char in the SafeString
995  // str[..] = c; is not supported because it allows direct access to modify the underlying char buffer
1002  void setCharAt(unsigned int index, char c); //if index >= length() the error flag is set
1003  // calls to setCharAt(length(), ..) and setCharAt(.. , '\0') are ignored and error flag is set
1004 
1005  // returning the underlying buffer
1006  // returned as a const and should not be changesdor recast to a non-const
1011  const char* c_str();
1012 
1013 
1014  /* search methods *******************
1015  Arrays are indexed by a unsigned int variable
1016  See the SafeStringIndexOf.ino example sketch
1017  All indexOf methods return -1 if not found
1018  **********************************************/
1019  // The fromIndex is offset into this SafeString where to start searching (inclusive)
1020  // 0 to length() and -1 is valid for fromIndex
1021  // if fromIndex > length(), than the error flag is set and -1 returned and prints an error if debug enabled
1022  // if fromIndex == (unsigned int)(-1) -1 is returned without error.
1023  /*
1024  returns the index
1025  */
1026  //int indexOf( char ch ) ;
1034  int indexOf( char ch, unsigned int fromIndex = 0) ;
1035  //int indexOf( SafeString & str ) ;
1036  //int indexOf( const char* str ) ;
1043  int indexOf(const char* str , unsigned int fromIndex = 0) ;
1050  int indexOf( SafeString & str, unsigned int fromIndex = 0 ) ;
1051 
1057  int lastIndexOf( char ch ) ;
1058 
1065  int lastIndexOf( char ch, unsigned int fromIndex) ;
1066 
1072  int lastIndexOf( SafeString & str ) ;
1079  int lastIndexOf( SafeString & str, unsigned int fromIndex) ;
1080 
1086  int lastIndexOf( const char *cstr ) ;
1087 
1094  int lastIndexOf(const char* cstr, unsigned int fromIndex);
1095 
1096  // first index of the chars listed in chars string
1097  // loop through chars and look for index of each and return the min index or -1 if none found
1098  //int indexOfCharFrom(SafeString & str);
1099  //int indexOfCharFrom(const char* chars);
1100  // start searching from fromIndex
1107  int indexOfCharFrom(SafeString & str, unsigned int fromIndex = 0);
1108 
1115  int indexOfCharFrom(const char* chars, unsigned int fromIndex = 0);
1116 
1117  /* *** utf8 methods ************/
1118  // For endIdx <= length(), utf8index returns an index in the range endIdx-3 to endIdx
1119  // such that using that index for substring will not split a valid utf8 code point
1120  // if endIdx > length(), endIdx is set to length(); and the error flag is set
1121  // endIdx == (unsigned int)(-1) is treated as endIdx == length() returns a result without an error
1122  //Code Points 1st-Byte 2nd-Byte 3rd-Byte 4th-Byte
1123  //U+0000..U+007F 00..7F
1124  //U+0080..U+07FF C2..DF 80..BF
1125  //U+0800..U+0FFF E0 A0..BF 80..BF
1126  //U+1000..U+CFFF E1..EC 80..BF 80..BF
1127  //U+D000..U+D7FF ED 80..9F 80..BF
1128  //U+E000..U+FFFF EE..EF 80..BF 80..BF
1129  //U+10000..U+3FFFF F0 90..BF 80..BF 80..BF
1130  //U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
1131  //U+100000..U+10FFFF F4 80..8F 80..BF 80..BF
1132 
1149  int utf8index(unsigned int endIdx);
1150 
1151 
1152  // For startIdx < length(), utf8nextIndex returns an index in the range startIdx+1 to startIdx+4
1153  // such that using that index for substring will not split a valid utf8 code point
1154  // if startIdx > length(), (unsigned int)(-1) will be returned and the error flag is set
1155  // if startIdx == (unsigned int)(-1), OR startIdx == length(), (unsigned int)(-1) will be returned with no error
1173  int utf8nextIndex(unsigned int startIdx);
1174 
1175  /* *** substring methods ************/
1176  // substring is from beginIdx to end of string
1177  // The result substring is ALWAYS first cleared by this method so it will be empty on errors
1178  // if beginIdx = length(), an empty result will be returned without error
1179  // if beginIdx > length(), an empty result will be returned with error flag set on both this SafeString and the result SafeString
1180  // beginIdx == (unsigned int)(-1) returns an empty result without an error
1181  // You can take substring of yourself e.g. str.substring(str,3);
1182  // if result does not have the capacity to hold the substring, hasError() is set on both this SafeString and the result SafeString
1183 
1199  SafeString & substring(SafeString & result, unsigned int beginIdx);
1200 
1201  // The result substring is ALWAYS first cleared by this method so it will be empty on errors
1202  // if beginIdx = length(), an empty result will be returned without error
1203  // if beginIdx > length(), an empty result will be returned with error flag set on both this SafeString and the result SafeString
1204  // if beginIdx > endIdx, beginIdx and endIdx will be swapped so that beginIdx <= endIdx and the error flag is set on both this SafeString and the result SafeString
1205  // if endIdx > length(), endIdx is set to length(); and the error flag is set on both this SafeString and the result SafeString
1206  // endIdx == (unsigned int)(-1) is treated as endIdx == length() returns a result without an error
1207  // substring is from beginIdx to endIdx-1, endIdx is exclusive
1208  // You can take substring of yourself e.g. str.substring(str,3,6);
1209  // if result does not have the capacity to hold the substring, and empty result is returned and hasError() is set on both this SafeString and the result SafeString
1228  SafeString & substring(SafeString & result, unsigned int beginIdx, unsigned int endIdx);
1229 
1230  /* *** SafeString modification methods ************/
1231 
1232  /* *** replace ************/
1238  void replace(char findChar, char replaceChar);
1239 
1245  void replace(const char findChar, const char *replaceStr);
1246 
1252  void replace(const char findChar, SafeString& sfReplace);
1253 
1259  void replace(const char* findStr, const char *replaceStr);
1260 
1266  void replace(SafeString & sfFind, SafeString & sfReplace);
1267 
1268  /* *** remove ************/
1269  // remove from index to end of SafeString
1270  // 0 to length() and (unsigned int)(-1) are valid for index,
1271  // -1 => length() for processing and just returns without error
1278  void removeFrom(unsigned int startIndex);
1279 
1280  // remove from 0 to startIdx (excluding startIdx)
1281  // 0 to length() and (unsigned int)(-1) are valid for index,
1282  // -1 => length() for processing
1289  void removeBefore(unsigned int startIndex);
1290 
1291  // remove from index to end of SafeString
1292  // 0 to length() and (unsigned int)(-1) are valid for index,
1293  // -1 => length() for processing and just returns without error
1300  void remove(unsigned int index);
1301 
1302  // remove count chars starting from index
1303  // 0 to length() and unsigned int(-1) are valid for index
1304  // -1 just returns without error
1305  // 0 to (length()- index) is valid for count, larger values set the error flag and remove from idx to end of string
1314  void remove(unsigned int index, unsigned int count);
1315 
1316  // remove the last 'count' chars
1317  // 0 to length() is valid for count,
1318  // count >= length() clears the SafeString
1319  // count > length() set the error flag
1327  void removeLast(unsigned int count);
1328 
1329  // keep last 'count' number of chars remove the rest
1330  // 0 to length() is valid for count, passing in count == 0 clears the SafeString
1331  // count > length() sets error flag and returns SafeString unchanged
1339  void keepLast(unsigned int count);
1340 
1341 
1342  /* *** change case ************/
1346  void toLowerCase(void);
1350  void toUpperCase(void);
1351 
1352  /* *** remove white space from front and back of SafeString ************/
1353  // the method isspace( ) is used to. For the 'C' local the following are trimmed
1354  // ' ' (0x20) space (SPC)
1355  // '\t' (0x09) horizontal tab (TAB)
1356  // '\n' (0x0a) newline (LF)
1357  // '\v' (0x0b) vertical tab (VT)
1358  // '\f' (0x0c) feed (FF)
1359  // '\r' (0x0d) carriage return (CR)
1371  void trim(void); // trims front and back
1372 
1373  // processBackspaces recursively remove backspaces, '\b' and the preceeding char
1374  // use for processing inputs from terminal (Telent) connections
1380  void processBackspaces(void);
1381 
1382  /* *** numgber parsing/conversion ************/
1383  // convert numbers
1384  // If the SafeString is a valid number update the argument with the result
1385  // else leave the argument unchanged
1386  // SafeString conversions are stricter than the Arduino String version
1387  // trailing chars can only be white space
1394  unsigned char toInt(int & i) ;
1395 
1402  unsigned char toInt64_t(int64_t &l) ;
1403 
1410  unsigned char toLong(long & l) ;
1411 
1418  unsigned char binToLong(long & l) ;
1425  unsigned char octToLong(long & l) ;
1432  unsigned char hexToLong(long & l) ;
1439  unsigned char toUnsignedLong(unsigned long & l) ;
1446  unsigned char binToUnsignedLong(unsigned long & l) ;
1453  unsigned char octToUnsignedLong(unsigned long & l) ;
1460  unsigned char hexToUnsignedLong(unsigned long & l) ;
1467  unsigned char toFloat(float & f) ;
1474  unsigned char toDouble(double & d) ;
1475 
1476  // float toFloat(); possible alternative
1477 
1478  /* Tokenizeing methods, stoken(), nextToken()/firstToken() ************************/
1479  /* Differences between stoken() and nextToken
1480  stoken() leaves the SafeString unchanged, nextToken() removes the token (and leading delimiters) from the SafeString giving space to add more input
1481  In stoken() the end of the SafeString is always treated as a delimiter, i.e. the last token is returned even if it is not followed by one of the delimiters
1482  In nextToken() the end of the SafeString is a delimiter by default, but setting returnLastNonDelimitedToken = false will leave last token that is not terminated in the SafeString
1483  Setting returnLastNonDelimitedToken = false this allows partial tokens to be read from a Stream and kept until the full token and delimiter is read
1484  */
1485  /*
1486  stoken -- The SafeString itself is not changed
1487  stoken breaks into the SafeString into tokens using chars in delimiters string and the end of the SafeString as delimiters.
1488  Any leading delimiters are first stepped over and then the delimited token is return in the token argument (less the delimiter).
1489  The token argument is always cleared at the start of the stoken().
1490  if there are any argument errors or the token does not have the capacity to hold the substring, hasError() is set on both this SafeString and the token SafeString
1491 
1492  params
1493  token - the SafeString to return the token in, it is cleared if no delimited token found or if there are errors
1494  The found delimited token (less the delimiter) is returned in the token SafeString argument if there is capacity.
1495  The token's capacity should be >= this SafeString's capacity incase the entire SafeString needs to be returned.
1496  If the token's capacity is < the next token, then token is returned empty and an error messages printed if debug is enabled.
1497  In this case the return (nextIndex) is still updated.
1498  fromIndex -- where to start the search from 0 to length() and -1 is valid for fromIndex, -1 => length() for processing
1499  delimiters - the characters that any one of which can delimit a token. The end of the SafeString is always a delimiter.
1500  returnEmptyFields -- default false, if true only skip one leading delimiter after each call. If the fromIndex is 0 and there is a delimiter at the beginning of the SafeString, an empty token will be returned
1501  useAsDelimiters - default true, if false then token consists only of chars in the delimiters and any other char terminates the token
1502 
1503  return -- nextIndex, the next index in this SafeString after the end of the token just found, -1 if this is the last token
1504  Use this as the fromIndex for the next call
1505  NOTE: if there are no delimiters then -1 is returned and the whole SafeString returned in token if the SafeString token argument is large enough
1506  If the token's capacity is < the next token, the token returned is empty and an error messages printed if debug is enabled.
1507  In this case the returned nextIndex is still updated to end of the token just found so that that the program will not be stuck in an infinite loop testing for nextIndex >=0
1508  while being consistent with the SafeString's all or nothing insertion rule
1509 
1510  Input argument errors return -1 and an empty token and hasError() is set on both this SafeString and the token SafeString.
1511  **/
1512 
1539  int stoken(SafeString & token, unsigned int fromIndex, const char delimiter, bool returnEmptyFields = false, bool useAsDelimiters = true);
1540 
1567  int stoken(SafeString & token, unsigned int fromIndex, const char* delimiters, bool returnEmptyFields = false, bool useAsDelimiters = true);
1568 
1595  int stoken(SafeString & token, unsigned int fromIndex, SafeString & delimiters, bool returnEmptyFields = false, bool useAsDelimiters = true);
1596 
1622  inline unsigned char firstToken(SafeString & token, char delimiter, bool returnLastNonDelimitedToken = true) {
1623  return nextToken(token,delimiter,true,returnLastNonDelimitedToken,true);
1624  }
1625 
1656  unsigned char nextToken(SafeString & token, char delimiter, bool returnEmptyFields = false, bool returnLastNonDelimitedToken = true, bool firstToken = false);
1657 
1683  inline unsigned char firstToken(SafeString & token, SafeString & delimiters, bool returnLastNonDelimitedToken = true) {
1684  return nextToken(token,delimiters,true,returnLastNonDelimitedToken,true);
1685  }
1686 
1717  unsigned char nextToken(SafeString & token, SafeString & delimiters, bool returnEmptyFields = false, bool returnLastNonDelimitedToken = true, bool firstToken = false);
1718 
1744  inline unsigned char firstToken(SafeString & token, const char* delimiters, bool returnLastNonDelimitedToken = true) {
1745  return nextToken(token,delimiters,true,returnLastNonDelimitedToken,true);
1746  }
1747 
1778  unsigned char nextToken(SafeString & token, const char* delimiters, bool returnEmptyFields = false, bool returnLastNonDelimitedToken = true, bool firstToken = false);
1779 
1780 
1781  /* *** ReadFrom from SafeString, writeTo SafeString ************************/
1797  unsigned int readFrom(SafeString & sfInput, unsigned int startIdx = 0);
1798 
1812  unsigned int readFrom(const char* strPtr, unsigned int maxCharsToRead = ((unsigned int)-1));
1813 
1826  unsigned int writeTo(SafeString & output, unsigned int startIdx = 0);
1827 
1828  /* *** NON-blocking reads from Stream ************************/
1829 
1839  unsigned char read(Stream & input);
1840 
1852  unsigned char readUntil(Stream & input, const char delimiter);
1864  unsigned char readUntil(Stream & input, const char* delimiters);
1876  unsigned char readUntil(Stream & input, SafeString & delimiters);
1877 
1905  unsigned char readUntilToken(Stream & input, SafeString & token, const char delimiter, bool & skipToDelimiter, uint8_t echoInput = false, unsigned long timeout_ms = 0);
1906 
1934  unsigned char readUntilToken(Stream & input, SafeString & token, const char* delimiters, bool & skipToDelimiter, uint8_t echoInput = false, unsigned long timeout_ms = 0);
1935 
1963  unsigned char readUntilToken(Stream & input, SafeString & token, SafeString & delimiters, bool & skipToDelimiter, uint8_t echoInput = false, unsigned long timeout_ms = 0);
1964 
1971  size_t getLastReadCount();
1972 
1973  /* *** END OF PUBLIC METHODS ************/
1974 
1975  protected:
1976  static Print* debugPtr;
1977  static bool fullDebug;
1978  char *buffer; // the actual char array
1979  size_t _capacity; // the array length minus one (for the '\0')
1980  size_t len; // the SafeString length (not counting the '\0')
1981 
1982  class noDebugPrint : public Print {
1983  public:
1984  inline size_t write(uint8_t b) {
1985  (void)(b);
1986  return 0;
1987  }
1988  inline size_t write(const uint8_t *buffer, size_t length) {
1989  (void)(buffer);
1990  (void)(length);
1991  return 0;
1992  };
1993  void flush() { }
1994  };
1995 
1997 
1998  static Print* currentOutput;// = &emptyPrint;
1999 
2000  class DebugPrint : public Print {
2001  public:
2002  size_t write(uint8_t b) {
2003  return currentOutput->write(b);
2004  }
2005  size_t write(const uint8_t *buffer, size_t length) {
2006  return currentOutput->write(buffer, length);
2007  };
2008  void flush() {
2009 #if defined(ESP_PLATFORM) || defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_ARCH_NRF5) || defined(ARDUINO_SAM_DUE) || defined(ARDUINO_ARCH_STM32F1) || defined(ARDUINO_ARCH_STM32F4) || defined(ARDUINO_NRF52832_FEATHER) || defined(MEGATINYCORE_MAJOR)
2010  // ESP32 has no flush in Print!! but ESP8266 has
2011 #else
2012  currentOutput->flush();
2013 #endif
2014  }
2015  };
2016 
2017  public:
2018  static SafeString::DebugPrint Output; // a Print object controlled by setOutput() / turnOutputOff()
2019 
2020  protected:
2021  SafeString & concatln(const __FlashStringHelper * pstr);
2023  SafeString & concatln(const char *cstr, size_t length);
2024  void outputName() const ;
2025  SafeString & concatInternal(const char *cstr, size_t length, bool assignOp = false); // concat at most length chars from cstr
2026  SafeString & concatInternal(const __FlashStringHelper * str, size_t length, bool assignOp = false); // concat at most length chars
2027 
2028  SafeString & concatInternal(const char *cstr, bool assignOp = false);
2029  SafeString & concatInternal(char c, bool assignOp = false);
2030  SafeString & concatInternal(const __FlashStringHelper * str, bool assignOp = false);
2031  size_t printInternal(long, int = DEC, bool assignOp = false);
2032  size_t printInternal(unsigned long, int = DEC, bool assignOp = false);
2033  size_t printInternal(double, int = 2, bool assignOp = false);
2034  size_t printInternal(int64_t num, int base = 2, bool assignOp = false);
2035 
2036  void setError();
2037  void printlnErr()const ;
2038  void debugInternalMsg(bool _fullDebug) const ;
2039  size_t limitedStrLen(const char* p, size_t limit);
2040  size_t printInt(double d, int decs, int width, bool forceSign, bool addNL);
2041 
2042  private:
2043  bool readUntilTokenInternal(Stream & input, SafeString & token, const char* delimitersIn, char delimiterIn, bool & skipToDelimiter, uint8_t echoInput, unsigned long timeout_ms);
2044  bool readUntilInternal(Stream & input, const char* delimitersIn, char delimiterIn);
2045  bool nextTokenInternal(SafeString & token, const char* delimitersIn, char delimiterIn, bool returnEmptyFields, bool returnLastNonDelimitedToken);
2046  int stokenInternal(SafeString &token, unsigned int fromIndex, const char* delimitersIn, char delimiterIn, bool returnEmptyFields, bool useAsDelimiters);
2047  bool fromBuffer; // true if createSafeStringFromBuffer created this object
2048  bool errorFlag; // set to true if error detected, cleared on each call to hasError()
2049  static bool classErrorFlag; // set to true if any error detected in any SafeString, cleared on each call to SafeString::errorDetected()
2050  void cleanUp(); // reterminates buffer at capacity and resets len to current strlen
2051  const char *name;
2052  unsigned long timeoutStart_ms;
2053  bool timeoutRunning;
2054  size_t noCharsRead; // number of char read on last call to readUntilToken
2055  static char nullBufferSafeStringBuffer[1];
2056  static char emptyDebugRtnBuffer[1];
2057  void debugInternal(bool _fullDebug) const ;
2058  void debugInternalResultMsg(bool _fullDebug) const ;
2059  void baseError(const __FlashStringHelper * methodName, int base) const ;
2060  void concatErr()const ;
2061  void concatAssignError() const;
2062  void prefixErr()const ;
2063  void capError(const __FlashStringHelper * methodName, size_t neededCap, const char* cstr, const __FlashStringHelper *pstr = NULL, char c = '\0', size_t length = 0)const ;
2064  void assignError(size_t neededCap, const char* cstr, const __FlashStringHelper *pstr = NULL, char c = '\0', bool numberFlag = false) const;
2065  void errorMethod(const __FlashStringHelper * methodName) const ;
2066  void warningMethod(const __FlashStringHelper * methodName) const ;
2067  void assignErrorMethod() const ;
2068  void outputFromIndexIfFullDebug(unsigned int fromIndex) const ;
2069  int64_t strto_int64_t(const char *nptr, char **endptr, int base);
2070 };
2071 
2072 #include "SafeStringNameSpaceEnd.h"
2073 
2074 #endif // __cplusplus
2075 #endif // SafeString_class_h
size_t write(const uint8_t *buffer, size_t length)
Definition: SafeString.h:2005
size_t write(uint8_t b)
Definition: SafeString.h:2002
size_t write(uint8_t b)
Definition: SafeString.h:1984
size_t write(const uint8_t *buffer, size_t length)
Definition: SafeString.h:1988
To create SafeStrings use one of the four (4) macros createSafeString or cSF, createSafeStringFromCha...
Definition: SafeString.h:306
int stoken(SafeString &token, unsigned int fromIndex, const char delimiter, bool returnEmptyFields=false, bool useAsDelimiters=true)
break into the SafeString into tokens using the char delimiter, the end of the SafeString is always a...
size_t getLastReadCount()
returns the number of chars read on previous calls to read, readUntil or readUntilToken (includes '\0...
size_t print(const __FlashStringHelper *)
int indexOfCharFrom(const char *chars, unsigned int fromIndex=0)
returns the first index of any char from the argument
static void setOutput(Print &debugOut, bool verbose=true)
Turns on Error msgs and debug( ) output for all SafeStrings.
SafeString & operator=(char c)
Clears this SafeString and concatinates a single char.
unsigned char endsWith(SafeString &suffix)
returns non-zero of this SafeString ends with the argument
SafeString & concatln(const __FlashStringHelper *pstr)
const char * debug(SafeString &stitle, bool verbose=true)
Output the details about the this SafeString to the output specified by setOutput().
static unsigned char errorDetected()
Returns non-zero if any SafeString has detected and error, each call clears the internal global stati...
size_t print(unsigned char, int=DEC)
SafeString & prefix(const __FlashStringHelper *str, size_t length)
unsigned char equalsConstantTime(SafeString &s)
int availableForWrite(void)
Returns the number chars that can be added to this SafeString before it is full.
SafeString & prefix(long num)
SafeString & prefix(unsigned long num)
SafeString & prefix(int num)
virtual ~SafeString()
Definition: SafeString.h:339
unsigned char hasError()
Returns non-zero if any error detected for this SafeString, each call clears the internal flag.
void printlnErr() const
SafeString(unsigned int maxLen, char *buf, const char *cstr, const char *_name=NULL, bool _fromBuffer=false, bool _fromPtr=true)
SafeString Constructor called from the four (4) macros createSafeString or cSF, createSafeStringFromC...
void debugInternalMsg(bool _fullDebug) const
unsigned char toUnsignedLong(unsigned long &l)
convert the SafeString to an unsigned long.
unsigned char isFull(void)
Returns non-zero if the SafeString is full.
unsigned char readUntil(Stream &input, const char *delimiters)
reads chars into this SafeString until either it is full OR a delimiter is read OR there are no more ...
SafeString & prefix(double num)
unsigned char read(Stream &input)
reads from the Stream (if chars available) into the SafeString.
static void turnOutputOff(void)
Turns off all debugging messages, both error messages AND debug() method output.
SafeString & concatInternal(const char *cstr, size_t length, bool assignOp=false)
static SafeString::DebugPrint Output
Definition: SafeString.h:2018
void replace(const char *findStr, const char *replaceStr)
replace the findStr string with the replace string
void remove(unsigned int index)
remove all chars from index to the end of the SafeString (inclusive)
unsigned char toDouble(double &d)
convert the SafeString to a float assuming the SafeString in the decimal format (not scientific)
unsigned char equalsIgnoreCase(SafeString &s)
int lastIndexOf(char ch, unsigned int fromIndex)
returns the last index of the char, searching backwards from fromIndex (inclusive).
SafeString & operator-=(SafeString &rhs)
-= operator prefixes the SafeString.
Definition: SafeString.h:740
unsigned char reserve(unsigned int size)
Checks there is enough free space in this SafeString for the current operation.
unsigned char operator>=(SafeString &rhs)
Definition: SafeString.h:871
size_t println(SafeString &str)
static SafeString::noDebugPrint emptyPrint
Definition: SafeString.h:1996
unsigned int readFrom(SafeString &sfInput, unsigned int startIdx=0)
reads from the SafeString argument, starting at startIdx, into this SafeString.
SafeString & prefix(const __FlashStringHelper *str)
unsigned char readUntil(Stream &input, const char delimiter)
reads chars into this SafeString until either it is full OR a delimiter is read OR there are no more ...
size_t println(char)
SafeString & concat(float num)
SafeString & concatln(const char *cstr, size_t length)
unsigned char startsWith(const char *str2, unsigned int fromIndex=0)
returns non-zero of this SafeString starts this argument looking from fromIndex onwards.
unsigned char binToUnsignedLong(unsigned long &l)
convert the SafeString to an unsigned long assuming the SafeString in binary (0/1).
unsigned char startsWithIgnoreCase(const char *str2, unsigned int fromIndex=0)
returns non-zero of this SafeString starts this argument, ignoring case, looking from fromIndex onwar...
size_t len
Definition: SafeString.h:1980
size_t println(long, int=DEC)
static Print * currentOutput
Definition: SafeString.h:1998
const char * debug(bool verbose=true)
Output the details about the this SafeString to the output specified by setOutput().
size_t println(unsigned int, int=DEC)
unsigned char hexToLong(long &l)
convert the SafeString to a long assuming the SafeString in HEX (0 to f or 0 to F).
unsigned char operator!=(SafeString &rhs)
Definition: SafeString.h:853
size_t printInternal(int64_t num, int base=2, bool assignOp=false)
SafeString & concat(const char *cstr)
unsigned int readFrom(const char *strPtr, unsigned int maxCharsToRead=((unsigned int) -1))
reads from the const char* argument, starting at 0 and read up to maxCharToRead, into this SafeString...
void replace(char findChar, char replaceChar)
replace the findChar with the replaceChar
const char * c_str()
returns a const char* to the underlying char[ ] in this SafeString.
unsigned char octToLong(long &l)
convert the SafeString to a long assuming the SafeString in octal (0 to 7).
size_t println(void)
unsigned char operator<=(SafeString &rhs)
Definition: SafeString.h:868
size_t println(double, int=2)
char charAt(unsigned int index)
returns the char at that location in this SafeString.
size_t printInt(double d, int decs, int width, bool forceSign, bool addNL)
int utf8index(unsigned int endIdx)
For endIdx <= length(), utf8index() returns an index in the range endIdx-3 to endIdx such that using ...
unsigned char nextToken(SafeString &token, SafeString &delimiters, bool returnEmptyFields=false, bool returnLastNonDelimitedToken=true, bool firstToken=false)
returns true if a delimited token is found, removes the first delimited token from this SafeString an...
size_t println(int, int=DEC)
unsigned char hexToUnsignedLong(unsigned long &l)
convert the SafeString to an unsigned long assuming the SafeString in HEX (0 to f or 0 to F).
SafeString & concat(unsigned int num)
int stoken(SafeString &token, unsigned int fromIndex, const char *delimiters, bool returnEmptyFields=false, bool useAsDelimiters=true)
break into the SafeString into tokens using the delimiters, the end of the SafeString is always a del...
void setError()
int stoken(SafeString &token, unsigned int fromIndex, SafeString &delimiters, bool returnEmptyFields=false, bool useAsDelimiters=true)
break into the SafeString into tokens using the delimiters, the end of the SafeString is always a del...
int compareTo(const char *cstr)
returns -1 if this SafeString is < cstr, 0 if this SafeString == cstr and +1 if this SafeString > cst
size_t println(unsigned long, int=DEC)
size_t print(long, int=DEC)
void processBackspaces(void)
recursively remove backspaces, '\b' and the preceeding char.
unsigned char equals(const char *cstr)
int lastIndexOf(const char *cstr, unsigned int fromIndex)
returns the last index of the char, searching backwards from fromIndex (inclusive).
size_t println(int64_t, int=DEC)
size_t limitedStrLen(const char *p, size_t limit)
size_t print(SafeString &str)
unsigned char readUntilToken(Stream &input, SafeString &token, const char delimiter, bool &skipToDelimiter, uint8_t echoInput=false, unsigned long timeout_ms=0)
returns true if a delimited token is found, else false ONLY delimited tokens of length less than thi...
size_t print(unsigned long, int=DEC)
unsigned char firstToken(SafeString &token, char delimiter, bool returnLastNonDelimitedToken=true)
returns true if a delimited token is found, removes the first delimited token from this SafeString an...
Definition: SafeString.h:1622
void removeFrom(unsigned int startIndex)
remove all chars from startIndex to the end of the SafeString (inclusive)
size_t println(const char *)
unsigned char operator>(SafeString &rhs)
Definition: SafeString.h:865
int indexOfCharFrom(SafeString &str, unsigned int fromIndex=0)
returns the first index of any char from the argument.
unsigned int writeTo(SafeString &output, unsigned int startIdx=0)
writes from this SafeString, starting from startIdx, into the SafeString output arguement.
const char * debug(const __FlashStringHelper *title, bool verbose=true)
Output the details about the this SafeString to the output specified by setOutput().
int indexOf(const char *str, unsigned int fromIndex=0)
returns the index of the string, searching from fromIndex.
virtual size_t write(const uint8_t *buffer, size_t length)
Write (concatinate) bytes to this SafeString, from Print class.
unsigned char endsWithCharFrom(const char *suffix)
returns non-zero of this SafeString ends any one of the chars in the argument
int utf8nextIndex(unsigned int startIdx)
For startIdx < length(), utf8nextIndex() returns an index in the range startIdx+1 to startIdx+4 such ...
const char * debug(const char *title, bool verbose=true)
Output the details about the this SafeString to the output specified by setOutput().
void toLowerCase(void)
convert this SafeString to all lower case
void outputName() const
unsigned char readUntil(Stream &input, SafeString &delimiters)
reads chars into this SafeString until either it is full OR a delimiter is read OR there are no more ...
unsigned char readUntilToken(Stream &input, SafeString &token, const char *delimiters, bool &skipToDelimiter, uint8_t echoInput=false, unsigned long timeout_ms=0)
returns true if a delimited token is found, else false ONLY delimited tokens of length less than thi...
unsigned char toInt(int &i)
convert the SafeString to an int.
void replace(const char findChar, SafeString &sfReplace)
replace the findChar with the sfReplace SafeString contents
unsigned char equals(const char c)
SafeString & concat(char c)
unsigned char firstToken(SafeString &token, SafeString &delimiters, bool returnLastNonDelimitedToken=true)
returns true if a delimited token is found, removes the first delimited token from this SafeString an...
Definition: SafeString.h:1683
unsigned char nextToken(SafeString &token, const char *delimiters, bool returnEmptyFields=false, bool returnLastNonDelimitedToken=true, bool firstToken=false)
returns true if a delimited token is found, removes the first delimited token from this SafeString an...
unsigned char toInt64_t(int64_t &l)
convert the SafeString to a int64_t (for time_t long long).
size_t print(char)
SafeString & clear(void)
Empties this SafeString.
void toUpperCase(void)
convert this SafeString to all lower case
size_t print(int64_t, int=DEC)
unsigned char readUntilToken(Stream &input, SafeString &token, SafeString &delimiters, bool &skipToDelimiter, uint8_t echoInput=false, unsigned long timeout_ms=0)
returns true if a delimited token is found, else false ONLY delimited tokens of length less than thi...
SafeString & operator+=(SafeString &rhs)
+= operator concatinate to the SafeString.
Definition: SafeString.h:790
unsigned char binToLong(long &l)
convert the SafeString to a long assuming the SafeString in binary (0/1).
void replace(const char findChar, const char *replaceStr)
replace the findChar with the replace string
unsigned char startsWithIgnoreCase(SafeString &s2, unsigned int fromIndex=0)
returns non-zero of this SafeString starts this argument, ignoring case, looking from fromIndex onwar...
void setCharAt(unsigned int index, char c)
sets the char at that location in this SafeString.
int lastIndexOf(SafeString &str, unsigned int fromIndex)
returns the last index of the char, searching backwards from fromIndex (inclusive).
virtual size_t write(uint8_t b)
Write (concatinate) a byte to this SafeString, from Print class.
size_t printInternal(unsigned long, int=DEC, bool assignOp=false)
void removeLast(unsigned int count)
remove the last count chars
SafeString & substring(SafeString &result, unsigned int beginIdx)
The result is the substring from the beginIdx to the end of the SafeString.
SafeString & concat(SafeString &str)
concat methods add to the end of the current SafeString.
SafeString & substring(SafeString &result, unsigned int beginIdx, unsigned int endIdx)
The result is the substring from the beginIdx to endIdx (exclusive), that is the endIdx is NOT includ...
SafeString & prefix(char c)
unsigned char nextToken(SafeString &token, char delimiter, bool returnEmptyFields=false, bool returnLastNonDelimitedToken=true, bool firstToken=false)
returns true if a delimited token is found, removes the first delimited token from this SafeString an...
SafeString & newline()
Adds \r\n to this SafeString.
char * buffer
Definition: SafeString.h:1978
SafeString & prefix(unsigned char c)
size_t print(double, int=2)
SafeString & prefix(int64_t num)
unsigned char isEmpty(void)
Returns non-zero if the SafeString is empty.
size_t printInternal(double, int=2, bool assignOp=false)
int lastIndexOf(char ch)
returns the last index of the char, searching backwards from fromIndex (inclusive).
size_t println(const __FlashStringHelper *)
size_t print(unsigned int, int=DEC)
SafeString & concat(const __FlashStringHelper *str, size_t length)
unsigned char firstToken(SafeString &token, const char *delimiters, bool returnLastNonDelimitedToken=true)
returns true if a delimited token is found, removes the first delimited token from this SafeString an...
Definition: SafeString.h:1744
size_t print(double d, int decs, int width, bool forceSign=false)
Prints a double (or long/int) to this SafeString padded with spaces (left or right) and limited to th...
SafeString & concatln(char c)
SafeString & prefix(const char *cstr, size_t length)
SafeString & concat(int num)
SafeString & concat(const char *cstr, size_t length)
SafeString & concatInternal(const __FlashStringHelper *str, bool assignOp=false)
void keepLast(unsigned int count)
keep the last count chars and remove the rest
static void setVerbose(bool verbose)
Controls size of error messages, setOutput sets verbose to true.
void remove(unsigned int index, unsigned int count)
remove count chars starting from index
unsigned char endsWithCharFrom(SafeString &suffix)
returns non-zero of this SafeString ends any one of the chars in the argument
SafeString & prefix(unsigned int num)
SafeString & concat(const __FlashStringHelper *str)
size_t println(unsigned char, int=DEC)
int lastIndexOf(const char *cstr)
returns the last index of the arguement, searching backwards from fromIndex (inclusive).
int lastIndexOf(SafeString &str)
returns the last index of the arguement, searching backwards from fromIndex (inclusive).
unsigned int capacity(void)
The maximum number of characters this SafeString can hold, excluding the terminating '\0'.
unsigned char endsWith(const char *suffix)
returns non-zero of this SafeString ends with the argument
size_t printTo(Print &p) const
Implements the Printable interface.
static Print * debugPtr
Definition: SafeString.h:1976
SafeString & prefix(float num)
unsigned char equalsIgnoreCase(const char *str2)
int compareTo(SafeString &s)
returns -1 if this SafeString is < s, 0 if this SafeString == s and +1 if this SafeString > s
size_t _capacity
Definition: SafeString.h:1979
unsigned char toLong(long &l)
convert the SafeString to a long.
SafeString & prefix(SafeString &s)
prefix methods add to the front of the current SafeString.
size_t printInternal(long, int=DEC, bool assignOp=false)
unsigned char equals(SafeString &s)
SafeString & concat(long num)
void trim(void)
remove all white space from the front and back of this SafeString.
unsigned char startsWithIgnoreCase(const char c, unsigned int fromIndex=0)
returns non-zero of this SafeString starts this argument, ignoring case, looking from fromIndex onwar...
unsigned char octToUnsignedLong(unsigned long &l)
convert the SafeString to an unsigned long assuming the SafeString in octal (0 to 7).
size_t print(const char *)
SafeString & concat(unsigned long num)
SafeString & concat(unsigned char c)
unsigned char startsWith(SafeString &s2, unsigned int fromIndex=0)
returns non-zero of this SafeString starts this argument looking from fromIndex onwards.
size_t print(int, int=DEC)
SafeString & concat(double num)
unsigned char endsWith(const char c)
returns non-zero of this SafeString ends with the argument
SafeString & prefix(const char *cstr)
void replace(SafeString &sfFind, SafeString &sfReplace)
replace the occurances of the sfFind string, with the sfReplace SafeString contents
unsigned char operator==(SafeString &rhs)
Definition: SafeString.h:844
SafeString & concatInternal(const char *cstr, bool assignOp=false)
size_t println(double d, int decs, int width, bool forceSign=false)
Prints a double (or long/int) to this SafeString padded with spaces (left or right) and limited to th...
unsigned char toFloat(float &f)
convert the SafeString to a float assuming the SafeString in the decimal format (not scientific)
unsigned char operator<(SafeString &rhs)
Definition: SafeString.h:862
static bool fullDebug
Definition: SafeString.h:1977
SafeString & concatInternal(const __FlashStringHelper *str, size_t length, bool assignOp=false)
unsigned int length(void)
Number of characters current in the SafeString, excluding the terminating '\0'.
unsigned char startsWith(const char c, unsigned int fromIndex=0)
returns non-zero of this SafeString starts this argument looking from fromIndex onwards.
SafeString & concat(int64_t num)
SafeString & concatInternal(char c, bool assignOp=false)
void removeBefore(unsigned int startIndex)
remove all chars from 0 to startIndex (exclusive), that is the char at startIndex is NOT removed
char operator[](unsigned int index)
returns the char at that location in this SafeString.
int indexOf(SafeString &str, unsigned int fromIndex=0)
returns the index of the SafeString, searching from fromIndex.
int indexOf(char ch, unsigned int fromIndex=0)
returns the index of the char, searching from fromIndex.