status-im/nim-stew

Templates in ptrops.nim inserting {.checks: off.} into all files that use them

Closed this issue · 1 comments

guzba commented

Hey, just reporting something I noticed while investigating why some code was changing its behavior when this file was imported. I found that these templates have {.checks: off.} which results in that being inserted anywhere these functions are used in code.

It doesn't seem great to potentially turn checks off at the global / program scope just by using a little helper from a library. Could this push and pop the checks:off or is there a good reason for this I'm not aware of?

template offset*[T](p: ptr T, count: int): ptr T =
  ## Offset a pointer to T by count elements. Behavior is undefined on
  ## overflow.

  # Actual behavior is wrapping, but this may be revised in the future to enable
  # better optimizations.

  # We turn off checking here - too large counts is UB
  {.checks: off.}
  let bytes = count * sizeof(T)
  cast[ptr T](offset(cast[pointer](p), bytes))

template distance*[T](a, b: ptr T): int =
  # Number of elements between a and b - undefined behavior when difference
  # exceeds what can be represented in an int
  {.checks: off.}
  distance(cast[pointer](a), cast[pointer](b)) div sizeof(T)```
zah commented

Fixed in bb73567