Skip to content

Strange sizeof behaviour depending on calling syntax #7238

@mratsim

Description

@mratsim

This works (on devel, not on 0.17.2)

type ByteArrayBE*[N: static[int]] = array[N, byte]
  ## A byte array that stores bytes in big-endian order

proc toByteArrayBE*[T: SomeInteger](num: T): ByteArrayBE[T.sizeof]=
  ## Convert an integer (in native host endianness) to a big-endian byte array
  const N = T.sizeof
  for i in 0 ..< N:
    result[i] = byte(num shr ((N-1-i) * 8))

let a = 12345.toByteArrayBE

echo a # [0, 0, 0, 0, 0, 0, 48, 57]

Now if I change T.sizeof to sizeof(T) in the result type I get Error: cannot evaluate 'sizeof' because type is not defined completely

type ByteArrayBE*[N: static[int]] = array[N, byte]
  ## A byte array that stores bytes in big-endian order

proc toByteArrayBE*[T: SomeInteger](num: T): ByteArrayBE[sizeof(T)]=
  ## Convert an integer (in native host endianness) to a big-endian byte array
  ## Notice the result type
  const N = T.sizeof
  for i in 0 ..< N:
    result[i] = byte(num shr ((N-1-i) * 8))

let a = 12345.toByteArrayBE

echo a

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions