blob: 50ac01ee6f84a1902acad715994550af552e69bd [file] [log] [blame]
Brian Silverman074392a2014-03-24 16:32:44 -07001#ifndef AOS_COMMON_PRINT_FIELD_HELPERS_H_
2#define AOS_COMMON_PRINT_FIELD_HELPERS_H_
3
4#include <stdint.h>
5
6#include <type_traits>
7
8namespace aos {
9
10template<typename T>
11inline bool PrintInteger(char *buf, T val, size_t *output) {
12 static const bool is_signed = ::std::is_signed<T>::value;
13
14 size_t len = 0;
15 if (is_signed && val <= 0) {
Brian Silverman89f557c2014-03-29 23:43:49 -070016 while (*output >= len && (val != 0 || len == 0)) {
Brian Silverman074392a2014-03-24 16:32:44 -070017 buf[len++] = '0' - (val % 10);
18 val /= 10;
19 }
20 buf[len++] = '-';
21 } else {
Brian Silverman89f557c2014-03-29 23:43:49 -070022 while (*output >= len && (val != 0 || len == 0)) {
Brian Silverman074392a2014-03-24 16:32:44 -070023 buf[len++] = '0' + (val % 10);
24 val /= 10;
25 }
26 }
27 // If we have enough space.
28 if (*output >= len) {
29 for (size_t i = 0; i < (len >> 1); i++) {
30 std::swap(buf[len - 1 - i], buf[i]);
31 }
32 *output -= len;
33 return true;
34 } else {
35 return false;
36 }
37}
38
39} // namespace aos
40
41#endif // AOS_COMMON_PRINT_FIELD_HELPERS_H_