Skip to content

Instantly share code, notes, and snippets.

@lithdew
Created July 28, 2020 04:56
Show Gist options
  • Save lithdew/25ab42d89732f793532d7fdbda73489f to your computer and use it in GitHub Desktop.
Save lithdew/25ab42d89732f793532d7fdbda73489f to your computer and use it in GitHub Desktop.
zig rocksdb
const Builder = @import("std").build.Builder;
pub fn build(b: *Builder) void {
// Standard target options allows the person running `zig build` to choose
// what target to build for. Here we do not override the defaults, which
// means any target is allowed, and the default is native. Other options
// for restricting supported target set are available.
const target = b.standardTargetOptions(.{});
// Standard release options allow the person running `zig build` to select
// between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall.
const mode = b.standardReleaseOptions();
const exe = b.addExecutable("rocksdb-zig", "src/main.zig");
exe.setTarget(target);
exe.setBuildMode(mode);
exe.addLibPath("rocksdb");
exe.addIncludeDir("rocksdb/include");
// exe.linkLibC();
exe.linkSystemLibrary("rocksdb");
exe.install();
const run_cmd = exe.run();
run_cmd.step.dependOn(b.getInstallStep());
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
}
const std = @import("std");
const c = @cImport(@cInclude("rocksdb/c.h"));
const assert = std.debug.assert;
const print = std.debug.print;
pub fn main() !void {
const opts = c.rocksdb_options_create();
defer c.rocksdb_options_destroy(opts);
c.rocksdb_options_increase_parallelism(opts, 8);
c.rocksdb_options_optimize_level_style_compaction(opts, @boolToInt(false));
c.rocksdb_options_set_create_if_missing(opts, @boolToInt(true));
var err: ?[*:0]u8 = null;
const db = c.rocksdb_open(opts, "db", &err);
if (err) |message| @panic(std.mem.spanZ(message));
defer c.rocksdb_close(db);
// Put value.
const write_opts = c.rocksdb_writeoptions_create();
defer c.rocksdb_writeoptions_destroy(write_opts);
const key = "hello";
const val = "world";
c.rocksdb_put(db, write_opts, key, key.len, val, val.len, &err);
if (err) |message| @panic(std.mem.spanZ(message));
print("Put '{}' = '{}' into the database.\n", .{ key, val });
// Get value.
const read_opts = c.rocksdb_readoptions_create();
defer c.rocksdb_readoptions_destroy(read_opts);
var read_len: usize = undefined;
var read_ptr = c.rocksdb_get(db, read_opts, key, key.len, &read_len, &err);
if (err) |message| @panic(std.mem.spanZ(message));
defer std.c.free(read_ptr);
var read_val = read_ptr[0..read_len];
print("Value of key '{}' from the database is: '{}'\n", .{ key, read_val });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment