memory.nim 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. if a.isNil: return 0
  40. when useLibC:
  41. cast[int](c_strlen(a))
  42. else:
  43. var a = cast[ptr byte](a)
  44. while a[] != 0:
  45. a = cast[ptr byte](cast[uint](a) + 1)
  46. inc result
  47. {.pop.}