I need to compare two `seq[byte]` using standard collation rules (like 
`strcmp`, except there can be embedded 0 bytes.) There doesn't seem to be any 
function in the standard library for this, or even a general `memcmp` function.

The best I found was a snippet in some of the std lib source code: 
    
    
    proc c_memcmp(a, b: pointer, size: csize_t): cint {.
      importc: "memcmp", header: "<string.h>", noSideEffect.}
    
    
    Run

so I've put this at the top of my source file and called `c_memcmp`. Is there 
anything better than this? Surely this should be wrapped already somewhere in 
the standard library?

Here's my compare function:
    
    
    proc cmp*(a, b: seq[byte]): int =
        let len = min(a.len, b.len)
        if len == 0:
            return 0
        let c = c_memcmp(unsafeAddr a[0], unsafeAddr b[0], csize_t(len))
        if c > 0:
            return 1
        elif c < 0:
            return -1
        else:
            return cmp(a.len, b.len)
    
    
    Run

Reply via email to