1
0
mirror of https://github.com/RIOT-OS/RIOT.git synced 2024-12-29 04:50:03 +01:00

Merge pull request #6784 from kaspar030/add_fmt_lpad

sys: fmt: add fmt_lpad()
This commit is contained in:
lebrush 2017-03-27 20:10:12 +02:00 committed by GitHub
commit 796eb64c0b
3 changed files with 87 additions and 0 deletions

View File

@ -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;

View File

@ -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

View File

@ -13,6 +13,7 @@
*/
#include <errno.h>
#include <stdint.h>
#include <string.h>
#include "embUnit/embUnit.h"
@ -275,6 +276,38 @@ static void test_scn_u32_dec(void)
TEST_ASSERT_EQUAL_INT(val2, scn_u32_dec(string1, 5));
}
static void test_fmt_lpad(void)
{
const char base[] = "abcd";
char string[9] = {0};
strcpy(string, base);
fmt_lpad(string, 4, 8, ' ');
TEST_ASSERT_EQUAL_STRING(" abcd", (char*)string);
fmt_lpad(string, 0, 0, '1');
TEST_ASSERT_EQUAL_STRING(" abcd", (char*)string);
fmt_lpad(string, 4, 0, '2');
TEST_ASSERT_EQUAL_STRING(" abcd", (char*)string);
fmt_lpad(string, 0, 4, '3');
TEST_ASSERT_EQUAL_STRING("3333abcd", (char*)string);
fmt_lpad(string, 8, 8, '4');
TEST_ASSERT_EQUAL_STRING("3333abcd", (char*)string);
fmt_lpad(string, 4, 8, 'x');
TEST_ASSERT_EQUAL_STRING((char*)string, "xxxx3333");
}
Test *tests_fmt_tests(void)
{
EMB_UNIT_TESTFIXTURES(fixtures) {
@ -293,6 +326,7 @@ Test *tests_fmt_tests(void)
new_TestFixture(test_fmt_strlen),
new_TestFixture(test_fmt_str),
new_TestFixture(test_scn_u32_dec),
new_TestFixture(test_fmt_lpad),
};
EMB_UNIT_TESTCALLER(fmt_tests, NULL, NULL, fixtures);