~ehmry/nim-tkrzw

18cf1c6f23e5124f93040f61bf338621ac47a1ab — Emery Hemingway 3 years ago aa2f1b2
Use std::string_view for C++ keys and values
1 files changed, 14 insertions(+), 4 deletions(-)

M src/tkrzw.nim
M src/tkrzw.nim => src/tkrzw.nim +14 -4
@@ 58,6 58,16 @@ type

using dbm: DBM

type StringView {.importcpp: "std::string_view".} = object
proc toStringView(s: pointer; count: int): StringView {.
  importcpp: "std::string_view(@)", constructor.}
proc toStringView(s: string): StringView {.inline.} =
  if s.len == 0: toStringView(nil, 0)
  else: toStringView(unsafeAddr s[0], s.len)
proc toStringView(buf: openarray[byte]): StringView {.inline.} =
  if buf.len == 0: toStringView(nil, 0)
  else: toStringView(unsafeAddr buf[0], buf.len)

type Status {.importcpp: "tkrzw::Status".} = object
proc IsOK(st: Status): bool {.importcpp: "#.IsOK()".}
proc GetMessage(st: Status): cstring {.importcpp: "#.GetMessage().c_str()".}


@@ 76,9 86,9 @@ template importDBM(T: untyped): untyped =
  proc Open(dbm: T; path: cstring; writeable: bool; options: int32) {.
      importcpp: "#->Open(@)".}
  proc Close(dbm: T) {.importcpp: "#->Close()".}
  proc GetSimple(dbm: T; key, default: cstring): cstring {.
  proc GetSimple(dbm: T; key: StringView; default: cstring): cstring {.
      importcpp: "#->GetSimple(@).c_str()".}
  proc Set(dbm: T; key, value: cstring; overwrite: bool) {.
  proc Set(dbm: T; key, value: StringView; overwrite: bool) {.
      importcpp: "#->Set(@)".}
  proc MakeIterator(dbm: T): Iterator {.importcpp: "#->MakeIterator()".}
  proc Synchronize(dbm: T; hard: bool): Status {.


@@ 124,10 134,10 @@ proc close*(dbm: DBM) =
  dbm.Close()

proc get*(dbm; key: string; default = ""): string =
  $dbm.GetSimple(key, default)
  $dbm.GetSimple(key.toStringView, default)

proc set*(dbm; key, value: string; overwrite = true) =
  dbm.Set(key, value, overwrite)
  dbm.Set(key.toStringView, value.toStringView, overwrite)

proc `[]`*(dbm; key: string): string =
  const def = genSym().strVal