~ehmry/nim-tkrzw

9ed47bf61c4bbf3de450cf98abbf42340d0236c5 — Emery Hemingway 2 years ago 11ebd1a
Cleaner get proc
2 files changed, 14 insertions(+), 13 deletions(-)

M src/tkrzw.nim
M tkrzw.nimble
M src/tkrzw.nim => src/tkrzw.nim +13 -12
@@ 6,8 6,6 @@
{.passC: staticExec("pkg-config --cflags tkrzw").}
{.passL: staticExec("pkg-config --libs tkrzw").}

from macros import genSym, strVal

type
  RW* = enum readonly, writeable
  OpenOption* = enum


@@ 146,20 144,23 @@ proc close*(dbm: DBM) =
  ## Closes the database file.
  dbm.Close()

proc get*[A,B](dbm; key: A; result: var B) =
  var
    buf: CppString
    st = dbm.Get(key.toStringView, addr buf)
  if not IsOK(st):
    raise newException(KeyError, $GetMessage(st))
  result.setLen(buf.len)
  copyMem(addr result[0], buf.data, result.len)
    # TODO: is this copy avoidable?
proc get*[A,B](dbm; key: A; dst: var B): bool =
  var src: CppString
  if IsOK dbm.Get(key.toStringView, addr src):
    result = true
    dst.setLen(src.len)
    if dst.len > 0:
      copyMem(addr dst[0], src.data, dst.len)

proc hasKey*[A](dbm; key: A): bool =
  dbm.Get(key.toStringView, nil).IsOK

proc set*[A,B](dbm; key: A; value: B; overwrite = true) =
  dbm.Set(key.toStringView, value.toStringView, overwrite)

proc `[]`*(dbm; key: string): string {.inline.} = get(dbm, key, result)
proc `[]`*(dbm; key: string): string {.inline.} =
  if not get(dbm, key, result):
    raise newException(KeyError, "")

proc `[]=`*(dbm; key, value: string) = set(dbm, key, value)


M tkrzw.nimble => tkrzw.nimble +1 -1
@@ 1,6 1,6 @@
# Package

version       = "0.1.2"
version = "20220830"
author        = "Emery Hemingway"
description   = "Wrapper of the Tkrzw key-value database library"
license       = "Apache-2.0"