Wiring String¶
Small String Optimisation¶
The String
class is probably the most used class in Arduino and Sming.
Unfortunately it gets the blame for one of the most indidious problems in the embedded world, heap fragmentation.
To alleviate this problem, Sming uses a technique known as Small String Optimisation, which uses the available space inside the String object itself to avoid using the heap for small allocations of 10 characters or fewer.
This was lifted from the Arduino Esp8266 core. Superb work - thank you!
Configuration Variables¶
-
STRING_OBJECT_SIZE
¶ minimum: 12 bytes (default) maximum: 128 bytes
Must be an integer multiple of 4 bytes.
This is an experimental feature which lets you increase the size of a String object to reduce heap allocations further. The effect of this will vary depending on your application, but you can see some example figures in Pull Request #1951.
Benefits of increasing
STRING_OBJECT_SIZE
:Increase code speed
Fewer heap allocations
Drawbacks:
Increased static memory usage for global/static String objects or embedded within global/static class instances.
A String can use SSO or the heap, but not both together, so in heap mode any additional SSO space will remain unused.
Allows the size of a String object to be changed to increase the string length available before the heap is used.
Note
The current implementation uses one byte for a NUL terminator, and another to store the length, so the maximum SSO string length is (STRING_OBJECT_SIZE - 2) characters.
However, the implementation may change so if you need to check the maximum SSO string size in your code, please use
String::SSO_CAPACITY
.
API Documentation¶
-
class
String
¶ The String class.
Note that a string object’s default constructor creates an empty string. This is not the same as a null string. A null string evaluates to false, but an empty string evaluates to true.
Small String Optimisation means that heap is only used for strings longer than 10 characters, not including the NUL terminator. This is simply making use of existing storage within the String object.
This length can be increased using STRING_OBJECT_SIZE, but note the additional space remains unused when switching to heap storage for longer Strings.
Subclassed by CStringArray, StringSumHelper
Copy constructors
If the initial value is null or invalid, or if memory allocation fails, the string will be marked as invalid (i.e. “if (s)” will be false).
Copy operators
If the value is null or invalid, or if the memory allocation fails, the String will be marked as invalid (“if (s)” will be false).
Move operators
Move content from one String to another without any heap allocation.
Move operators are automatically selected by the compiler when it is able, such as when returning temporary String objects from functions.
In other situations, use
std::move
:String original("A String"); String copy("This is the content for the copy"); copy = std::move(myString);
copy
will now contain “A String”, whilstoriginal
will be invalidated.Concatenation methods
Works with built-in types. On failure, the string is left unchanged. If the argument is null or invalid, the concatenation is considered unsucessful.
- Return Value
bool
: true on success, false on failure
Concatenation operators
If there’s not enough memory for the concatenated value, the string will be left unchanged (but this isn’t signalled in any way)
Comparison methods
Works with String and ‘c’ string
Comparisons are case-sensitive, binary comparison null strings (including cstr == nullptr) are treated as empty.
- Return Value
int
: Returns < 0 if String is lexically before the argument, > 0 if after or 0 if the same
Test for equality
Compares content byte-for-byte using binary comparison
null strings (including cstr == nullptr) are treated as empty.
- Return Value
bool
: Returns true if strings are identical
Equality operator ==
- Return Value
bool
: true if Strings are identical
In-equality operator !=
- Return Value
bool
: Returns true if strings are not identical
Test for equality, without case-sensitivity
null strings are treated as empty.
- Return Value
bool
: true if strings are considered the same
Array operators
If index is invalid, returns NUL \0
int indexOf(…)
Locate a character or String within another String.
By default, searches from the beginning of the
String, but can also start from a given index, allowing for the locating of all instances of the character or String.- Return Value
int
: Index if found, -1 if not found
int lastIndexOf(…)
Locate a character or String within another String
By default, searches from the end of the
String, but can also work backwards from a given index, allowing for the locating of all instances of the character or String.- Return Value
int
: Index if found, -1 if not found
String substring(…)
Get a substring of a String.
The starting index is inclusive (the corresponding character is included in the substring), but the optional ending index is exclusive (the corresponding character is not included in the substring).
- Parameters
from
: Index of first character to retrieveto
: (optional) One-past the ending character to retrieve
If the ending index is omitted, the substring continues to the end of the String.
If you don’t need the original String, consider using remove() instead:
String original("This is the original string."); String sub = original.substring(0, 13);
This produces the same result:
original.remove(13);
replace(…)
Replace all instances of a given character or substring with another character or substring.
Replacing a single character always succeeds as this is handled in-place.
- Return Value
bool
: true on success, false on allocation failure
Where
replace
is longer thanfind
the String may need to be re-allocated, which could fail. If this happens the method returns false and the String is left unchanged.remove()
Remove characters from a String.
If no count is provided then all characters from the given index to the end of the
String are removed.- Note
The String is modified in-situ without any reallocation
- Parameters
index
: Index of the first character to removecount
: Number of characters to remove
Public Functions
-
bool
reserve
(size_t size)¶ Pre-allocate String memory.
On failure, the
String is left unchanged. reserve(0), if successful, will validate an invalid string (i.e., “if (s)” will be true afterwards)- Parameters
size
:
- Return Value
bool
: true on success, false on failure
-
bool
setLength
(size_t length)¶ set the string length accordingly, expanding if necessary
- Note
extra characters are undefined
- Parameters
length
: required for string (nul terminator additional)
- Return Value
true
: on success, false on failure
-
bool
setBuffer
(const Buffer &buffer)¶ Set String content using move semantics from external memory buffer.
- Note
length MUST be <
size
- A NUL character is written at this location- Parameters
buffer
: We’ll take ownership of this buffer
- Return Value
bool
: true on success; on failure, ownership of buffer is not transferred
-
operator StringIfHelperType
() const¶ Provides safe bool() operator.
Evaluates as false if String is null, otherwise evaluates as true
-
bool
startsWith
(const String &prefix) const¶ Compare the start of a String Comparison is case-sensitive, must match exactly.
- Parameters
prefix
:
- Return Value
bool
: true on match
-
bool
startsWith
(const String &prefix, size_t offset) const¶ Compare a string portion.
mis-named as does not necessarily compare from start
- Note
Comparison is case-sensitive, must match exactly
- Parameters
prefix
:offset
: Index to start comparison at
- Return Value
bool
: true on match
-
bool
endsWith
(char suffix) const¶ Compare the end of a String.
- Parameters
suffix
:
- Return Value
bool
: true on match
-
bool
endsWith
(const String &suffix) const¶ Compare the end of a String.
- Parameters
suffix
:
- Return Value
bool
: true on match
-
char
charAt
(size_t index) const¶ Obtain the character at the given index.
- Note
If index is invalid, returns NUL \0
- Parameters
index
:
- Return Value
char
:
-
void
setCharAt
(size_t index, char c)¶ Sets the character at a given index.
- Note
If index is invalid, does nothing
- Parameters
index
:c
:
-
size_t
getBytes
(unsigned char *buf, size_t bufsize, size_t index = 0) const¶ Read contents of a String into a buffer.
- Note
Returned data always nul terminated so buffer size needs to take this into account
- Parameters
buf
: buffer to write databufsize
: size of buffer in bytesindex
: offset to start
- Return Value
unsigned
: number of bytes copied, excluding nul terminator
-
void
toCharArray
(char *buf, size_t bufsize, size_t index = 0) const¶ Read contents of String into a buffer.
- See
See
getBytes()
-
const char *
c_str
() const¶ Get a constant (un-modifiable) pointer to String content.
- Return Value
const
: char* Always valid, even for a null string
Public Static Attributes
-
constexpr size_t
SSO_CAPACITY
= STRING_OBJECT_SIZE - 2¶ Max chars. (excluding NUL terminator) we can store in SSO mode.
-
struct
Buffer
¶ Used with setBuffer and getBuffer methods.