memory.nim 1.5 KB

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