mirror of
https://github.com/RIOT-OS/RIOT.git
synced 2024-12-29 04:50:03 +01:00
sys: fmt: add fmt_lpad()
This commit is contained in:
parent
9e998efb16
commit
003b71b323
@ -243,6 +243,33 @@ size_t fmt_s16_dfp(char *out, int16_t val, unsigned fp_digits)
|
||||
return pos;
|
||||
}
|
||||
|
||||
size_t fmt_lpad(char *out, size_t in_len, size_t pad_len, char pad_char)
|
||||
{
|
||||
if (in_len >= pad_len) {
|
||||
return in_len;
|
||||
}
|
||||
|
||||
size_t n = pad_len - in_len;
|
||||
|
||||
if (FMT_USE_MEMMOVE) {
|
||||
memmove(out + n, out, in_len);
|
||||
memset(out, pad_char, n);
|
||||
}
|
||||
else {
|
||||
char *pos = out + pad_len - 1;
|
||||
out += in_len -1;
|
||||
|
||||
while(in_len--) {
|
||||
*pos-- = *out--;
|
||||
}
|
||||
|
||||
while (n--) {
|
||||
*pos-- = pad_char;
|
||||
}
|
||||
}
|
||||
return pad_len;
|
||||
}
|
||||
|
||||
uint32_t scn_u32_dec(const char *str, size_t n)
|
||||
{
|
||||
uint32_t res = 0;
|
||||
|
@ -41,6 +41,10 @@
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#ifndef FMT_USE_MEMMOVE
|
||||
#define FMT_USE_MEMMOVE (1) /**< use memmove() or internal implementation */
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @brief Format a byte value as hex
|
||||
*
|
||||
@ -294,6 +298,28 @@ void print_u64_dec(uint64_t val);
|
||||
*/
|
||||
void print_str(const char* str);
|
||||
|
||||
/**
|
||||
* @brief Pad string to the left
|
||||
*
|
||||
* This function left-pads a given string @p out with @p pad_char
|
||||
*
|
||||
* For example, calling
|
||||
*
|
||||
* fmt_lpad("abcd", 4, 7, ' ');
|
||||
*
|
||||
* would result in " abcd".
|
||||
*
|
||||
* @note Caller must ensure @p str can take pad_len characters!
|
||||
*
|
||||
* @param[inout] str string to pad
|
||||
* @param[in] in_len length of str
|
||||
* @param[in] pad_len total length after padding
|
||||
* @param[in] pad_char char to use as pad char
|
||||
*
|
||||
* @returns pad_len
|
||||
*/
|
||||
size_t fmt_lpad(char *str, size_t in_len, size_t pad_len, char pad_char);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
Loading…
Reference in New Issue
Block a user