| ... | ... | @@ -12,26 +12,39 @@ pub fn init(bytes: []const u8) HeaderIterator { |
| 12 | 12 | |
| 13 | 13 | pub fn next(it: *HeaderIterator) ?std.http.Header { |
| 14 | 14 | const end = std.mem.indexOfPosLinear(u8, it.bytes, it.index, "\r\n").?; |
| 15 | | var kv_it = std.mem.splitSequence(u8, it.bytes[it.index..end], ": "); |
| 16 | | const name = kv_it.next().?; |
| 17 | | const value = kv_it.rest(); |
| 18 | | if (name.len == 0 and value.len == 0) { |
| 15 | if (it.index == end) { // found the trailer boundary (\r\n\r\n) |
| 19 | 16 | if (it.is_trailer) return null; |
| 17 | |
| 20 | 18 | const next_end = std.mem.indexOfPosLinear(u8, it.bytes, end + 2, "\r\n") orelse |
| 21 | 19 | return null; |
| 20 | |
| 21 | var kv_it = std.mem.splitScalar(u8, it.bytes[end + 2 .. next_end], ':'); |
| 22 | const name = kv_it.first(); |
| 23 | const value = kv_it.rest(); |
| 24 | |
| 22 | 25 | it.is_trailer = true; |
| 23 | 26 | it.index = next_end + 2; |
| 24 | | kv_it = std.mem.splitSequence(u8, it.bytes[end + 2 .. next_end], ": "); |
| 27 | if (name.len == 0) |
| 28 | return null; |
| 29 | |
| 30 | return .{ |
| 31 | .name = name, |
| 32 | .value = std.mem.trim(u8, value, " \t"), |
| 33 | }; |
| 34 | } else { // normal header |
| 35 | var kv_it = std.mem.splitScalar(u8, it.bytes[it.index..end], ':'); |
| 36 | const name = kv_it.first(); |
| 37 | const value = kv_it.rest(); |
| 38 | |
| 39 | it.index = end + 2; |
| 40 | if (name.len == 0) |
| 41 | return null; |
| 42 | |
| 25 | 43 | return .{ |
| 26 | | .name = kv_it.next().?, |
| 27 | | .value = kv_it.rest(), |
| 44 | .name = name, |
| 45 | .value = std.mem.trim(u8, value, " \t"), |
| 28 | 46 | }; |
| 29 | 47 | } |
| 30 | | it.index = end + 2; |
| 31 | | return .{ |
| 32 | | .name = name, |
| 33 | | .value = value, |
| 34 | | }; |
| 35 | 48 | } |
| 36 | 49 | |
| 37 | 50 | test next { |
| ... | ... | @@ -62,7 +75,23 @@ test next { |
| 62 | 75 | try std.testing.expectEqualStrings("g", header.value); |
| 63 | 76 | } |
| 64 | 77 | try std.testing.expectEqual(null, it.next()); |
| 78 | |
| 79 | it = HeaderIterator.init("200 OK\r\n: ss\r\n\r\n"); |
| 80 | try std.testing.expect(!it.is_trailer); |
| 81 | try std.testing.expectEqual(null, it.next()); |
| 82 | |
| 83 | it = HeaderIterator.init("200 OK\r\na: b\r\n\r\n: ss\r\n\r\n"); |
| 84 | try std.testing.expect(!it.is_trailer); |
| 85 | { |
| 86 | const header = it.next().?; |
| 87 | try std.testing.expect(!it.is_trailer); |
| 88 | try std.testing.expectEqualStrings("a", header.name); |
| 89 | try std.testing.expectEqualStrings("b", header.value); |
| 90 | } |
| 91 | try std.testing.expectEqual(null, it.next()); |
| 92 | try std.testing.expect(it.is_trailer); |
| 65 | 93 | } |
| 66 | 94 | |
| 67 | 95 | const HeaderIterator = @This(); |
| 68 | 96 | const std = @import("../std.zig"); |
| 97 | const assert = std.debug.assert; |