internal_util.odin 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #+private
  2. package os2
  3. import "base:intrinsics"
  4. import "base:runtime"
  5. import "core:math/rand"
  6. // Splits pattern by the last wildcard "*", if it exists, and returns the prefix and suffix
  7. // parts which are split by the last "*"
  8. @(require_results)
  9. _prefix_and_suffix :: proc(pattern: string) -> (prefix, suffix: string, err: Error) {
  10. for i in 0..<len(pattern) {
  11. if is_path_separator(pattern[i]) {
  12. err = .Pattern_Has_Separator
  13. return
  14. }
  15. }
  16. prefix = pattern
  17. for i := len(pattern)-1; i >= 0; i -= 1 {
  18. if pattern[i] == '*' {
  19. prefix, suffix = pattern[:i], pattern[i+1:]
  20. break
  21. }
  22. }
  23. return
  24. }
  25. @(require_results)
  26. clone_string :: proc(s: string, allocator: runtime.Allocator) -> (res: string, err: runtime.Allocator_Error) {
  27. buf := make([]byte, len(s), allocator) or_return
  28. copy(buf, s)
  29. return string(buf), nil
  30. }
  31. @(require_results)
  32. clone_to_cstring :: proc(s: string, allocator: runtime.Allocator) -> (res: cstring, err: runtime.Allocator_Error) {
  33. res = "" // do not use a `nil` cstring
  34. buf := make([]byte, len(s)+1, allocator) or_return
  35. copy(buf, s)
  36. buf[len(s)] = 0
  37. return cstring(&buf[0]), nil
  38. }
  39. @(require_results)
  40. string_from_null_terminated_bytes :: proc(b: []byte) -> (res: string) {
  41. s := string(b)
  42. i := 0
  43. for ; i < len(s); i += 1 {
  44. if s[i] == 0 {
  45. break
  46. }
  47. }
  48. return s[:i]
  49. }
  50. @(require_results)
  51. concatenate_strings_from_buffer :: proc(buf: []byte, strings: ..string) -> string {
  52. n := 0
  53. for s in strings {
  54. (n < len(buf)) or_break
  55. n += copy(buf[n:], s)
  56. }
  57. n = min(len(buf), n)
  58. return string(buf[:n])
  59. }
  60. @(require_results)
  61. concatenate :: proc(strings: []string, allocator: runtime.Allocator) -> (res: string, err: runtime.Allocator_Error) {
  62. n := 0
  63. for s in strings {
  64. n += len(s)
  65. }
  66. buf := make([]byte, n, allocator) or_return
  67. n = 0
  68. for s in strings {
  69. n += copy(buf[n:], s)
  70. }
  71. return string(buf), nil
  72. }
  73. @(require_results)
  74. random_string :: proc(buf: []byte) -> string {
  75. for i := 0; i < len(buf); i += 16 {
  76. n := rand.uint64()
  77. end := min(i + 16, len(buf))
  78. for j := i; j < end; j += 1 {
  79. buf[j] = '0' + u8(n) % 10
  80. n >>= 4
  81. }
  82. }
  83. return string(buf)
  84. }