memory.nim 1.2 KB

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