aboutsummaryrefslogtreecommitdiff
path: root/src/proto/query.zig
blob: 9f238fc76cc5cd0a7c4d7c987e90c903f204660d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
const std = @import("std");
const log = std.log.scoped(.pgz);
const ByteArrayList = std.ArrayList(u8);
const ProtocolError = @import("../main.zig").ProtocolError;
const ClientError = @import("../main.zig").ClientError;
const enum_from_int = @import("../main.zig").enum_from_int;

pub const Tag: u8 = 'Q';

const Query = @This();

string: []const u8,
owned: bool = false,

pub fn read(a: std.mem.Allocator, b: []const u8) !Query {
    return .{
        .string = try a.dupe(u8, b[0..(b.len-1)]), // Drop the null terminator
        .owned = true,
    };
}

pub fn write(self: Query, _: std.mem.Allocator, stream_writer: anytype) !void {
    try stream_writer.writeByte(Tag);
    try stream_writer.writeIntBig(u32, @as(u32, @intCast(self.string.len+5)));
    try stream_writer.writeAll(self.string);
    try stream_writer.writeByte(0);
}

pub fn deinit(self: *Query, a: std.mem.Allocator) void {
    if (self.owned) a.free(self.string);
}

test "round trip" {
    const allocator = std.testing.allocator;
    var sm = Query{
        .string = "Hello",
    };
    defer sm.deinit(allocator);

    var bal = ByteArrayList.init(allocator);
    defer bal.deinit();
    try sm.write(allocator, bal.writer());

    var fbs = std.io.fixedBufferStream(bal.items);
    var reader = fbs.reader();
    const tag = try reader.readByte();
    try std.testing.expectEqual(Tag, tag);
    const len = try reader.readIntBig(u32);
    const buf = try allocator.alloc(u8, len - 4);
    defer allocator.free(buf);
    try reader.readNoEof(buf);
    var sm2 = try Query.read(allocator, buf);
    defer sm2.deinit(allocator);
    try std.testing.expectEqualStrings("Hello", sm2.string);
}