Add a template overload of 'readUnitName'

This template function is provided as a convinience to help users to avoid potential buffer overrun errors at compile time.
It performs a `static_assert` to check if the provided `char` array is large enough to receive the unit name.
There should be no additional cost as the template simply calls the other `readUnitName` overload (and thus should always be inlined).
This commit is contained in:
Pharap 2020-04-21 05:04:05 +01:00 committed by GitHub
parent 3f9e86ab99
commit fe9efee4e3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 43 additions and 0 deletions

View File

@ -1108,6 +1108,49 @@ class Arduboy2Base : public Arduboy2Core
*/ */
void writeUnitID(uint16_t id); void writeUnitID(uint16_t id);
/** \brief
* Read the unit name from system EEPROM.
*
* \param name A char array variable where the unit name will be placed.
* The array will be up to 6 characters and terminated with a
* null (0x00) character, so the provided array must be at least 7 bytes long.
* This template enforces the size restriction with a `static_assert`.
*
* \return The length of the string (0-6).
*
* \details
* This function reads the unit name that has been set in system EEPROM. The
* name is in ASCII and can contain any values except 0xFF and the
* null (0x00) terminator value.
*
* The name can be used for any purpose. It could identify the owner or
* give the unit itself a nickname. A sketch could use it to automatically
* fill in a name or initials in a high score table, or display it as the
* "player" when the opponent is the computer.
*
* \note
* Sketches can use the defined value `ARDUBOY_UNIT_NAME_LEN` instead of
* hard coding a 6 when working with the unit name. For example, to allocate
* a buffer and read the unit name into it:
* \code{.cpp}
* // Buffer for maximum name length plus the terminator
* char unitName[ARDUBOY_UNIT_NAME_LEN + 1];
*
* // The actual name length
* byte unitNameLength;
*
* unitNameLength = arduboy.readUnitName(unitName);
* \endcode
*
* \see readUnitName() writeUnitName() readUnitID() Arduboy2::bootLogoExtra()
*/
template<size_t size>
uint8_t readUnitName(char (&name)[size])
{
static_assert(size >= (ARDUBOY_UNIT_NAME_LEN + 1), "Provided array is not large enough to hold a unit name");
return readUnitName(&name[0]);
}
/** \brief /** \brief
* Read the unit name from system EEPROM. * Read the unit name from system EEPROM.
* *