openArray compare

This commit is contained in:
Jaremy Creechley 2023-09-20 19:48:31 -07:00
parent 1627e4d286
commit b388d242bb
No known key found for this signature in database
GPG Key ID: 4E66FB67B21D3300
2 changed files with 17 additions and 1 deletions

View File

@ -42,6 +42,11 @@ proc `==`*(a, b: DataBuffer): bool =
elif a[].buf == b[].buf: return true
else: a.hash() == b.hash()
template `==`*[T: char | byte](a: DataBuffer, b: openArray[T]): bool =
if a.isNil: false
elif a[].size != b.len: false
else: a.hash() == b.hash()
proc new*(tp: type DataBuffer, capacity: int = 0): DataBuffer =
## allocate new buffer with given capacity
##
@ -65,11 +70,12 @@ proc new*[T: byte | char](tp: type DataBuffer, data: openArray[T], opts: set[Dat
proc clear*(db: DataBuffer) =
zeroMem(db[].buf, db[].cap)
db[].size = 0
proc setData*[T: byte | char](db: DataBuffer, data: openArray[T]) =
## allocate new buffer and copies indata from openArray
##
if data.len() > db.len():
if data.len() > db[].cap:
raise newException(IndexDefect, "data too large for buffer")
db.clear() # this is expensive, but we can optimize later
copyMem(db[].buf, baseAddr data, data.len())

View File

@ -109,6 +109,16 @@ suite "Share buffer test":
check cstr.capacity() == 5
check "test" == cstr.toString()
test "basic clear test":
let test = DataBuffer.new("test", {dbNullTerminate})
test.clear()
check "" == test.toString()
test.setData("hi")
check "hi" == test.toString()
test "check openArray compare":
assert a == toOpenArray(@"/a/b", 0, 3)
test "basic openArray test":
proc letters(val: openArray[char]): int =
val.len()