Skip to content

Instantly share code, notes, and snippets.

@meme
Created January 17, 2020 03:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save meme/cb6d455a6f00b1fe798a378ced19c651 to your computer and use it in GitHub Desktop.
Save meme/cb6d455a6f00b1fe798a378ced19c651 to your computer and use it in GitHub Desktop.
const std = @import("std");
const c = @cImport({
@cInclude("X11/Xlib.h");
@cInclude("time.h");
});
const X11Error = error{
NoDisplay,
InternalError,
SyncFailed,
};
const X11 = struct {
handle: ?*c.Display,
pub fn new() X11Error!X11 {
const handle = c.XOpenDisplay(null);
if (handle == null) {
return X11Error.NoDisplay;
}
return X11 {
.handle = handle
};
}
pub fn setName(self: X11, name: []const u8) X11Error!void {
if (c.XStoreName(self.handle, c.XDefaultRootWindow(self.handle),
name[0.. :0]) == 0) {
return X11Error.InternalError;
}
if (c.XSync(self.handle, c.True) == 0) {
return X11Error.SyncFailed;
}
}
};
fn currentTime() []const u8 {
var buffer: [64]u8 = undefined;
const clock: c.time_t = c.time(null);
const time: ?*c.tm = c.localtime(&clock);
const size = c.strftime(&buffer, buffer.len, "%Y-%m-%d %H:%M:%S", time);
return buffer[0..size];
}
pub fn main() anyerror!void {
const desktop = try X11.new();
const time = currentTime();
try desktop.setName(time);
}
@meme
Copy link
Author

meme commented Jan 17, 2020

03:20 <andrewrk> another user recently figured out how to use creduce with zig
03:22 <andrewrk> keegans, this is definitely a compiler bug, but name[0.. :0] is almost certainly incorrect, because you're accessing outside the name slice
03:22 <andrewrk> if the byte after the name slice is 0 then it should be `name: [:0]const u8` rather than `name: []const u8`
03:23 <andrewrk> so you don't need name[0.. :0] at all, just name. but update the parameter type. and update currentTime to return [:0]const u8 instead of []const u8, by changing buffer[0..size] to buffer[0..size :0]
03:24 <andrewrk> give the type system all that juicy info

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment