ipc.zig 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /// Client side support for Zig IPC.
  2. const std = @import("std");
  3. const debug = std.debug;
  4. const fs = std.fs;
  5. const mem = std.mem;
  6. const Allocator = mem.Allocator;
  7. const Client = std.zig.Client;
  8. const ErrorBundle = std.zig.ErrorBundle;
  9. const Server = std.zig.Server;
  10. /// This data structure must be kept in sync with zig.Server.Message.EmitBinPath.
  11. const EmitBinPath = struct {
  12. flags: Flags,
  13. path: []const u8,
  14. pub const Flags = Server.Message.EmitBinPath.Flags;
  15. pub fn deinit(self: *EmitBinPath, allocator: Allocator) void {
  16. allocator.free(self.path);
  17. self.* = undefined;
  18. }
  19. };
  20. pub fn parseErrorBundle(allocator: Allocator, data: []const u8) !ErrorBundle {
  21. const EbHdr = Server.Message.ErrorBundle;
  22. const eb_hdr = @ptrCast(*align(1) const EbHdr, data);
  23. const extra_bytes =
  24. data[@sizeOf(EbHdr)..][0 .. @sizeOf(u32) * eb_hdr.extra_len];
  25. const string_bytes =
  26. data[@sizeOf(EbHdr) + extra_bytes.len ..][0..eb_hdr.string_bytes_len];
  27. // TODO: use @ptrCast when the compiler supports it
  28. const unaligned_extra = std.mem.bytesAsSlice(u32, extra_bytes);
  29. const extra_array = try allocator.alloc(u32, unaligned_extra.len);
  30. // TODO: use @memcpy when it supports slices
  31. //
  32. // Don't use the "multi-object for loop" syntax, in
  33. // order to avoid a syntax error with old Zig compilers.
  34. var i: usize = 0;
  35. while (i < extra_array.len) : (i += 1) {
  36. extra_array[i] = unaligned_extra[i];
  37. }
  38. return .{
  39. .string_bytes = try allocator.dupe(u8, string_bytes),
  40. .extra = extra_array,
  41. };
  42. }
  43. pub fn parseEmitBinPath(allocator: Allocator, data: []const u8) !EmitBinPath {
  44. const EbpHdr = Server.Message.EmitBinPath;
  45. const ebp_hdr = @ptrCast(*align(1) const EbpHdr, data);
  46. const path = try allocator.dupe(u8, data[@sizeOf(EbpHdr)..]);
  47. return .{
  48. .flags = ebp_hdr.flags,
  49. .path = path,
  50. };
  51. }
  52. pub fn sendMessage(file: fs.File, tag: Client.Message.Tag) !void {
  53. const header: Client.Message.Header = .{
  54. .tag = tag,
  55. .bytes_len = 0,
  56. };
  57. try file.writeAll(mem.asBytes(&header));
  58. }