aboutsummaryrefslogtreecommitdiff
path: root/src/http/header_builder.zig
blob: 540484655b15b4aa7e59f4abff082acd7b40ddbd (plain) (blame)
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
56
57
58
59
60
const HeaderBuilder = @This();
const StringBuilder = @import("../string_builder.zig");
const Headers = @import("./headers.zig");
const string = @import("root").bun.string;
const HTTPClient = @import("../http_client_async.zig");
const Api = @import("../api/schema.zig").Api;
const std = @import("std");

content: StringBuilder = StringBuilder{},
header_count: u64 = 0,
entries: Headers.Entries = Headers.Entries{},

pub fn count(this: *HeaderBuilder, name: string, value: string) void {
    this.header_count += 1;
    this.content.count(name);
    this.content.count(value);
}

pub fn allocate(this: *HeaderBuilder, allocator: std.mem.Allocator) !void {
    try this.content.allocate(allocator);
    try this.entries.ensureTotalCapacity(allocator, this.header_count);
}
pub fn append(this: *HeaderBuilder, name: string, value: string) void {
    const name_ptr = Api.StringPointer{
        .offset = @as(u32, @truncate(this.content.len)),
        .length = @as(u32, @truncate(name.len)),
    };

    _ = this.content.append(name);

    const value_ptr = Api.StringPointer{
        .offset = @as(u32, @truncate(this.content.len)),
        .length = @as(u32, @truncate(value.len)),
    };
    _ = this.content.append(value);
    this.entries.appendAssumeCapacity(Headers.Kv{ .name = name_ptr, .value = value_ptr });
}

pub fn appendFmt(this: *HeaderBuilder, name: string, comptime fmt: string, args: anytype) void {
    const name_ptr = Api.StringPointer{
        .offset = @as(u32, @truncate(this.content.len)),
        .length = @as(u32, @truncate(name.len)),
    };

    _ = this.content.append(name);

    const value = this.content.fmt(fmt, args);

    const value_ptr = Api.StringPointer{
        .offset = @as(u32, @truncate(this.content.len - value.len)),
        .length = @as(u32, @truncate(value.len)),
    };

    this.entries.appendAssumeCapacity(Headers.Kv{ .name = name_ptr, .value = value_ptr });
}

pub fn apply(this: *HeaderBuilder, client: *HTTPClient) void {
    client.header_entries = this.entries;
    client.header_buf = this.content.ptr.?[0..this.content.len];
}