| @@ -23,7 +23,7 @@ |
| 23 | 23 | /// returns, unsubscribing first. |
| 24 | 24 | |
| 25 | 25 | import std/actor.{Continue} |
| 26 | | −import std/bytes |
| 26 | +import std/bytes.{type Builder} |
| 27 | 27 | import std/ffi.{type Resource} |
| 28 | 28 | import std/http |
| 29 | 29 | import std/list |
| @@ -59,21 +59,46 @@ pub fn new_event(data: String) -> Event { |
| 59 | 59 | /// -- "id: 42\ndata: two\ndata: lines\n\n" |
| 60 | 60 | pub fn frame(e: Event) -> Bytes { |
| 61 | 61 | let Event(data, event, id, retry) = e |
| 62 | | − let head = string.concat([ |
| 63 | | − option.unwrap_or(option.map(event, fn(name) { "event: " <> one_line(name) <> "\n" }), ""), |
| 64 | | − option.unwrap_or(option.map(id, fn(i) { "id: " <> one_line(i) <> "\n" }), ""), |
| 65 | | − option.unwrap_or(option.map(retry, fn(r) { "retry: " <> show(r) <> "\n" }), ""), |
| 66 | | − ]) |
| 67 | | − let body = string.concat(list.map(string.split(data, "\n"), fn(line) { "data: " <> line <> "\n" })) |
| 68 | | − bytes.from_string(head <> body <> "\n") |
| 62 | + let b = bytes.builder() |
| 63 | + let b = match event { |
| 64 | + Some(name) -> field_line(b, "event: ", one_line(name)), |
| 65 | + None -> b, |
| 66 | + } |
| 67 | + let b = match id { |
| 68 | + Some(i) -> field_line(b, "id: ", one_line(i)), |
| 69 | + None -> b, |
| 70 | + } |
| 71 | + let b = match retry { |
| 72 | + Some(r) -> field_line(b, "retry: ", show(r)), |
| 73 | + None -> b, |
| 74 | + } |
| 75 | + bytes.build(bytes.append_string(data_lines(b, string.split(data, "\n")), "\n")) |
| 69 | 76 | } |
| 70 | 77 | |
| 71 | 78 | /// A comment frame (": text"), the heartbeat: clients ignore it, proxies |
| 72 | 79 | /// keep the stream open for it. Newlines in `text` start new comment |
| 73 | 80 | /// lines. |
| 74 | 81 | pub fn comment(text: String) -> Bytes { |
| 75 | | − let lines = string.concat(list.map(string.split(text, "\n"), fn(line) { ": " <> line <> "\n" })) |
| 76 | | − bytes.from_string(lines <> "\n") |
| 82 | + bytes.build(bytes.append_string(comment_lines(bytes.builder(), string.split(text, "\n")), "\n")) |
| 83 | +} |
| 84 | + |
| 85 | +/// `"tag" <> value <> "\n"` appended without building the string. |
| 86 | +fn field_line(b: Builder, tag: String, value: String) -> Builder { |
| 87 | + bytes.append_string(bytes.append_string(bytes.append_string(b, tag), value), "\n") |
| 88 | +} |
| 89 | + |
| 90 | +fn data_lines(b: Builder, lines: List<String>) -> Builder { |
| 91 | + match lines { |
| 92 | + [] -> b, |
| 93 | + [line, ..rest] -> data_lines(field_line(b, "data: ", line), rest), |
| 94 | + } |
| 95 | +} |
| 96 | + |
| 97 | +fn comment_lines(b: Builder, lines: List<String>) -> Builder { |
| 98 | + match lines { |
| 99 | + [] -> b, |
| 100 | + [line, ..rest] -> comment_lines(field_line(b, ": ", line), rest), |
| 101 | + } |
| 77 | 102 | } |
| 78 | 103 | |
| 79 | 104 | /// The `Last-Event-ID` a request resumes from, if it gives one. |