Skip to content

Commit

Permalink
Merge #19027
Browse files Browse the repository at this point in the history
19027: sys/fmt: optimize scn_u32_dec scn_u32_hex r=benpicco a=kfessel

### Contribution description

Improves the compilation result for `scn_u32_dec` `scn_u32_hex` especially on `cortex-m` reducing either stack usage and or code size.

This makes use of unsigned int overflow (slightly less better without doing that `hexn`).

See godbolt (original versions got an `o` attached, modified versions got `k`s) all functions are  marked `_S_` defined to `static`

by assigning the global at end the compiled function can be changed (`deco deck  hexo hexk hexkk hexn`)

this PR is `hexkk` and `deck` 

### Testing procedure

run unit-test/test-fmt

```
<RIOT>/tests/unittests$ make tests-fmt
<RIOT>/tests/unittests$ make term
```

### Issues/PRs references

[godbolt](https://godbolt.org/z/MzT1zh4q1)

Co-authored-by: Karl Fessel <karl.fessel@ovgu.de>
  • Loading branch information
bors[bot] and kfessel committed Feb 17, 2023
2 parents 6f6727d + 18a783d commit 3e6d948
Showing 1 changed file with 19 additions and 18 deletions.
37 changes: 19 additions & 18 deletions sys/fmt/fmt.c
Original file line number Diff line number Diff line change
Expand Up @@ -471,14 +471,13 @@ uint32_t scn_u32_dec(const char *str, size_t n)
uint32_t res = 0;

while (n--) {
char c = *str++;
if (!fmt_is_digit(c)) {
unsigned c = *str++;
unsigned d = c - (unsigned)'0';
if ( !( '0'<= c && c <= '9') ) {
break;
}
else {
res *= 10;
res += (c - '0');
}
res *= 10U;
res += d;
}
return res;
}
Expand All @@ -488,21 +487,23 @@ uint32_t scn_u32_hex(const char *str, size_t n)
uint32_t res = 0;

while (n--) {
char c = *str++;
if (!fmt_is_digit(c)) {
if (fmt_is_upper(c)) {
c = _to_lower(c);
}
if (c == '\0' || c > 'f') {
break;
}
res <<= 4;
res |= c - 'a' + 0xa;
unsigned c = *str++;
unsigned d;
if (('0'<= c) && (c <= '9')){
d = c - (unsigned)'0';
}
else if (('A' <= c) && (c <= 'F')) {
d = c - (unsigned)'A' + 0xaU;
}
else if (('a' <= c) && (c <= 'f')) {
d = c - (unsigned)'a' + 0xaU;
}
else {
res <<= 4;
res |= c - '0';
break;
}
res <<= 4U;
res |= d;

}
return res;
}
Expand Down

0 comments on commit 3e6d948

Please sign in to comment.