Zig 0.17.0-dev (Split by item)

Shortcut keys
?
Show these tips
S
Focus search field
Esc
Clear focus & close tips
U
Jump to source code
↑
Move up in search results
↓
Move down in search results
↵
Go to active search result
This is an example of documentation generated by ZigDoc, an alternative to Zig's built-in Auto Doc feature. See also examples in other modes/formats. The project being documented here (as the example) is the Zig standard library. Public Struct

Encoder

Public Struct

A buffered DER encoder.

Prefers calling container's fn encodeDer(self: @This(), encoder: *der.Encoder). That function should encode values, lengths, then tags.

Fields

buffer: ArrayListReverse
field_tag: ?FieldTag = null

The field tag set by a parent container. This is needed because we might visit an implicitly tagged container with a fn encodeDer.

Namespaces

Structs

Values

Functions

pub fn init(allocator: std.mem.Allocator) Encoder
pub fn deinit(self: *Encoder) void
pub fn any(self: *Encoder, val: anytype) !void

Encode any value.

fn checkAnyEncoding(T: type, value: T, expected: []const u8) !void
fn anyTag(self: *Encoder, tag_: Tag, val: anytype) !void
pub fn tag(self: *Encoder, tag_: Tag) !void

Encode a tag.

fn mergedTag(self: *Encoder, tag_: Tag) Tag
pub fn length(self: *Encoder, len: usize) !void

Encode a length.

pub fn tagBytes(self: *Encoder, tag_: Tag, bytes: []const u8) !void

Encode a tag and length-prefixed bytes.

pub fn prependBytes(self: *Encoder, bytes: []const u8) !void

Write raw bytes. The encoder builds its output back-to-front, so chained calls should be made in reverse of the desired on-wire order.

fn int(self: *Encoder, comptime T: type, value: T) !void

File

crypto/codecs/asn1/der/Encoder.zig
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
//! A buffered DER encoder.
//!
//! Prefers calling container's `fn encodeDer(self: @This(), encoder: *der.Encoder)`.
//! That function should encode values, lengths, then tags.
buffer: ArrayListReverse,
/// The field tag set by a parent container.
/// This is needed because we might visit an implicitly tagged container with a `fn encodeDer`.
field_tag: ?FieldTag = null,

pub fn init(allocator: std.mem.Allocator) Encoder {
    return Encoder{ .buffer = ArrayListReverse.init(allocator) };
}

pub fn deinit(self: *Encoder) void {
    self.buffer.deinit();
}

/// Encode any value.
pub fn any(self: *Encoder, val: anytype) !void {
    const T = @TypeOf(val);
    try self.anyTag(Tag.fromZig(T), val);
}

test any {
    const Enum = enum(u8) {
        x = 0,
    };

    try checkAnyEncoding(u16, 0, &.{ 0x02, 0x01, 0x00 });
    try checkAnyEncoding(Enum, .x, &.{ 0x0a, 0x01, 0x00 });
}

fn checkAnyEncoding(T: type, value: T, expected: []const u8) !void {
    var encoder: @This() = .init(std.testing.allocator);
    defer encoder.deinit();

    try encoder.any(value);
    const encoded = try encoder.buffer.toOwnedSlice();
    defer std.testing.allocator.free(encoded);

    try std.testing.expectEqualSlices(u8, expected, encoded);
}

fn anyTag(self: *Encoder, tag_: Tag, val: anytype) !void {
    const T = @TypeOf(val);
    if (std.meta.hasFn(T, "encodeDer")) return try val.encodeDer(self);
    const outer_field_tag = self.field_tag;
    const start = self.buffer.data.len;
    const merged_tag = self.mergedTag(tag_);

    switch (@typeInfo(T)) {
        .@"struct" => |info| {
            inline for (0..info.field_names.len) |i| {
                const f_idx = info.field_names.len - i - 1;
                const f_name = info.field_names[f_idx];
                const f_type = info.field_types[f_idx];
                const f_attrs = info.field_attrs[f_idx];
                const field_val = @field(val, f_name);
                const field_tag = FieldTag.fromContainer(T, f_name);

                // > The encoding of a set value or sequence value shall not include an encoding for any
                // > component value which is equal to its default value.
                const is_default = if (f_attrs.@"comptime") false else if (f_attrs.defaultValue(f_type)) |default_val| brk: {
                    break :brk std.mem.eql(u8, std.mem.asBytes(&default_val), std.mem.asBytes(&field_val));
                } else false;
                const is_null_optional = if (@typeInfo(f_type) == .optional) field_val == null else false;

                if (!is_default and !is_null_optional) {
                    const start2 = self.buffer.data.len;
                    self.field_tag = field_tag;
                    // will merge with self.field_tag.
                    // may mutate self.field_tag.
                    try self.anyTag(Tag.fromZig(f_type), field_val);
                    if (field_tag) |ft| {
                        if (ft.explicit) {
                            try self.length(self.buffer.data.len - start2);
                            try self.tag(ft.toTag());
                            self.field_tag = null;
                        }
                    }
                }
            }
            self.field_tag = outer_field_tag;
        },
        .bool => try self.buffer.prependSlice(&[_]u8{if (val) 0xff else 0}),
        .int => try self.int(T, val),
        .@"enum" => |e| {
            if (@hasDecl(T, "oids")) {
                return self.any(T.oids.enumToOid(val));
            } else {
                try self.int(e.tag_type, @backingInt(val));
            }
        },
        .optional => if (val) |v| return try self.anyTag(tag_, v) else return,
        .null => {},
        else => @compileError("cannot encode type " ++ @typeName(T)),
    }

    try self.length(self.buffer.data.len - start);
    try self.tag(merged_tag);
}

/// Encode a tag.
pub fn tag(self: *Encoder, tag_: Tag) !void {
    const t = self.mergedTag(tag_);
    var buf: [Tag.max_encoded_len]u8 = undefined;
    try self.buffer.prependSlice(t.encodeToSlice(&buf));
}

fn mergedTag(self: *Encoder, tag_: Tag) Tag {
    var res = tag_;
    if (self.field_tag) |ft| {
        if (!ft.explicit) {
            res.number = @fromBackingInt(@intCast(ft.number));
            res.class = ft.class;
        }
    }
    return res;
}

/// Encode a length.
pub fn length(self: *Encoder, len: usize) !void {
    if (len < 128) return self.buffer.prependSlice(&.{@intCast(len)});
    const len32 = std.math.cast(u32, len) orelse return error.InvalidLength;
    var buf: [@sizeOf(u32) + 1]u8 = undefined;
    std.mem.writeInt(u32, buf[1..], len32, .big);
    var first: usize = 1;
    while (buf[first] == 0) first += 1;
    buf[first - 1] = @intCast((buf.len - first) | 0x80);
    return self.buffer.prependSlice(buf[first - 1 ..]);
}

/// Encode a tag and length-prefixed bytes.
pub fn tagBytes(self: *Encoder, tag_: Tag, bytes: []const u8) !void {
    try self.buffer.prependSlice(bytes);
    try self.length(bytes.len);
    try self.tag(tag_);
}

/// Write raw bytes. The encoder builds its output back-to-front, so chained
/// calls should be made in reverse of the desired on-wire order.
pub fn prependBytes(self: *Encoder, bytes: []const u8) !void {
    return self.buffer.prependSlice(bytes);
}

fn int(self: *Encoder, comptime T: type, value: T) !void {
    const info = @typeInfo(T).int;
    const Unsigned = @Int(.unsigned, info.bits);
    const pad: u8 = if (info.signedness == .signed and value < 0) 0xff else 0;
    var buf: [@sizeOf(Unsigned) + 1]u8 = undefined;
    buf[0] = pad;
    std.mem.writeInt(Unsigned, buf[1..], @bitCast(value), .big);

    var first: usize = 0;
    while (first + 1 < buf.len and buf[first] == pad and (buf[first + 1] ^ pad) & 0x80 == 0) first += 1;
    try self.buffer.prependSlice(buf[first..]);
}

test int {
    const allocator = std.testing.allocator;
    var encoder = Encoder.init(allocator);
    defer encoder.deinit();

    try encoder.int(u8, 0);
    try std.testing.expectEqualSlices(u8, &.{0}, encoder.buffer.data);

    encoder.buffer.clearAndFree();
    try encoder.int(u16, 0x00ff);
    try std.testing.expectEqualSlices(u8, &.{ 0, 0xff }, encoder.buffer.data);

    encoder.buffer.clearAndFree();
    try encoder.int(u32, 0xffff);
    try std.testing.expectEqualSlices(u8, &.{ 0, 0xff, 0xff }, encoder.buffer.data);

    encoder.buffer.clearAndFree();
    try encoder.int(u32, 0x01020304);
    try std.testing.expectEqualSlices(u8, &.{ 0x01, 0x02, 0x03, 0x04 }, encoder.buffer.data);

    encoder.buffer.clearAndFree();
    try encoder.int(u8, 127);
    try std.testing.expectEqualSlices(u8, &.{0x7f}, encoder.buffer.data);

    encoder.buffer.clearAndFree();
    try encoder.int(u16, 128);
    try std.testing.expectEqualSlices(u8, &.{ 0, 0x80 }, encoder.buffer.data);

    encoder.buffer.clearAndFree();
    try encoder.int(u16, 256);
    try std.testing.expectEqualSlices(u8, &.{ 0x01, 0x00 }, encoder.buffer.data);

    encoder.buffer.clearAndFree();
    try encoder.int(u8, 128);
    try std.testing.expectEqualSlices(u8, &.{ 0, 0x80 }, encoder.buffer.data);

    encoder.buffer.clearAndFree();
    try encoder.int(u8, 255);
    try std.testing.expectEqualSlices(u8, &.{ 0, 0xff }, encoder.buffer.data);

    encoder.buffer.clearAndFree();
    try encoder.int(u16, 0x8000);
    try std.testing.expectEqualSlices(u8, &.{ 0, 0x80, 0 }, encoder.buffer.data);

    encoder.buffer.clearAndFree();
    try encoder.int(i8, -1);
    try std.testing.expectEqualSlices(u8, &.{0xff}, encoder.buffer.data);

    encoder.buffer.clearAndFree();
    try encoder.int(i8, -128);
    try std.testing.expectEqualSlices(u8, &.{0x80}, encoder.buffer.data);

    encoder.buffer.clearAndFree();
    try encoder.int(i16, -129);
    try std.testing.expectEqualSlices(u8, &.{ 0xff, 0x7f }, encoder.buffer.data);
}

test length {
    const allocator = std.testing.allocator;
    var encoder = Encoder.init(allocator);
    defer encoder.deinit();

    try encoder.length(127);
    try std.testing.expectEqualSlices(u8, &.{0x7f}, encoder.buffer.data);

    encoder.buffer.clearAndFree();
    try encoder.length(128);
    try std.testing.expectEqualSlices(u8, &.{ 0x81, 0x80 }, encoder.buffer.data);

    encoder.buffer.clearAndFree();
    try encoder.length(255);
    try std.testing.expectEqualSlices(u8, &.{ 0x81, 0xff }, encoder.buffer.data);

    encoder.buffer.clearAndFree();
    try encoder.length(256);
    try std.testing.expectEqualSlices(u8, &.{ 0x82, 0x01, 0x00 }, encoder.buffer.data);

    encoder.buffer.clearAndFree();
    try encoder.length(65535);
    try std.testing.expectEqualSlices(u8, &.{ 0x82, 0xff, 0xff }, encoder.buffer.data);

    encoder.buffer.clearAndFree();
    try encoder.length(65536);
    try std.testing.expectEqualSlices(u8, &.{ 0x83, 0x01, 0x00, 0x00 }, encoder.buffer.data);
}

const std = @import("std");
const Oid = @import("../Oid.zig");
const asn1 = @import("../../asn1.zig");
const ArrayListReverse = @import("./ArrayListReverse.zig");
const Tag = asn1.Tag;
const FieldTag = asn1.FieldTag;
const Encoder = @This();