diff --git a/datastore/databuffer.nim b/datastore/databuffer.nim index 14d7d21..1ee5c5f 100644 --- a/datastore/databuffer.nim +++ b/datastore/databuffer.nim @@ -54,9 +54,15 @@ proc `=copy`*(a: var DataBuffer; b: DataBuffer) = proc incrAtomicCount*(a: DataBuffer) = let res = atomicAddFetch(a.cnt, 1, ATOMIC_RELAXED) -proc getAtomicCount*(a: DataBuffer): int = +proc unsafeGetAtomicCount*(a: DataBuffer): int = atomicLoad(a.cnt, addr result, ATOMIC_RELAXED) +proc len*(a: DataBuffer): int = a.size + +proc toSeq*[T: byte | char](a: DataBuffer, tp: typedesc[T]): seq[T] = + result = newSeq[T](a.len) + copyMem(addr result[0], unsafeAddr a.buf[0], a.len) + proc new*(tp: typedesc[DataBuffer], size: int = 0): DataBuffer = let cnt = cast[ptr int](allocShared0(sizeof(result.cnt))) cnt[] = 1 diff --git a/tests/datastore/testsharedbuffer.nim b/tests/datastore/testsharedbuffer.nim index 499438a..4a0f062 100644 --- a/tests/datastore/testsharedbuffer.nim +++ b/tests/datastore/testsharedbuffer.nim @@ -43,8 +43,8 @@ proc thread1(val: int) {.thread.} = var myBytes = DataBuffer.new(@"hello world") myBytes2 = myBytes - echo "thread1: sending: ", myBytes, " cnt: ", myBytes.getAtomicCount() - echo "mybytes2: ", myBytes2, " cnt: ", myBytes2.getAtomicCount() + echo "thread1: sending: ", myBytes, " cnt: ", myBytes.unsafeGetAtomicCount() + echo "mybytes2: ", myBytes2, " cnt: ", myBytes2.unsafeGetAtomicCount() shareVal = myBytes echo "thread1: sent, left over: ", $myBytes @@ -60,7 +60,8 @@ proc thread2(val: int) {.thread.} = wait(cond, lock) echo "thread2: receiving " let msg: DataBuffer = shareVal - echo "thread2: received: ", msg, " cnt: ", msg.getAtomicCount() + echo "thread2: received: ", msg, " cnt: ", msg.unsafeGetAtomicCount() + check msg.toSeq(char) == @"hello world" # os.sleep(100) proc runBasicTest() =