| @@ -0,0 +1,513 @@ |
| 1 | +/// PostgreSQL's wire protocol, version 3.0 (issue #145): pure encoding |
| 2 | +/// and decoding of messages — no IO here, so every exchange is testable |
| 3 | +/// against recorded byte transcripts. |
| 4 | +/// |
| 5 | +/// Frames on the wire: a type byte, a big-endian 32-bit length that |
| 6 | +/// counts itself, then the payload. (`Startup` and `SslRequest` have no |
| 7 | +/// type byte; the answer to `SslRequest` is one byte, not a frame.) |
| 8 | + |
| 9 | +import std/bytes |
| 10 | +import std/int |
| 11 | +import std/list |
| 12 | +import std/result |
| 13 | + |
| 14 | +// ---- outgoing (frontend) --------------------------------------------------- |
| 15 | + |
| 16 | +/// A message the client sends. |
| 17 | +pub type Out { |
| 18 | + /// Ask whether the server upgrades this connection to TLS. |
| 19 | + SslRequest |
| 20 | + /// Protocol 3.0, with the user, the database and the application name. |
| 21 | + Startup(user: String, database: String, application: String) |
| 22 | + /// The (cleartext, or hashed) password. |
| 23 | + Password(String) |
| 24 | + /// One step of a SCRAM exchange. |
| 25 | + SaslResponse(Bytes) |
| 26 | + /// The simple query protocol (used for `BEGIN`/`COMMIT`/`ROLLBACK` only). |
| 27 | + Query(String) |
| 28 | + /// Name a statement for the SQL; no parameter types, the server infers. |
| 29 | + Parse(name: String, sql: String) |
| 30 | + /// A portal for a statement with its parameters: text format both ways |
| 31 | + /// (`None` is SQL `NULL`). |
| 32 | + Bind(portal: String, statement: String, params: List<Option<Bytes>>) |
| 33 | + /// Ask for a statement's description (`RowDescription`). |
| 34 | + DescribeStatement(String) |
| 35 | + /// Ask for a portal's description. |
| 36 | + DescribePortal(String) |
| 37 | + /// Run a portal (`max_rows` 0 = all rows). |
| 38 | + Execute(portal: String, max_rows: Int) |
| 39 | + /// End the extended-protocol exchange. |
| 40 | + Sync |
| 41 | + /// Ask for the pending responses now. |
| 42 | + Flush |
| 43 | + /// End the connection politely. |
| 44 | + Terminate |
| 45 | +} |
| 46 | + |
| 47 | +/// A message as bytes on the wire. |
| 48 | +pub fn encode(msg: Out) -> Bytes { |
| 49 | + match msg { |
| 50 | + SslRequest -> { |
| 51 | + let b = be32(bytes.builder(), 8) |
| 52 | + bytes.build(be32(b, 80877103)) |
| 53 | + }, |
| 54 | + Startup(user, database, application) -> { |
| 55 | + let p = bytes.builder() |
| 56 | + let p = be32(p, 196608) // 3.0 |
| 57 | + let p = cstr(p, "user") |
| 58 | + let p = cstr(p, user) |
| 59 | + let p = cstr(p, "database") |
| 60 | + let p = cstr(p, database) |
| 61 | + let p = cstr(p, "application_name") |
| 62 | + let p = cstr(p, application) |
| 63 | + let p = bytes.append_byte(p, 0) |
| 64 | + let payload = bytes.build(p) |
| 65 | + let b = be32(bytes.builder(), bytes.length(payload) + 4) |
| 66 | + bytes.build(bytes.append(b, payload)) |
| 67 | + }, |
| 68 | + Password(password) -> frame(112, bytes.build(cstr(bytes.builder(), password))), |
| 69 | + SaslResponse(data) -> frame(112, data), |
| 70 | + Query(sql) -> frame(81, bytes.build(cstr(bytes.builder(), sql))), |
| 71 | + Parse(name, sql) -> { |
| 72 | + let p = cstr(bytes.builder(), name) |
| 73 | + let p = cstr(p, sql) |
| 74 | + frame(80, bytes.build(be16(p, 0))) |
| 75 | + }, |
| 76 | + Bind(portal, statement, params) -> { |
| 77 | + let p = cstr(bytes.builder(), portal) |
| 78 | + let p = cstr(p, statement) |
| 79 | + let p = be16(p, 0) // all parameters in text format |
| 80 | + let p = be16(p, list.length(params)) |
| 81 | + let p = list.fold(params, p, bind_param) |
| 82 | + frame(66, bytes.build(be16(p, 0))) // all result columns in text format |
| 83 | + }, |
| 84 | + DescribeStatement(name) -> describe(83, name), |
| 85 | + DescribePortal(name) -> describe(80, name), |
| 86 | + Execute(portal, max_rows) -> { |
| 87 | + let p = cstr(bytes.builder(), portal) |
| 88 | + frame(69, bytes.build(be32(p, max_rows))) |
| 89 | + }, |
| 90 | + Sync -> frame(83, bytes.empty()), |
| 91 | + Flush -> frame(72, bytes.empty()), |
| 92 | + Terminate -> frame(88, bytes.empty()), |
| 93 | + } |
| 94 | +} |
| 95 | + |
| 96 | +fn bind_param(p: bytes.Builder, param: Option<Bytes>) -> bytes.Builder { |
| 97 | + match param { |
| 98 | + None -> be32(p, -1), |
| 99 | + Some(data) -> { |
| 100 | + let p = be32(p, bytes.length(data)) |
| 101 | + bytes.append(p, data) |
| 102 | + } |
| 103 | + } |
| 104 | +} |
| 105 | + |
| 106 | +/// A Describe frame: the tag, then 'S' or 'P' and the name. |
| 107 | +fn describe(what: Int, name: String) -> Bytes { |
| 108 | + let p = bytes.append_byte(bytes.builder(), what) |
| 109 | + frame(68, bytes.build(cstr(p, name))) |
| 110 | +} |
| 111 | + |
| 112 | +/// A frame: the tag byte, then the big-endian length (counting itself) |
| 113 | +/// and the payload. |
| 114 | +fn frame(tag: Int, payload: Bytes) -> Bytes { |
| 115 | + let b = bytes.append_byte(bytes.builder(), tag) |
| 116 | + let b = be32(b, bytes.length(payload) + 4) |
| 117 | + bytes.build(bytes.append(b, payload)) |
| 118 | +} |
| 119 | + |
| 120 | +/// `n` as 4 big-endian bytes (its low 32 bits). |
| 121 | +fn be32(b: bytes.Builder, n: Int) -> bytes.Builder { |
| 122 | + let n = int.low_bits(n, 32) |
| 123 | + let b = bytes.append_byte(b, int.and(int.shift_right(n, 24), 255)) |
| 124 | + let b = bytes.append_byte(b, int.and(int.shift_right(n, 16), 255)) |
| 125 | + let b = bytes.append_byte(b, int.and(int.shift_right(n, 8), 255)) |
| 126 | + bytes.append_byte(b, int.and(n, 255)) |
| 127 | +} |
| 128 | + |
| 129 | +/// `n` as 2 big-endian bytes. |
| 130 | +fn be16(b: bytes.Builder, n: Int) -> bytes.Builder { |
| 131 | + let b = bytes.append_byte(b, int.and(int.shift_right(n, 8), 255)) |
| 132 | + bytes.append_byte(b, int.and(n, 255)) |
| 133 | +} |
| 134 | + |
| 135 | +/// `s` as UTF-8, then a zero byte. |
| 136 | +fn cstr(b: bytes.Builder, s: String) -> bytes.Builder { |
| 137 | + bytes.append_byte(bytes.append_string(b, s), 0) |
| 138 | +} |
| 139 | + |
| 140 | +// ---- the TLS negotiation answer --------------------------------------------- |
| 141 | + |
| 142 | +/// What the server answered to `SslRequest`. |
| 143 | +pub type SslAnswer { |
| 144 | + /// 'S': send the TLS handshake now. |
| 145 | + Upgrade |
| 146 | + /// 'N': the server does not do TLS. |
| 147 | + Plain |
| 148 | +} |
| 149 | + |
| 150 | +/// The one byte that answers `SslRequest` (it is not a frame). |
| 151 | +pub fn ssl_answer(byte: Int) -> Option<SslAnswer> { |
| 152 | + match byte { |
| 153 | + 83 -> Some(Upgrade), |
| 154 | + 78 -> Some(Plain), |
| 155 | + _ -> None, |
| 156 | + } |
| 157 | +} |
| 158 | + |
| 159 | +// ---- incoming (backend) ----------------------------------------------------- |
| 160 | + |
| 161 | +/// A message the server sent. |
| 162 | +@derive(Eq, Debug) |
| 163 | +pub type In { |
| 164 | + /// Authentication succeeded. |
| 165 | + AuthenticationOk |
| 166 | + /// The server wants a cleartext password (only over TLS, documented). |
| 167 | + AuthenticationCleartext |
| 168 | + /// The server wants SASL, offering these mechanisms. |
| 169 | + AuthenticationSasl(List<String>) |
| 170 | + /// A SCRAM step's data (`AuthenticationSASLContinue`). |
| 171 | + SaslContinue(Bytes) |
| 172 | + /// The last SCRAM step's data (`AuthenticationSASLFinal`). |
| 173 | + SaslFinal(Bytes) |
| 174 | + /// A run-time parameter the server reports (`server_version`, ...). |
| 175 | + ParameterStatus(name: String, value: String) |
| 176 | + /// The connection's process id and secret key (for `CancelRequest`). |
| 177 | + BackendKeyData(process: Int, secret: Int) |
| 178 | + /// The server is ready for a query, in this transaction state. |
| 179 | + ReadyForQuery(TxStatus) |
| 180 | + /// An error, as (field code, text) pairs (`"C"` is the SQLSTATE). |
| 181 | + ErrorResponse(List<(String, String)>) |
| 182 | + /// A notice, with the same fields. |
| 183 | + NoticeResponse(List<(String, String)>) |
| 184 | + ParseComplete |
| 185 | + BindComplete |
| 186 | + /// A row set's columns. |
| 187 | + RowDescription(List<Field>) |
| 188 | + /// A row (`None` is SQL `NULL`). |
| 189 | + DataRow(List<Option<Bytes>>) |
| 190 | + /// The command's tag (`"SELECT 2"`, ...). |
| 191 | + CommandComplete(String) |
| 192 | + /// A `NOTIFY`: process id, channel, payload. |
| 193 | + NotificationResponse(process: Int, channel: String, payload: String) |
| 194 | + /// A `Query` that returned nothing. |
| 195 | + EmptyQueryResponse |
| 196 | + /// A portal with no rows (Describe's answer). |
| 197 | + NoData |
| 198 | +} |
| 199 | + |
| 200 | +/// A `RowDescription` field. |
| 201 | +@derive(Eq, Debug) |
| 202 | +pub type Field { |
| 203 | + Field(name: String, table: Int, column: Int, type_oid: Int, size: Int, modifier: Int, format: Int) |
| 204 | +} |
| 205 | + |
| 206 | +/// The transaction state a `ReadyForQuery` reports. |
| 207 | +@derive(Eq, Debug) |
| 208 | +pub type TxStatus { |
| 209 | + /// 'I': not in a transaction. |
| 210 | + Idle |
| 211 | + /// 'T': in a transaction. |
| 212 | + InTx |
| 213 | + /// 'E': in a failed transaction (rolled back on `COMMIT`). |
| 214 | + Failed |
| 215 | +} |
| 216 | + |
| 217 | +/// What [`next`] found in the buffer. |
| 218 | +pub type Next { |
| 219 | + /// Not all of the message's bytes are there yet. |
| 220 | + Incomplete |
| 221 | + /// A message, and the rest of the buffer. |
| 222 | + Message(In, Bytes) |
| 223 | + /// A frame that cannot be one: the connection is broken. |
| 224 | + Malformed(String) |
| 225 | +} |
| 226 | + |
| 227 | +/// The most payload a message may declare (1 GiB). A bigger length marks |
| 228 | +/// a broken connection: nothing allocates before the check. |
| 229 | +pub fn max_message() -> Int { |
| 230 | + 1073741824 |
| 231 | +} |
| 232 | + |
| 233 | +/// The first message in `buffer`, if its bytes are all there, and the |
| 234 | +/// rest of the buffer. |
| 235 | +pub fn next(buffer: Bytes) -> Next { |
| 236 | + if bytes.length(buffer) < 5 { |
| 237 | + Incomplete |
| 238 | + } else { |
| 239 | + let tag = byte(buffer, 0) |
| 240 | + let length = be32_at(buffer, 1) |
| 241 | + if length < 4 || length > max_message() + 4 { |
| 242 | + Malformed("invalid frame length {length}") |
| 243 | + } else if bytes.length(buffer) < length + 1 { |
| 244 | + Incomplete |
| 245 | + } else { |
| 246 | + let payload = bytes.slice(buffer, 5, length + 1) |
| 247 | + let rest = bytes.slice(buffer, length + 1, bytes.length(buffer)) |
| 248 | + match parse(tag, payload) { |
| 249 | + Ok(msg) -> Message(msg, rest), |
| 250 | + Error(e) -> Malformed(e), |
| 251 | + } |
| 252 | + } |
| 253 | + } |
| 254 | +} |
| 255 | + |
| 256 | +/// The byte at `i` (callers stay in bounds). |
| 257 | +fn byte(b: Bytes, i: Int) -> Int { |
| 258 | + match bytes.get(b, i) { |
| 259 | + Some(x) -> x, |
| 260 | + None -> panic("protocol: a byte out of bounds (a bug in the codec)"), |
| 261 | + } |
| 262 | +} |
| 263 | + |
| 264 | +/// The big-endian 32-bit integer at `i`, signed. |
| 265 | +fn be32_at(b: Bytes, i: Int) -> Int { |
| 266 | + let n = |
| 267 | + int.shift_left(byte(b, i), 24) |
| 268 | + + int.shift_left(byte(b, i + 1), 16) |
| 269 | + + int.shift_left(byte(b, i + 2), 8) |
| 270 | + + byte(b, i + 3) |
| 271 | + if n >= 2147483648 { n - 4294967296 } else { n } |
| 272 | +} |
| 273 | + |
| 274 | +/// A cursor over a message's payload. |
| 275 | +type Cursor { |
| 276 | + Cursor(bytes: Bytes, at: Int) |
| 277 | +} |
| 278 | + |
| 279 | +fn parse(tag: Int, payload: Bytes) -> Result<In, String> { |
| 280 | + let cur = Cursor(payload, 0) |
| 281 | + match tag { |
| 282 | + 82 -> authentication(cur), // 'R' |
| 283 | + 83 -> parameter_status(cur), // 'S' |
| 284 | + 75 -> backend_key_data(cur), // 'K' |
| 285 | + 90 -> ready_for_query(cur), // 'Z' |
| 286 | + 69 -> error_fields(cur, ErrorResponse_of), // 'E' |
| 287 | + 78 -> error_fields(cur, NoticeResponse_of), // 'N' |
| 288 | + 84 -> row_description(cur), // 'T' |
| 289 | + 68 -> data_row(cur), // 'D' |
| 290 | + 67 -> command_complete(cur), // 'C' |
| 291 | + 65 -> notification(cur), // 'A' |
| 292 | + 49 -> plain(cur, ParseComplete), // '1' |
| 293 | + 50 -> plain(cur, BindComplete), // '2' |
| 294 | + 73 -> plain(cur, EmptyQueryResponse), // 'I' |
| 295 | + 110 -> plain(cur, NoData), // 'n' |
| 296 | + _ -> Error("a message type the driver does not know: tag {tag}"), |
| 297 | + } |
| 298 | +} |
| 299 | + |
| 300 | +// The constructors as values (for the error fields' two shapes). |
| 301 | +fn ErrorResponse_of(fields: List<(String, String)>) -> In { ErrorResponse(fields) } |
| 302 | +fn NoticeResponse_of(fields: List<(String, String)>) -> In { NoticeResponse(fields) } |
| 303 | + |
| 304 | +/// A message with an empty payload. |
| 305 | +fn plain(cur: Cursor, msg: In) -> Result<In, String> { |
| 306 | + if cur.at == bytes.length(cur.bytes) { |
| 307 | + Ok(msg) |
| 308 | + } else { |
| 309 | + Error("the message has bytes left over") |
| 310 | + } |
| 311 | +} |
| 312 | + |
| 313 | +fn authentication(cur: Cursor) -> Result<In, String> { |
| 314 | + use (kind, cur) <- result.try(read_be32(cur)) |
| 315 | + match kind { |
| 316 | + 0 -> Ok(AuthenticationOk), |
| 317 | + 3 -> Ok(AuthenticationCleartext), |
| 318 | + 10 -> mechanism_list(cur, []), |
| 319 | + 11 -> read_rest(cur, SaslContinue_of), |
| 320 | + 12 -> read_rest(cur, SaslFinal_of), |
| 321 | + _ -> Error("an authentication method the driver does not know: {kind}"), |
| 322 | + } |
| 323 | +} |
| 324 | + |
| 325 | +fn SaslContinue_of(data: Bytes) -> In { SaslContinue(data) } |
| 326 | +fn SaslFinal_of(data: Bytes) -> In { SaslFinal(data) } |
| 327 | + |
| 328 | +/// The list of mechanism names, ended by an empty string. |
| 329 | +fn mechanism_list(cur: Cursor, acc: List<String>) -> Result<In, String> { |
| 330 | + use (name, cur) <- result.try(read_cstr(cur)) |
| 331 | + if name == "" { |
| 332 | + Ok(AuthenticationSasl(list.reverse(acc))) |
| 333 | + } else { |
| 334 | + mechanism_list(cur, [name, ..acc]) |
| 335 | + } |
| 336 | +} |
| 337 | + |
| 338 | +/// The rest of the payload as bytes. |
| 339 | +fn read_rest(cur: Cursor, of: fn(Bytes) -> In) -> Result<In, String> { |
| 340 | + Ok(of(bytes.slice(cur.bytes, cur.at, bytes.length(cur.bytes)))) |
| 341 | +} |
| 342 | + |
| 343 | +fn parameter_status(cur: Cursor) -> Result<In, String> { |
| 344 | + use (name, cur) <- result.try(read_cstr(cur)) |
| 345 | + use (value, _) <- result.try(read_cstr(cur)) |
| 346 | + Ok(ParameterStatus(name, value)) |
| 347 | +} |
| 348 | + |
| 349 | +fn backend_key_data(cur: Cursor) -> Result<In, String> { |
| 350 | + use (process, cur) <- result.try(read_be32(cur)) |
| 351 | + use (secret, _) <- result.try(read_be32(cur)) |
| 352 | + Ok(BackendKeyData(process, secret)) |
| 353 | +} |
| 354 | + |
| 355 | +fn ready_for_query(cur: Cursor) -> Result<In, String> { |
| 356 | + use (status, _) <- result.try(read_u8(cur)) |
| 357 | + match status { |
| 358 | + 73 -> Ok(ReadyForQuery(Idle)), |
| 359 | + 84 -> Ok(ReadyForQuery(InTx)), |
| 360 | + 69 -> Ok(ReadyForQuery(Failed)), |
| 361 | + _ -> Error("a transaction status the driver does not know: {status}"), |
| 362 | + } |
| 363 | +} |
| 364 | + |
| 365 | +/// The `(code, text)` fields of an error or a notice, ended by a zero |
| 366 | +/// byte. |
| 367 | +fn error_fields( |
| 368 | + cur: Cursor, |
| 369 | + of: fn(List<(String, String)>) -> In, |
| 370 | +) -> Result<In, String> { |
| 371 | + use (code, cur) <- result.try(read_u8(cur)) |
| 372 | + if code == 0 { |
| 373 | + Ok(of([])) |
| 374 | + } else { |
| 375 | + error_fields_loop(cur, of, code, []) |
| 376 | + } |
| 377 | +} |
| 378 | + |
| 379 | +fn error_fields_loop( |
| 380 | + cur: Cursor, |
| 381 | + of: fn(List<(String, String)>) -> In, |
| 382 | + code: Int, |
| 383 | + acc: List<(String, String)>, |
| 384 | +) -> Result<In, String> { |
| 385 | + use (text, cur) <- result.try(read_cstr(cur)) |
| 386 | + let field = (code_string(code), text) |
| 387 | + use (next_code, cur) <- result.try(read_u8(cur)) |
| 388 | + if next_code == 0 { |
| 389 | + Ok(of(list.reverse([field, ..acc]))) |
| 390 | + } else { |
| 391 | + error_fields_loop(cur, of, next_code, [field, ..acc]) |
| 392 | + } |
| 393 | +} |
| 394 | + |
| 395 | +fn row_description(cur: Cursor) -> Result<In, String> { |
| 396 | + use (count, cur) <- result.try(read_be16(cur)) |
| 397 | + field_list(cur, count, []) |
| 398 | +} |
| 399 | + |
| 400 | +fn field_list(cur: Cursor, count: Int, acc: List<Field>) -> Result<In, String> { |
| 401 | + if count <= 0 { |
| 402 | + Ok(RowDescription(list.reverse(acc))) |
| 403 | + } else { |
| 404 | + use (name, cur) <- result.try(read_cstr(cur)) |
| 405 | + use (table, cur) <- result.try(read_be32(cur)) |
| 406 | + use (column, cur) <- result.try(read_be16(cur)) |
| 407 | + use (type_oid, cur) <- result.try(read_be32(cur)) |
| 408 | + use (size, cur) <- result.try(read_be16(cur)) |
| 409 | + use (modifier, cur) <- result.try(read_be32(cur)) |
| 410 | + use (format, cur) <- result.try(read_be16(cur)) |
| 411 | + let field = Field(name, table, column, type_oid, size, modifier, format) |
| 412 | + field_list(cur, count - 1, [field, ..acc]) |
| 413 | + } |
| 414 | +} |
| 415 | + |
| 416 | +fn data_row(cur: Cursor) -> Result<In, String> { |
| 417 | + use (count, cur) <- result.try(read_be16(cur)) |
| 418 | + value_list(cur, count, []) |
| 419 | +} |
| 420 | + |
| 421 | +fn value_list(cur: Cursor, count: Int, acc: List<Option<Bytes>>) -> Result<In, String> { |
| 422 | + if count <= 0 { |
| 423 | + Ok(DataRow(list.reverse(acc))) |
| 424 | + } else { |
| 425 | + use (length, cur) <- result.try(read_be32(cur)) |
| 426 | + if length == -1 { |
| 427 | + value_list(cur, count - 1, [None, ..acc]) |
| 428 | + } else if length < 0 { |
| 429 | + Error("a column length of {length}") |
| 430 | + } else { |
| 431 | + use (value, cur) <- result.try(take(cur, length)) |
| 432 | + value_list(cur, count - 1, [Some(value), ..acc]) |
| 433 | + } |
| 434 | + } |
| 435 | +} |
| 436 | + |
| 437 | +fn command_complete(cur: Cursor) -> Result<In, String> { |
| 438 | + use (tag, _) <- result.try(read_cstr(cur)) |
| 439 | + Ok(CommandComplete(tag)) |
| 440 | +} |
| 441 | + |
| 442 | +fn notification(cur: Cursor) -> Result<In, String> { |
| 443 | + use (process, cur) <- result.try(read_be32(cur)) |
| 444 | + use (channel, cur) <- result.try(read_cstr(cur)) |
| 445 | + use (payload, _) <- result.try(read_cstr(cur)) |
| 446 | + Ok(NotificationResponse(process, channel, payload)) |
| 447 | +} |
| 448 | + |
| 449 | +// ---- the cursor's reads ----------------------------------------------------- |
| 450 | + |
| 451 | +fn read_u8(cur: Cursor) -> Result<(Int, Cursor), String> { |
| 452 | + match bytes.get(cur.bytes, cur.at) { |
| 453 | + Some(b) -> Ok((b, Cursor(cur.bytes, cur.at + 1))), |
| 454 | + None -> Error("the message ends early"), |
| 455 | + } |
| 456 | +} |
| 457 | + |
| 458 | +fn read_be16(cur: Cursor) -> Result<(Int, Cursor), String> { |
| 459 | + use (chunk, cur) <- result.try(take(cur, 2)) |
| 460 | + match bytes.to_list(chunk) { |
| 461 | + [a, b] -> Ok((int.shift_left(a, 8) + b, cur)), |
| 462 | + _ -> Error("the message ends early"), |
| 463 | + } |
| 464 | +} |
| 465 | + |
| 466 | +fn read_be32(cur: Cursor) -> Result<(Int, Cursor), String> { |
| 467 | + use (chunk, cur) <- result.try(take(cur, 4)) |
| 468 | + match bytes.to_list(chunk) { |
| 469 | + [a, b, c, d] -> { |
| 470 | + let n = int.shift_left(a, 24) + int.shift_left(b, 16) + int.shift_left(c, 8) + d |
| 471 | + let n = if n >= 2147483648 { n - 4294967296 } else { n } |
| 472 | + Ok((n, cur)) |
| 473 | + }, |
| 474 | + _ -> Error("the message ends early"), |
| 475 | + } |
| 476 | +} |
| 477 | + |
| 478 | +/// The bytes of the next `n`, or an error. |
| 479 | +fn take(cur: Cursor, n: Int) -> Result<(Bytes, Cursor), String> { |
| 480 | + if n < 0 || cur.at + n > bytes.length(cur.bytes) { |
| 481 | + Error("the message ends early") |
| 482 | + } else { |
| 483 | + Ok((bytes.slice(cur.bytes, cur.at, cur.at + n), Cursor(cur.bytes, cur.at + n))) |
| 484 | + } |
| 485 | +} |
| 486 | + |
| 487 | +/// The next zero-terminated string. |
| 488 | +fn read_cstr(cur: Cursor) -> Result<(String, Cursor), String> { |
| 489 | + match find_zero(cur.bytes, cur.at) { |
| 490 | + None -> Error("the string is not terminated"), |
| 491 | + Some(end) -> { |
| 492 | + match bytes.to_string(bytes.slice(cur.bytes, cur.at, end)) { |
| 493 | + Ok(s) -> Ok((s, Cursor(cur.bytes, end + 1))), |
| 494 | + Error(e) -> Error("the string is not UTF-8: {e}"), |
| 495 | + } |
| 496 | + } |
| 497 | + } |
| 498 | +} |
| 499 | + |
| 500 | +fn find_zero(b: Bytes, at: Int) -> Option<Int> { |
| 501 | + match bytes.get(b, at) { |
| 502 | + None -> None, |
| 503 | + Some(0) -> Some(at), |
| 504 | + Some(_) -> find_zero(b, at + 1), |
| 505 | + } |
| 506 | +} |
| 507 | + |
| 508 | +fn code_string(code: Int) -> String { |
| 509 | + match bytes.to_string(bytes.from_list([code])) { |
| 510 | + Ok(s) -> s, |
| 511 | + Error(_) -> "?", |
| 512 | + } |
| 513 | +} |