vantabot/store.ml

34 lines
923 B
OCaml
Raw Permalink Normal View History

2019-05-16 20:20:23 +00:00
(** main entry top-level function: `register_nick` *)
2019-05-16 20:43:36 +00:00
(** TODO: consider storing the Rwdb.t in memory? *)
2019-02-16 20:04:52 +00:00
module Rwdb = Dokeysto.Db.RW
2019-05-16 20:43:36 +00:00
type t = DB of string
let get_db (DB db : t) : Rwdb.t =
2019-02-16 20:04:52 +00:00
let open Unix in
let already_exists =
try access db [F_OK]; true
with Unix_error(ENOENT,_,_) -> false in
if already_exists
then Rwdb.open_existing db
else Rwdb.create db
let release_db (h : Rwdb.t) : unit = Rwdb.sync h; Rwdb.close h
let try_finalize f x finally y = let res = try f x with exn -> finally y; raise exn in finally y; res
2019-05-16 20:43:36 +00:00
let with_db f (db : t) =
let h = get_db db in
try_finalize f h
release_db h
let inc_nick_value (nick : string) (h : Rwdb.t) : unit =
2019-02-16 20:04:52 +00:00
if Rwdb.mem h nick
then let n = int_of_string (Rwdb.find h nick) in
Rwdb.replace h nick (string_of_int (n+1))
else Rwdb.add h nick "1"
2019-05-16 20:43:36 +00:00
let register_nick (nick : string) (db : t) =
with_db (inc_nick_value nick) db
2019-02-16 20:04:52 +00:00