Initial problem is: 
    
    
    #  Error: type mismatch: got (Array constructor[0..3, int]) but expected 
'array[0..3, byte]'
    const data: array[4,byte] = [0xFD, 0x10, 0x20, 0x30]
    

Because typing _'u8_ or _'u32_ or similar is no fun for large const arrays, I 
thought let's use some sort of automation. Enter first option, template: 
    
    
    template seqOf[T, N] (buff: openarray[T]): untyped =
        map[T, N](buff, proc (x: T): N = x.N)
    
    const dataSeq = seqOf[int,byte]([0xEF, 0x7F, 0x80, 0xFF, 0x10A])
    

Everything works fine (with proper data) and as bonus I get the error when 
overflowing with 0x10A.

But then I read some posts saying the const seq are not so good , use const 
arrays instead (shouldn`t make a difference for my case as using them as global 
variables anyway). Enter second option, macro: 
    
    
    macro arrayOfU8(data: openArray[int]): untyped =
        result = newNimNode(nnkStmtList)
        var arrayStmt = newNimNode(nnkBracket)
        
        for i in 0 .. <data.len:
            var u8Node = newNimNode(nnkUInt8Lit)
            u8Node.intVal = intVal(data[i])
            arrayStmt.add(u8Node)
        
        result.add(arrayStmt)
    
    const dataArray = [0xEF, 0x7F, 0x80, 0xFF, 0x10A].arrayOfU8()
    

So I got my array declared but the 0x10A yields no error and instead gets 
truncated to the lesser byte 0x0A. While I care not so much for having the 
error triggered, it would have been nice though to catch early errors as in the 
seq case.

Is there any other approach to my initial problem? Thank you.

Reply via email to