Skip to content

Commit 54e37ad

Browse files
server: simplify onInspector methods
Signed-off-by: Francis Bouvier <[email protected]>
1 parent 955cf5b commit 54e37ad

File tree

1 file changed

+19
-27
lines changed

1 file changed

+19
-27
lines changed

src/server.zig

Lines changed: 19 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -260,39 +260,31 @@ pub const Ctx = struct {
260260
}
261261
}
262262

263-
pub fn onInspectorResp(cmd_opaque: *anyopaque, _: u32, msg: []const u8) void {
264-
std.log.debug("onResp biz fn called: {s}", .{msg});
265-
const aligned = @as(*align(@alignOf(Ctx)) anyopaque, @alignCast(cmd_opaque));
266-
const self = @as(*Ctx, @ptrCast(aligned));
263+
inline fn inspectorCtx(ctx_opaque: *anyopaque) *Ctx {
264+
const aligned = @as(*align(@alignOf(Ctx)) anyopaque, @alignCast(ctx_opaque));
265+
return @as(*Ctx, @ptrCast(aligned));
266+
}
267267

268+
fn inspectorMsg(allocator: std.mem.Allocator, ctx: *Ctx, msg: []const u8) !void {
269+
// inject sessionID in cdp msg
268270
const tpl = "{s},\"sessionId\":\"{s}\"}}";
269271
const msg_open = msg[0 .. msg.len - 1]; // remove closing bracket
270-
const s = std.fmt.allocPrint(
271-
self.alloc(),
272-
tpl,
273-
.{ msg_open, cdp.ContextSessionID },
274-
) catch unreachable;
275-
defer self.alloc().free(s);
276-
277-
sendSync(self, s) catch unreachable;
272+
const s = try std.fmt.allocPrint(allocator, tpl, .{ msg_open, cdp.ContextSessionID });
273+
defer ctx.alloc().free(s);
274+
275+
try sendSync(ctx, s);
278276
}
279277

280-
pub fn onInspectorNotif(cmd_opaque: *anyopaque, msg: []const u8) void {
281-
std.log.debug("onNotif biz fn called: {s}", .{msg});
282-
const aligned = @as(*align(@alignOf(Ctx)) anyopaque, @alignCast(cmd_opaque));
283-
const self = @as(*Ctx, @ptrCast(aligned));
278+
pub fn onInspectorResp(ctx_opaque: *anyopaque, _: u32, msg: []const u8) void {
279+
std.log.debug("inspector resp: {s}", .{msg});
280+
const ctx = inspectorCtx(ctx_opaque);
281+
inspectorMsg(ctx.alloc(), ctx, msg) catch unreachable;
282+
}
284283

285-
const tpl = "{s},\"sessionId\":\"{s}\"}}";
286-
const msg_open = msg[0 .. msg.len - 1]; // remove closing bracket
287-
const s = std.fmt.allocPrint(
288-
self.alloc(),
289-
tpl,
290-
.{ msg_open, cdp.ContextSessionID },
291-
) catch unreachable;
292-
defer self.alloc().free(s);
293-
std.log.debug("event: {s}", .{s});
294-
295-
sendSync(self, s) catch unreachable;
284+
pub fn onInspectorNotif(ctx_opaque: *anyopaque, msg: []const u8) void {
285+
std.log.debug("inspector event: {s}", .{msg});
286+
const ctx = inspectorCtx(ctx_opaque);
287+
inspectorMsg(ctx.alloc(), ctx, msg) catch unreachable;
296288
}
297289
};
298290

0 commit comments

Comments
 (0)