tsizeof3.nim 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. discard """
  2. output: '''
  3. @[48, 57]
  4. '''
  5. """
  6. # bug #7238
  7. type ByteArrayBE*[N: static[int]] = array[N, byte]
  8. ## A byte array that stores bytes in big-endian order
  9. proc toByteArrayBE*[T: SomeInteger](num: T): ByteArrayBE[sizeof(T)]=
  10. ## Convert an integer (in native host endianness) to a big-endian byte array
  11. ## Notice the result type
  12. const N = T.sizeof
  13. for i in 0 ..< N:
  14. result[i] = byte((num shr ((N-1-i) * 8)) and high(int8))
  15. let a = 12345.toByteArrayBE
  16. echo a[^2 .. ^1] # to make it work on both 32-bit and 64-bit
  17. #---------------------------------------------------------------------
  18. type
  19. Payload = object
  20. something: int
  21. vals: UncheckedArray[int]
  22. static:
  23. doAssert(compiles(offsetOf(Payload, vals)))
  24. type
  25. GoodboySave* {.bycopy.} = object
  26. saveCount: uint8
  27. savePoint: uint16
  28. shards: uint32
  29. friendCount: uint8
  30. friendCards: set[0..255]
  31. locationsKnown: set[0..127]
  32. locationsUnlocked: set[0..127]
  33. pickupsObtained: set[0..127]
  34. pickupsUsed: set[0..127]
  35. pickupCount: uint8
  36. block: # bug #20914
  37. block:
  38. proc csizeof[T](a: T): int {.importc:"sizeof", nodecl.}
  39. var s: GoodboySave
  40. doAssert sizeof(s) == 108
  41. doAssert csizeof(s) == static(sizeof(s))
  42. block:
  43. proc calignof[T](a: T): int {.importc:"alignof", header: "<stdalign.h>".}
  44. var s: set[0..256]
  45. doAssert alignof(s) == 1
  46. doAssert calignof(s) == static(alignof(s))