diff --git a/src/main.zig b/src/main.zig index 725171c..60e71af 100644 --- a/src/main.zig +++ b/src/main.zig @@ -8,6 +8,7 @@ const calendar = @import("modules/calendar.zig"); const display = @import("modules/display.zig"); const uptime = @import("modules/uptime.zig"); const volume = @import("modules/volume.zig"); +const memory = @import("modules/memory.zig"); const Module = @import("module.zig"); pub fn main() !void { @@ -23,6 +24,7 @@ pub fn main() !void { var modules = [_]Module{ uptime.init(arena.allocator()).module, + memory.init(arena.allocator()).module, volume.init(arena.allocator()).module, display.init(arena.allocator()).module, battery.init(arena.allocator()).module, diff --git a/src/modules/memory.zig b/src/modules/memory.zig new file mode 100644 index 0000000..b7291a2 --- /dev/null +++ b/src/modules/memory.zig @@ -0,0 +1,40 @@ +const std = @import("std"); +const Module = @import("../module.zig"); +const Self = @This(); + +module: Module, + +pub fn init(allocator: std.mem.Allocator) Self { + return .{ + .module = .{ + .allocator = allocator, + .getJsonFn = getJson, + }, + }; +} + +pub fn getJson(module: *const Module) !Module.JSON { + const self = @fieldParentPtr(Self, "module", module); + + var meminfo_file = try std.fs.openFileAbsolute("/proc/meminfo", .{}); + defer meminfo_file.close(); + + const meminfo_string = try meminfo_file.reader().readAllAlloc(self.module.allocator, 4096); + const mem_total_idx = std.mem.indexOf(u8, meminfo_string, "MemTotal:"); + const mem_available_idx = std.mem.indexOf(u8, meminfo_string, "MemAvailable:"); + const mem_total_newline = std.mem.indexOfScalarPos(u8, meminfo_string, mem_total_idx.?, '\n'); + const mem_available_newline = std.mem.indexOfScalarPos(u8, meminfo_string, mem_available_idx.?, '\n'); + var mem_total_split = std.mem.splitBackwardsScalar(u8, meminfo_string[mem_total_idx.?..mem_total_newline.?], ' '); + var mem_available_split = std.mem.splitBackwardsScalar(u8, meminfo_string[mem_available_idx.?..mem_available_newline.?], ' '); + _ = mem_total_split.next(); + _ = mem_available_split.next(); + + const mem_total = try std.fmt.parseInt(usize, mem_total_split.next().?, 10); + const mem_available = try std.fmt.parseInt(usize, mem_available_split.next().?, 10); + + const mem = @as(f32, @floatFromInt(mem_total)) - @as(f32, @floatFromInt(mem_available)); + + return .{ + .full_text = try std.fmt.allocPrint(self.module.allocator, "{d:.3} GB", .{mem / 1000 / 1000}), + }; +}