(** main entry top-level function: `register_nick` *) (** TODO: consider storing the Rwdb.t in memory? *) module Rwdb = Dokeysto.Db.RW type t = DB of string let get_db (DB db : t) : Rwdb.t = 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 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 = 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" let register_nick (nick : string) (db : t) = with_db (inc_nick_value nick) db