Skip to content

Commit

Permalink
all the const
Browse files Browse the repository at this point in the history
  • Loading branch information
donpdonp committed Jul 8, 2024
1 parent bb88115 commit 48c4a45
Show file tree
Hide file tree
Showing 15 changed files with 112 additions and 50 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/config.json
/db/
/zig-cache/
/.zig-cache/
/zig-out/
/cache/
/ragel/*.c
Expand Down
18 changes: 9 additions & 9 deletions build.zig
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,19 @@ pub fn build(b: *std.Build) void {
// set a preferred release mode, allowing the user to decide how to optimize.
const optimize = b.standardOptimizeOption(.{});

const lib = b.addStaticLibrary(.{
.name = "zootdeck",
// In this case the main source file is merely a path, however, in more
// complicated build scripts, this could be a generated file.
.root_source_file = .{ .src_path = .{ .sub_path = "src/root.zig", .owner = b } },
.target = target,
.optimize = optimize,
});
// const lib = b.addStaticLibrary(.{
// .name = "zootdeck",
// // In this case the main source file is merely a path, however, in more
// // complicated build scripts, this could be a generated file.
// .root_source_file = .{ .src_path = .{ .sub_path = "src/root.zig", .owner = b } },
// .target = target,
// .optimize = optimize,
// });

// This declares intent for the library to be installed into the standard
// location when the user invokes the "install" step (the default step when
// running `zig build`).
b.installArtifact(lib);
// b.installArtifact(lib);

const exe = b.addExecutable(.{
.name = "zootdeck",
Expand Down
62 changes: 62 additions & 0 deletions build.zig.zon
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
.{
.name = "zootdeck",
// This is a [Semantic Version](https://semver.org/).
// In a future version of Zig it will be used for package deduplication.
.version = "0.0.0",

// This field is optional.
// This is currently advisory only; Zig does not yet do anything
// with this value.
//.minimum_zig_version = "0.11.0",

// This field is optional.
// Each dependency must either provide a `url` and `hash`, or a `path`.
// `zig build --fetch` can be used to fetch all dependencies of a package, recursively.
// Once all dependencies are fetched, `zig build` no longer requires
// internet connectivity.
.dependencies = .{
// See `zig fetch --save <url>` for a command-line interface for adding dependencies.
//.example = .{
// // When updating this field to a new URL, be sure to delete the corresponding
// // `hash`, otherwise you are communicating that you expect to find the old hash at
// // the new URL.
// .url = "https://example.com/foo.tar.gz",
//
// // This is computed from the file contents of the directory of files that is
// // obtained after fetching `url` and applying the inclusion rules given by
// // `paths`.
// //
// // This field is the source of truth; packages do not come from a `url`; they
// // come from a `hash`. `url` is just one of many possible mirrors for how to
// // obtain a package matching this `hash`.
// //
// // Uses the [multihash](https://multiformats.io/multihash/) format.
// .hash = "...",
//
// // When this is provided, the package is found in a directory relative to the
// // build root. In this case the package's hash is irrelevant and therefore not
// // computed. This field and `url` are mutually exclusive.
// .path = "foo",
//},
},

// Specifies the set of files and directories that are included in this package.
// Only files and directories listed here are included in the `hash` that
// is computed for this package.
// Paths are relative to the build root. Use the empty string (`""`) to refer to
// the build root itself.
// A directory listed here means that all files within, recursively, are included.
.paths = .{
// This makes *all* files, recursively, included in this package. It is generally
// better to explicitly list the files and directories instead, to insure that
// fetching from tarballs, file system paths, and version control all result
// in the same contents hash.
"",
// For example...
//"build.zig",
//"build.zig.zon",
//"src",
//"LICENSE",
//"README.md",
},
}
16 changes: 8 additions & 8 deletions src/config.zig
Original file line number Diff line number Diff line change
Expand Up @@ -125,12 +125,12 @@ pub fn readfile(filename: []const u8) !Settings {
},
else => return err,
};
var json = try std.fs.cwd().readFileAlloc(allocator, filename, std.math.maxInt(usize));
const json = try std.fs.cwd().readFileAlloc(allocator, filename, std.math.maxInt(usize));
return read(json);
}

pub fn read(json: []const u8) !Settings {
var value_tree = try std.json.parseFromSlice(std.json.Value, allocator, json, .{});
const value_tree = try std.json.parseFromSlice(std.json.Value, allocator, json, .{});
var root = value_tree.value.object;
var settings = allocator.create(Settings) catch unreachable;
settings.columns = std.ArrayList(*ColumnInfo).init(allocator);
Expand All @@ -153,14 +153,14 @@ pub fn read(json: []const u8) !Settings {
var colInfo = allocator.create(ColumnInfo) catch unreachable;
colInfo.reset();
colInfo.toots = toot_list.TootList.init();
var colconfig = allocator.create(ColumnConfig) catch unreachable;
const colconfig = allocator.create(ColumnConfig) catch unreachable;
colInfo.config = colconfig;
var title = value.object.get("title").?.string;
const title = value.object.get("title").?.string;
colInfo.config.title = title;
var filter = value.object.get("filter").?.string;
const filter = value.object.get("filter").?.string;
colInfo.config.filter = filter;
colInfo.filter = filter_lib.parse(allocator, filter);
var tokenTag = value.object.get("token");
const tokenTag = value.object.get("token");
if (tokenTag) |tokenKV| {
if (@TypeOf(tokenKV) == []const u8) {
colInfo.config.token = tokenKV.value.string;
Expand All @@ -170,7 +170,7 @@ pub fn read(json: []const u8) !Settings {
} else {
colInfo.config.token = null;
}
var img_only = value.object.get("img_only").?.bool;
const img_only = value.object.get("img_only").?.bool;
colInfo.config.img_only = img_only;
settings.columns.append(colInfo) catch unreachable;
}
Expand Down Expand Up @@ -205,7 +205,7 @@ pub fn now() Time {

const assert = @import("std").debug.assert;
test "read" {
var ret = read("{\"url\":\"abc\"}");
const ret = read("{\"url\":\"abc\"}");
if (ret) {
assert(true);
} else |err| {
Expand Down
4 changes: 2 additions & 2 deletions src/db/file.zig
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ pub fn has(namespace: []const u8, key: []const u8, allocator: Allocator) bool {
_ = namespace;
_ = key;
_ = allocator;
var keypath = "Z"; //std.fmt.allocPrint(allocator, "{s}/{s}/{s}", .{ cache_dir, namespace, key }) catch unreachable;
const keypath = "Z"; //std.fmt.allocPrint(allocator, "{s}/{s}/{s}", .{ cache_dir, namespace, key }) catch unreachable;
var found = false;
if (std.fs.cwd().access(keypath, .{ .mode = .read_only })) {
found = true;
Expand All @@ -30,7 +30,7 @@ pub fn write(namespace: []const u8, key: []const u8, value: []const u8, allocato
_ = cache_dir;
_ = namespace;
_ = allocator;
var dirpath = "Z"; //try std.fmt.allocPrint(allocator, "{s}/{s}", .{ cache_dir, namespace });
const dirpath = "Z"; //try std.fmt.allocPrint(allocator, "{s}/{s}", .{ cache_dir, namespace });
warn("MKDIR {s}\n", .{dirpath});
var dir = std.fs.Dir.makeOpenPath(std.fs.cwd(), dirpath, .{}) catch unreachable;
defer dir.close();
Expand Down
14 changes: 7 additions & 7 deletions src/db/lmdb.zig
Original file line number Diff line number Diff line change
Expand Up @@ -39,21 +39,21 @@ pub fn stats() void {
}

pub fn write(namespace: []const u8, key: []const u8, value: []const u8, allocator: Allocator) !void {
var txnptr = allocator.create(*c.struct_MDB_txn) catch unreachable;
var ctxnMaybe = @as([*c]?*c.struct_MDB_txn, @ptrCast(txnptr));
const txnptr = allocator.create(*c.struct_MDB_txn) catch unreachable;
const ctxnMaybe = @as([*c]?*c.struct_MDB_txn, @ptrCast(txnptr));
var ret = c.mdb_txn_begin(env, null, 0, ctxnMaybe);
if (ret == 0) {
// warn("lmdb write {} {}={}\n", namespace, key, value);
var dbiptr = allocator.create(c.MDB_dbi) catch unreachable;
const dbiptr = allocator.create(c.MDB_dbi) catch unreachable;
ret = c.mdb_dbi_open(txnptr.*, null, c.MDB_CREATE, dbiptr);
if (ret == 0) {
// TODO: seperator issue. perhaps 2 byte invalid utf8 sequence
var fullkey = "Z";
const fullkey = "Z";
_ = key;
_ = namespace;
//std.fmt.allocPrint(allocator, "{s}:{s}", .{ namespace, key }) catch unreachable;
var mdb_key = mdbVal(fullkey, allocator);
var mdb_value = mdbVal(value, allocator);
const mdb_key = mdbVal(fullkey, allocator);
const mdb_value = mdbVal(value, allocator);
ret = c.mdb_put(txnptr.*, dbiptr.*, mdb_key, mdb_value, 0);
if (ret == 0) {
ret = c.mdb_txn_commit(txnptr.*);
Expand All @@ -78,7 +78,7 @@ pub fn write(namespace: []const u8, key: []const u8, value: []const u8, allocato
}

fn mdbVal(data: []const u8, allocator: Allocator) *c.MDB_val {
var dataptr = @as(?*anyopaque, @ptrFromInt(@intFromPtr(data.ptr)));
const dataptr = @as(?*anyopaque, @ptrFromInt(@intFromPtr(data.ptr)));
var mdb_val = allocator.create(c.MDB_val) catch unreachable;
mdb_val.mv_size = data.len;
mdb_val.mv_data = dataptr;
Expand Down
2 changes: 1 addition & 1 deletion src/filter.zig
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ pub const ptree = struct {

pub fn parse(allocator: Allocator, lang: []const u8) *ptree {
var ragel_points = c.urlPoints{ .scheme_pos = 0, .loc_pos = 0 };
var clang = util.sliceToCstr(allocator, lang);
const clang = util.sliceToCstr(allocator, lang);
_ = c.url(clang, &ragel_points);
warn("ragel parse \"{s}\"\n", .{lang});

Expand Down
2 changes: 1 addition & 1 deletion src/heartbeat.zig
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ pub fn init(myAllocator: Allocator) !void {
}

pub fn go(actor_ptr: ?*anyopaque) callconv(.C) ?*anyopaque {
var actor = @as(*thread.Actor, @ptrCast(@alignCast(actor_ptr)));
const actor = @as(*thread.Actor, @ptrCast(@alignCast(actor_ptr)));
util.log("heartbeat mainloop started", .{});
const sleep_seconds = 60;
while (true) {
Expand Down
6 changes: 3 additions & 3 deletions src/html.zig
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ pub fn parse(html: []const u8) *Node {
.fragment_context = c.GUMBO_TAG_BODY,
.fragment_namespace = c.GUMBO_NAMESPACE_HTML,
};
var doc = c.gumbo_parse_with_options(&options, html.ptr, html.len);
var root = doc.*.root;
const doc = c.gumbo_parse_with_options(&options, html.ptr, html.len);
const root = doc.*.root;
//var tagType = root.*.type;
//var tagName = root.*.v.element.tag;
return root;
Expand All @@ -33,7 +33,7 @@ pub fn search(node: *Node) void {
if (node.v.element.tag == c.GUMBO_TAG_A) {
//warn("A TAG found\n");
}
var children = node.v.element.children;
const children = node.v.element.children;
var idx = @as(u32, @intCast(0));
while (idx < children.length) : (idx += 1) {
const cnode = children.data[idx];
Expand Down
8 changes: 4 additions & 4 deletions src/ipc/epoll.zig
Original file line number Diff line number Diff line change
Expand Up @@ -71,19 +71,19 @@ pub fn wait() *Client {
warn("epoll_wait ignoring errno {}\n", .{errno});
}
}
var client = @as(*Client, @ptrCast(@alignCast(events_waiting[0].data.ptr)));
const client = @as(*Client, @ptrCast(@alignCast(events_waiting[0].data.ptr)));
return client;
}

pub fn read(client: *Client, buf: []u8) []u8 {
const pkt_fixed_portion = 1;
var readCountOrErr = c.read(client.readSocket, buf.ptr, pkt_fixed_portion);
const readCountOrErr = c.read(client.readSocket, buf.ptr, pkt_fixed_portion);
if (readCountOrErr >= pkt_fixed_portion) {
const msglen: usize = buf[0];
var msgrecv = @as(usize, @intCast(readCountOrErr - pkt_fixed_portion));
if (msgrecv < msglen) {
var msgleft = msglen - msgrecv;
var r2ce = c.read(client.readSocket, buf.ptr, msgleft);
const msgleft = msglen - msgrecv;
const r2ce = c.read(client.readSocket, buf.ptr, msgleft);
if (r2ce >= 0) {
msgrecv += @as(usize, @intCast(r2ce));
} else {
Expand Down
2 changes: 1 addition & 1 deletion src/main.zig
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ pub fn main() !void {

if (config.readfile(config.config_file_path())) |config_data| {
settings = config_data;
var dummy_payload = alloc.create(thread.CommandVerb) catch unreachable;
const dummy_payload = alloc.create(thread.CommandVerb) catch unreachable;
_ = try thread.create("gui", gui.go, dummy_payload, guiback);
_ = try thread.create("heartbeat", heartbeat.go, dummy_payload, heartback);

Expand Down
12 changes: 6 additions & 6 deletions src/net.zig
Original file line number Diff line number Diff line change
Expand Up @@ -50,13 +50,13 @@ pub fn go(data: ?*anyopaque) callconv(.C) ?*anyopaque {

pub fn httpget(req: *config.HttpInfo) ![]const u8 {
_ = c.curl_global_init(0);
var curl = c.curl_easy_init();
const curl = c.curl_easy_init();
if (curl != null) {
var cstr = util.sliceAddNull(allocator, req.url);
const cstr = util.sliceAddNull(allocator, req.url);
_ = c.curl_easy_setopt(curl, c.CURLOPT_URL, cstr.ptr);

var zero: c_long = 0;
var seconds: c_long = 30;
const zero: c_long = 0;
const seconds: c_long = 30;
_ = c.curl_easy_setopt(curl, c.CURLOPT_CONNECTTIMEOUT, seconds);
_ = c.curl_easy_setopt(curl, c.CURLOPT_SSL_VERIFYPEER, zero);
_ = c.curl_easy_setopt(curl, c.CURLOPT_SSL_VERIFYHOST, zero);
Expand All @@ -82,7 +82,7 @@ pub fn httpget(req: *config.HttpInfo) ![]const u8 {
},
}

var res = c.curl_easy_perform(curl);
const res = c.curl_easy_perform(curl);
defer c.curl_easy_cleanup(curl);
if (res == c.CURLE_OK) {
_ = c.curl_easy_getinfo(curl, c.CURLINFO_RESPONSE_CODE, &req.response_code);
Expand Down Expand Up @@ -114,7 +114,7 @@ pub fn httpget(req: *config.HttpInfo) ![]const u8 {

pub fn curl_write(ptr: [*c]const u8, _: usize, nmemb: usize, userdata: *anyopaque) usize {
var buf = @as(*std.ArrayList(u8), @ptrCast(@alignCast(userdata)));
var body_part: []const u8 = ptr[0..nmemb];
const body_part: []const u8 = ptr[0..nmemb];
buf.appendSlice(body_part) catch |err| {
warn("curl_write append fail {}\n", .{err});
};
Expand Down
6 changes: 3 additions & 3 deletions src/thread.zig
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ pub fn create(
actor.name = actor_name;
//ipc.register(actor.client, recvback);
const null_pattr = @as([*c]const c.union_pthread_attr_t, @ptrFromInt(0));
var pt_err = c.pthread_create(&actor.thread_id, null_pattr, startFn, actor);
const pt_err = c.pthread_create(&actor.thread_id, null_pattr, startFn, actor);
try actors.putNoClobber(actor.thread_id, actor);
if (pt_err == 0) {
return actor;
Expand Down Expand Up @@ -81,7 +81,7 @@ pub fn self() c.pthread_t {
}

pub fn wait() void {
var client = ipc.wait();
const client = ipc.wait();

var bufArray = [_]u8{0} ** 16; // arbitrary receive buffer
const buf: []u8 = ipc.read(client, bufArray[0..]);
Expand All @@ -90,7 +90,7 @@ pub fn wait() void {
warn("thread.wait ipc.read no socket payload! DEFLECTED!\n", .{});
} else {
const b8: *[@sizeOf(usize)]u8 = @as(*[@sizeOf(usize)]u8, @ptrCast(buf.ptr));
var command: *Command = std.mem.bytesAsValue(*Command, b8).*;
const command: *Command = std.mem.bytesAsValue(*Command, b8).*;
var iter = actors.iterator();
while (iter.next()) |entry| {
const actor = entry.value_ptr.*;
Expand Down
2 changes: 1 addition & 1 deletion src/toot.zig
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ pub fn Toot() type {
}

pub fn imgCount(self: *Self) usize {
var images = self.hashmap.get("media_attachments").?.Array;
const images = self.hashmap.get("media_attachments").?.Array;
return images.items.len;
}
};
Expand Down
6 changes: 3 additions & 3 deletions src/util.zig
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ pub fn sliceToCstr(allocator: Allocator, str: []const u8) [*]u8 {
}

pub fn cstrToSliceCopy(allocator: Allocator, cstr: [*c]const u8) []const u8 {
var i: usize = std.mem.len(cstr);
var ram = allocator.alloc(u8, i) catch unreachable;
const i: usize = std.mem.len(cstr);
const ram = allocator.alloc(u8, i) catch unreachable;
std.mem.copy(u8, ram, cstr[0..i]);
return ram;
}
Expand Down Expand Up @@ -132,6 +132,6 @@ pub fn htmlEntityDecode(str: []const u8, allocator: Allocator) ![]const u8 {

test "htmlEntityParse" {
const allocator = std.debug.global_allocator;
var stripped = htmlEntityDecode("amp&amp;pam", allocator) catch unreachable;
const stripped = htmlEntityDecode("amp&amp;pam", allocator) catch unreachable;
std.testing.expect(std.mem.eql(u8, stripped, "amp&pam"));
}

0 comments on commit 48c4a45

Please sign in to comment.