memory.nim 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. {.push stack_trace: off.}
  2. const useLibC = not defined(nimNoLibc)
  3. when useLibC:
  4. import ansi_c
  5. proc nimCopyMem*(dest, source: pointer, size: Natural) {.nonReloadable, compilerproc, inline.} =
  6. when useLibC:
  7. c_memcpy(dest, source, cast[csize_t](size))
  8. else:
  9. let d = cast[ptr UncheckedArray[byte]](dest)
  10. let s = cast[ptr UncheckedArray[byte]](source)
  11. var i = 0
  12. while i < size:
  13. d[i] = s[i]
  14. inc i
  15. proc nimSetMem*(a: pointer, v: cint, size: Natural) {.nonReloadable, inline.} =
  16. when useLibC:
  17. c_memset(a, v, cast[csize_t](size))
  18. else:
  19. let a = cast[ptr UncheckedArray[byte]](a)
  20. var i = 0
  21. let v = cast[byte](v)
  22. while i < size:
  23. a[i] = v
  24. inc i
  25. proc nimZeroMem*(p: pointer, size: Natural) {.compilerproc, nonReloadable, inline.} =
  26. nimSetMem(p, 0, size)
  27. proc nimCmpMem*(a, b: pointer, size: Natural): cint {.compilerproc, nonReloadable, inline.} =
  28. when useLibC:
  29. c_memcmp(a, b, cast[csize_t](size))
  30. else:
  31. let a = cast[ptr UncheckedArray[byte]](a)
  32. let b = cast[ptr UncheckedArray[byte]](b)
  33. var i = 0
  34. while i < size:
  35. let d = a[i].cint - b[i].cint
  36. if d != 0: return d
  37. inc i
  38. proc nimCStrLen*(a: cstring): int {.compilerproc, nonReloadable, inline.} =
  39. when useLibC:
  40. cast[int](c_strlen(a))
  41. else:
  42. var a = cast[ptr byte](a)
  43. while a[] != 0:
  44. a = cast[ptr byte](cast[uint](a) + 1)
  45. inc result
  46. {.pop.}