string_utils.h 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. * Copyright (c) 2012-2016 Daniele Bartolini and individual contributors.
  3. * License: https://github.com/taylor001/crown/blob/master/LICENSE
  4. */
  5. #pragma once
  6. #include "types.h"
  7. #include "error.h"
  8. #include "platform.h"
  9. #include "macros.h"
  10. #include <stdio.h> // sscanf, vsnprintf
  11. #include <string.h>
  12. #include <stdarg.h>
  13. #include <ctype.h> // isspace
  14. namespace crown
  15. {
  16. inline int32_t vsnprintf(char* str, size_t num, const char* format, va_list args)
  17. {
  18. #if CROWN_COMPILER_MSVC
  19. int32_t len = _vsnprintf_s(str, num, _TRUNCATE, format, args);
  20. return (len == 1) ? _vscprintf(format, args) : len;
  21. #else
  22. return ::vsnprintf(str, num, format, args);
  23. #endif // CROWN_COMPILER_MSVC
  24. }
  25. inline int32_t snprintf(char* str, size_t n, const char* format, ...)
  26. {
  27. va_list args;
  28. va_start(args, format);
  29. int32_t len = vsnprintf(str, n, format, args);
  30. va_end(args);
  31. return len;
  32. }
  33. inline uint32_t strlen32(const char* str)
  34. {
  35. return (uint32_t)strlen(str);
  36. }
  37. inline const char* skip_spaces(const char* str)
  38. {
  39. while (isspace(*str)) ++str;
  40. return str;
  41. }
  42. inline const char* skip_block(const char* str, char a, char b)
  43. {
  44. uint32_t num = 0;
  45. for (char ch = *str++; ch != '\0'; ch = *str++)
  46. {
  47. if (ch == a) ++num;
  48. else if (ch == b)
  49. {
  50. if (--num == 0)
  51. {
  52. return str;
  53. }
  54. }
  55. }
  56. return NULL;
  57. }
  58. } // namespace crown