Created
January 17, 2025 02:41
-
-
Save jiacai2050/4b7fd38d01c9d8823e45b2d93c4ef720 to your computer and use it in GitHub Desktop.
Use rocksdb in Zig!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const std = @import("std"); | |
pub const c = @cImport({ | |
@cInclude("rocksdb/c.h"); | |
}); | |
const key = "hello"; | |
const value = "world"; | |
pub fn main() !void { | |
const opts = c.rocksdb_options_create(); | |
c.rocksdb_options_set_create_if_missing(opts, 1); | |
var err: ?[*:0]u8 = null; | |
const c_handle = c.rocksdb_open( | |
opts, | |
"/tmp/rocksdb.test", | |
&err, | |
); | |
if (err) |e| { | |
std.log.err("Error when open: {s}", .{e}); | |
c.rocksdb_free(err); | |
return error.OpenDatabase; | |
} | |
defer c.rocksdb_close(c_handle); | |
const write_opts = c.rocksdb_writeoptions_create(); | |
c.rocksdb_put(c_handle, write_opts, key.ptr, key.len, value, value.len, &err); | |
if (err) |e| { | |
std.log.err("Error when put: {s}", .{e}); | |
c.rocksdb_free(err); | |
return error.Put; | |
} | |
const read_opts = c.rocksdb_readoptions_create(); | |
var res_len: usize = 0; | |
const res = c.rocksdb_get(c_handle, read_opts, key.ptr, key.len, &res_len, &err); | |
if (err) |e| { | |
std.log.err("Error when get: {s}", .{e}); | |
c.rocksdb_free(err); | |
return error.Get; | |
} | |
defer c.rocksdb_free(res); | |
std.debug.print("Value: {s}\n", .{res[0..res_len]}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment