cstrutils.nim 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2017 Nim contributors
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module supports helper routines for working with ``cstring``
  10. ## without having to convert ``cstring`` to ``string`` in order to
  11. ## save allocations.
  12. include "system/inclrtl"
  13. proc toLowerAscii(c: char): char {.inline.} =
  14. if c in {'A'..'Z'}:
  15. result = chr(ord(c) + (ord('a') - ord('A')))
  16. else:
  17. result = c
  18. proc startsWith*(s, prefix: cstring): bool {.noSideEffect,
  19. rtl, extern: "csuStartsWith".} =
  20. ## Returns true iff ``s`` starts with ``prefix``.
  21. ##
  22. ## If ``prefix == ""`` true is returned.
  23. var i = 0
  24. while true:
  25. if prefix[i] == '\0': return true
  26. if s[i] != prefix[i]: return false
  27. inc(i)
  28. proc endsWith*(s, suffix: cstring): bool {.noSideEffect,
  29. rtl, extern: "csuEndsWith".} =
  30. ## Returns true iff ``s`` ends with ``suffix``.
  31. ##
  32. ## If ``suffix == ""`` true is returned.
  33. let slen = s.len
  34. var i = 0
  35. var j = slen - len(suffix)
  36. while i+j <% slen:
  37. if s[i+j] != suffix[i]: return false
  38. inc(i)
  39. if suffix[i] == '\0': return true
  40. proc cmpIgnoreStyle*(a, b: cstring): int {.noSideEffect,
  41. rtl, extern: "csuCmpIgnoreStyle".} =
  42. ## Semantically the same as ``cmp(normalize($a), normalize($b))``. It
  43. ## is just optimized to not allocate temporary strings. This should
  44. ## NOT be used to compare Nim identifier names. use `macros.eqIdent`
  45. ## for that. Returns:
  46. ##
  47. ## | 0 iff a == b
  48. ## | < 0 iff a < b
  49. ## | > 0 iff a > b
  50. var i = 0
  51. var j = 0
  52. while true:
  53. while a[i] == '_': inc(i)
  54. while b[j] == '_': inc(j) # BUGFIX: typo
  55. var aa = toLowerAscii(a[i])
  56. var bb = toLowerAscii(b[j])
  57. result = ord(aa) - ord(bb)
  58. if result != 0 or aa == '\0': break
  59. inc(i)
  60. inc(j)
  61. proc cmpIgnoreCase*(a, b: cstring): int {.noSideEffect,
  62. rtl, extern: "csuCmpIgnoreCase".} =
  63. ## Compares two strings in a case insensitive manner. Returns:
  64. ##
  65. ## | 0 iff a == b
  66. ## | < 0 iff a < b
  67. ## | > 0 iff a > b
  68. var i = 0
  69. while true:
  70. var aa = toLowerAscii(a[i])
  71. var bb = toLowerAscii(b[i])
  72. result = ord(aa) - ord(bb)
  73. if result != 0 or aa == '\0': break
  74. inc(i)