utility_string.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
  2. * Use of this source code is governed by a BSD-style license that can be
  3. * found in the LICENSE file.
  4. *
  5. * String utility functions that need to be built as part of the firmware.
  6. */
  7. #include "sysincludes.h"
  8. #include "utility.h"
  9. uint32_t Uint64ToString(char *buf, uint32_t bufsize, uint64_t value,
  10. uint32_t radix, uint32_t zero_pad_width)
  11. {
  12. char ibuf[UINT64_TO_STRING_MAX];
  13. char *s;
  14. uint32_t usedsize = 1;
  15. if (!buf)
  16. return 0;
  17. /* Clear output buffer in case of error */
  18. *buf = '\0';
  19. /* Sanity-check input args */
  20. if (radix < 2 || radix > 36 || zero_pad_width >= UINT64_TO_STRING_MAX)
  21. return 0;
  22. /* Start at end of string and work backwards */
  23. s = ibuf + UINT64_TO_STRING_MAX - 1;
  24. *(s) = '\0';
  25. do {
  26. int v = value % radix;
  27. value /= radix;
  28. *(--s) = (char)(v < 10 ? v + '0' : v + 'a' - 10);
  29. if (++usedsize > bufsize)
  30. return 0; /* Result won't fit in buffer */
  31. } while (value);
  32. /* Zero-pad if necessary */
  33. while (usedsize <= zero_pad_width) {
  34. *(--s) = '0';
  35. if (++usedsize > bufsize)
  36. return 0; /* Result won't fit in buffer */
  37. }
  38. /* Now copy the string back to the input buffer. */
  39. memcpy(buf, s, usedsize);
  40. /* Don't count the terminating null in the bytes used */
  41. return usedsize - 1;
  42. }
  43. uint32_t StrnAppend(char *dest, const char *src, uint32_t destlen)
  44. {
  45. uint32_t used = 0;
  46. if (!dest || !src || !destlen)
  47. return 0;
  48. /* Skip past existing string in destination.*/
  49. while (dest[used] && used < destlen - 1)
  50. used++;
  51. /* Now copy source */
  52. while (*src && used < destlen - 1)
  53. dest[used++] = *src++;
  54. /* Terminate destination and return count of non-null characters */
  55. dest[used] = 0;
  56. return used;
  57. }