Skip to content

Instantly share code, notes, and snippets.

@creationix
Created March 9, 2021 20:03
Show Gist options
  • Save creationix/1c11d155c40f09b656ae9ef4bcb986c5 to your computer and use it in GitHub Desktop.
Save creationix/1c11d155c40f09b656ae9ef4bcb986c5 to your computer and use it in GitHub Desktop.
extern fn wsSendText(client: *Client, message: CSlice(u8)) void;
extern fn wsSendBInary(client: *Client, message: CSlice(u8)) void;
extern fn wsClose(client: *Client) void;
fn CSlice(comptime T: type) type {
return extern struct {
ptr: [*]const T,
len: usize,
pub fn fromSlice(slice: []const T) CSlice(T) {
return .{ .ptr = slice.ptr, .len = slice.len };
}
pub fn toSlice(self: CSlice(T)) []const T {
return self.ptr[0..self.len];
}
};
}
export fn add(a: i32, b:i32) i32 {
return a + b;
}
const Client = opaque {
pub fn sendText(self: *Client, message: []const u8) void {
return wsSendText(self, CSlice(u8).fromSlice(message));
}
pub fn sendBinary(self: *Client, message: []const u8) void {
return wsSendBInary(self, CSlice(u8).fromSlice(message));
}
pub fn close(self: *Client) void {
return wsClose(self);
}
};
// Websocket connect event handler
export fn connect(client: *Client, path: CSlice(u8), headers: CSlice(CSlice(u8))) usize {
var sum: usize = 0;
// Echo back the path as a websocket text message to test this working.
client.sendText(path.toSlice());
for (headers.toSlice()) |entry, index| {
sum += index;
client.sendBinary(entry.toSlice());
}
client.close();
return sum;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment