kevy_cli/migrate.rs
1//! Migration toolchain: `export` / `import`.
2//!
3//! Wire format = a RESP command stream of rebuild frames (SET / HSET /
4//! RPUSH / SADD / ZADD / PEXPIREAT) — bidirectionally compatible with
5//! `redis-cli --pipe`. Export walks SCAN cursors (per-key
6//! point-in-time; SCAN-class consistency). Import pipelines 512
7//! commands per batch with a fsynced progress file for `--resume`.
8//! Every key's frames start with DEL, so replay REBUILDS the key from
9//! scratch — genuinely idempotent for every type (RPUSH would
10//! otherwise append on re-import; the round-trip test caught exactly
11//! that). No cross-batch atomicity to lose.
12//!
13//! ```
14//! use kevy_cli::migrate::{ImportStart, OnErrorReply, run_export, run_import};
15//! use kevy_resp_client::Reply;
16//! # let port = include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/doc_server/serve.rs"));
17//! let mut client = kevy_resp_client::RespClient::connect("127.0.0.1", port)?;
18//! # let port_b = include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/doc_server/serve.rs"));
19//! let mut target = kevy_resp_client::RespClient::connect("127.0.0.1", port_b)?;
20//! client.request_borrowed(&[b"RPUSH", b"user:1:tags", b"a", b"b"])?;
21//! client.request_borrowed(&[b"SET", b"user:1:name", b"ada"])?;
22//!
23//! let dir = kevy_tmpdir::TmpDir::new("migrate-roundtrip");
24//! let file = dir.path().join("users.resp");
25//! assert_eq!(run_export(&mut client, Some(&b"user:"[..]), &file)?.keys, 2);
26//! // replay is idempotent: every key is rebuilt from scratch, so twice is once
27//! for _ in 0..2 {
28//! run_import(&mut target, &file, ImportStart::Fresh, OnErrorReply::Abort)?;
29//! }
30//! let tags = target.request_borrowed(&[b"LLEN", b"user:1:tags"])?;
31//! assert_eq!(tags, Reply::Int(2));
32//! # Ok::<(), Box<dyn std::error::Error>>(())
33//! ```
34
35use std::fs::{File, OpenOptions};
36use std::io::{self, BufWriter, Read, Seek, SeekFrom, Write};
37use std::path::Path;
38
39use crate::link::Link;
40use kevy_resp::Reply;
41
42mod rebuild;
43use rebuild::export_key;
44pub(crate) use rebuild::{Rebuilt, rebuild_frames};
45
46const PIPELINE: usize = 512;
47
48/// What an export did — including what it did NOT do. The skipped map
49/// is the half that used to be invisible: a type with no rebuild verb
50/// produced no frames, no error and no mention, so a migration could
51/// report success while leaving a whole type behind.
52///
53/// ```
54/// use kevy_cli::migrate::run_export;
55/// # let port = include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/doc_server/serve.rs"));
56/// let mut client = kevy_resp_client::RespClient::connect("127.0.0.1", port)?;
57/// client.request_borrowed(&[b"SET", b"k", b"v"])?;
58/// client.request_borrowed(&[b"XADD", b"events", b"*", b"f", b"v"])?;
59/// # let dir = kevy_tmpdir::TmpDir::new("migrate");
60/// let e = run_export(&mut client, None, &dir.path().join("all.resp"))?;
61/// if !e.skipped.is_empty() {
62/// eprintln!("left behind: {:?}", e.skipped); // say so rather than report success
63/// }
64/// assert_eq!(e.keys, 1);
65/// # Ok::<(), Box<dyn std::error::Error>>(())
66/// ```
67#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
68#[non_exhaustive]
69pub struct Export {
70 /// Keys whose frames are in the file.
71 ///
72 /// ```
73 /// use kevy_cli::migrate::run_export;
74 /// # let port = include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/doc_server/serve.rs"));
75 /// let mut client = kevy_resp_client::RespClient::connect("127.0.0.1", port)?;
76 /// client.request_borrowed(&[b"SET", b"a", b"1"])?;
77 /// client.request_borrowed(&[b"HSET", b"b", b"f", b"v"])?;
78 /// # let dir = kevy_tmpdir::TmpDir::new("migrate");
79 /// assert_eq!(run_export(&mut client, None, &dir.path().join("x.resp"))?.keys, 2);
80 /// # Ok::<(), Box<dyn std::error::Error>>(())
81 /// ```
82 pub keys: u64,
83 /// Type name -> keys left out because nothing here rebuilds them.
84 ///
85 /// ```
86 /// use kevy_cli::migrate::run_export;
87 /// # let port = include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/doc_server/serve.rs"));
88 /// let mut client = kevy_resp_client::RespClient::connect("127.0.0.1", port)?;
89 /// client.request_borrowed(&[b"XADD", b"events", b"*", b"f", b"v"])?;
90 /// # let dir = kevy_tmpdir::TmpDir::new("migrate");
91 /// let e = run_export(&mut client, None, &dir.path().join("x.resp"))?;
92 /// assert_eq!(e.skipped.get(&b"stream".to_vec()), Some(&1));
93 /// # Ok::<(), Box<dyn std::error::Error>>(())
94 /// ```
95 pub skipped: std::collections::BTreeMap<Vec<u8>, u64>,
96}
97
98/// Walk the keyspace (optionally under `prefix`) and write rebuild
99/// frames to `out_path`, reporting both what went in and what could
100/// not.
101///
102/// ```
103/// use kevy_cli::migrate::run_export;
104/// # let port = include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/doc_server/serve.rs"));
105/// let mut client = kevy_resp_client::RespClient::connect("127.0.0.1", port)?;
106/// client.request_borrowed(&[b"SET", b"user:1", b"ada"])?;
107/// client.request_borrowed(&[b"SET", b"order:1", b"open"])?;
108/// # let dir = kevy_tmpdir::TmpDir::new("migrate");
109/// let file = dir.path().join("users.resp");
110/// assert_eq!(run_export(&mut client, Some(&b"user:"[..]), &file)?.keys, 1);
111/// // the file is plain RESP, `redis-cli --pipe` compatible: DEL, then the rebuild
112/// let text = std::fs::read_to_string(&file)?;
113/// assert!(text.starts_with("*2\r\n$3\r\nDEL\r\n$6\r\nuser:1\r\n*3\r\n$3\r\nSET\r\n"));
114/// # Ok::<(), Box<dyn std::error::Error>>(())
115/// ```
116pub fn run_export(
117 client: &mut dyn Link,
118 prefix: Option<&[u8]>,
119 out_path: &Path,
120) -> io::Result<Export> {
121 let mut out = BufWriter::new(File::create(out_path)?);
122 let mut cursor: Vec<u8> = b"0".to_vec();
123 let mut pattern = prefix.unwrap_or_default().to_vec();
124 pattern.push(b'*');
125 let mut n = 0u64;
126 // Types with no rebuild verb, counted by name. Silence here is how
127 // a migration loses a whole type and reports success.
128 let mut skipped: std::collections::BTreeMap<Vec<u8>, u64> = Default::default();
129 loop {
130 let reply =
131 client.request_borrowed(&[b"SCAN", &cursor, b"MATCH", &pattern, b"COUNT", b"512"])?;
132 let Reply::Array(items) = reply else {
133 return Err(io::Error::new(io::ErrorKind::InvalidData, "SCAN reply shape"));
134 };
135 let (Some(Reply::Bulk(next)), Some(Reply::Array(keys))) = (items.first(), items.get(1))
136 else {
137 return Err(io::Error::new(io::ErrorKind::InvalidData, "SCAN reply shape"));
138 };
139 let next = next.clone();
140 for k in keys {
141 let Reply::Bulk(key) = k else { continue };
142 let key = key.clone();
143 match export_key(client, &key, &mut out)? {
144 Some(None) => n += 1,
145 Some(Some(ty)) => *skipped.entry(ty).or_insert(0u64) += 1,
146 None => {}
147 }
148 }
149 cursor = next;
150 if cursor == b"0" {
151 break;
152 }
153 }
154 out.flush()?;
155 Ok(Export { keys: n, skipped })
156}
157
158/// Import stats.
159///
160/// ```
161/// use kevy_cli::migrate::{ImportStart, OnErrorReply, run_import};
162/// # let port = include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/doc_server/serve.rs"));
163/// let mut client = kevy_resp_client::RespClient::connect("127.0.0.1", port)?;
164/// # let dir = kevy_tmpdir::TmpDir::new("migrate");
165/// # let src = dir.path().join("cmds.resp");
166/// # let mut raw = Vec::new();
167/// # for argv in [&[&b"SET"[..], b"a", b"1"][..], &[b"SET", b"b", b"x"], &[b"INCR", b"b"]] {
168/// # kevy_resp::encode_command_borrowed(&mut raw, argv);
169/// # }
170/// # std::fs::write(&src, raw)?;
171/// let r = run_import(&mut client, &src, ImportStart::Fresh, OnErrorReply::Count)?;
172/// assert_eq!((r.sent, r.errors), (2, 1));
173/// assert_eq!(r.offset, std::fs::metadata(&src)?.len());
174/// # Ok::<(), Box<dyn std::error::Error>>(())
175/// ```
176#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
177#[non_exhaustive]
178pub struct ImportReport {
179 /// Commands sent successfully.
180 ///
181 /// ```
182 /// use kevy_cli::migrate::{ImportStart, OnErrorReply, run_import};
183 /// # let port = include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/doc_server/serve.rs"));
184 /// let mut client = kevy_resp_client::RespClient::connect("127.0.0.1", port)?;
185 /// # let dir = kevy_tmpdir::TmpDir::new("migrate");
186 /// # let src = dir.path().join("cmds.resp");
187 /// # let mut raw = Vec::new();
188 /// # for argv in [&[&b"SET"[..], b"a", b"1"][..], &[b"SET", b"b", b"x"], &[b"INCR", b"b"]] {
189 /// # kevy_resp::encode_command_borrowed(&mut raw, argv);
190 /// # }
191 /// # std::fs::write(&src, raw)?;
192 /// assert_eq!(run_import(&mut client, &src, ImportStart::Fresh, OnErrorReply::Count)?.sent, 2);
193 /// # Ok::<(), Box<dyn std::error::Error>>(())
194 /// ```
195 pub sent: u64,
196 /// -ERR replies (counted; fatal under [`OnErrorReply::Abort`]).
197 ///
198 /// ```
199 /// use kevy_cli::migrate::{ImportStart, OnErrorReply, run_import};
200 /// # let port = include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/doc_server/serve.rs"));
201 /// let mut client = kevy_resp_client::RespClient::connect("127.0.0.1", port)?;
202 /// # let dir = kevy_tmpdir::TmpDir::new("migrate");
203 /// # let src = dir.path().join("cmds.resp");
204 /// # let mut raw = Vec::new();
205 /// # for argv in [&[&b"SET"[..], b"a", b"1"][..], &[b"SET", b"b", b"x"], &[b"INCR", b"b"]] {
206 /// # kevy_resp::encode_command_borrowed(&mut raw, argv);
207 /// # }
208 /// # std::fs::write(&src, raw)?;
209 /// let r = run_import(&mut client, &src, ImportStart::Fresh, OnErrorReply::Count)?;
210 /// assert_eq!(r.errors, 1, "INCR on a non-number");
211 /// # Ok::<(), Box<dyn std::error::Error>>(())
212 /// ```
213 pub errors: u64,
214 /// Byte offset reached in the source file.
215 ///
216 /// ```
217 /// use kevy_cli::migrate::{ImportStart, OnErrorReply, run_import};
218 /// # let port = include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/doc_server/serve.rs"));
219 /// let mut client = kevy_resp_client::RespClient::connect("127.0.0.1", port)?;
220 /// # let dir = kevy_tmpdir::TmpDir::new("migrate");
221 /// # let src = dir.path().join("cmds.resp");
222 /// # let mut raw = Vec::new();
223 /// # for argv in [&[&b"SET"[..], b"a", b"1"][..], &[b"SET", b"b", b"x"], &[b"INCR", b"b"]] {
224 /// # kevy_resp::encode_command_borrowed(&mut raw, argv);
225 /// # }
226 /// # std::fs::write(&src, raw)?;
227 /// let r = run_import(&mut client, &src, ImportStart::Fresh, OnErrorReply::Count)?;
228 /// // the whole file was applied, and `<src>.progress` says so for a later --resume
229 /// assert_eq!(r.offset, std::fs::metadata(&src)?.len());
230 /// let progress = std::fs::read_to_string(dir.path().join("cmds.resp.progress"))?;
231 /// assert_eq!(progress, r.offset.to_string());
232 /// # Ok::<(), Box<dyn std::error::Error>>(())
233 /// ```
234 pub offset: u64,
235}
236
237/// Where an import starts reading its source file.
238///
239/// ```
240/// use kevy_cli::migrate::ImportStart;
241/// // `import --resume`
242/// assert_ne!(ImportStart::Resume, ImportStart::default());
243/// ```
244#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
245#[non_exhaustive]
246pub enum ImportStart {
247 /// From the first byte, resetting `<src>.progress` before any batch.
248 ///
249 /// ```
250 /// use kevy_cli::migrate::{ImportStart, OnErrorReply, run_import};
251 /// # let port = include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/doc_server/serve.rs"));
252 /// let mut client = kevy_resp_client::RespClient::connect("127.0.0.1", port)?;
253 /// # let dir = kevy_tmpdir::TmpDir::new("migrate");
254 /// # let src = dir.path().join("cmds.resp");
255 /// # let mut raw = Vec::new();
256 /// # for argv in [&[&b"SET"[..], b"a", b"1"][..], &[b"SET", b"b", b"x"], &[b"INCR", b"b"]] {
257 /// # kevy_resp::encode_command_borrowed(&mut raw, argv);
258 /// # }
259 /// # std::fs::write(&src, raw)?;
260 /// run_import(&mut client, &src, ImportStart::Fresh, OnErrorReply::Count)?;
261 /// // fresh ignores any earlier progress and replays the whole file
262 /// let again = run_import(&mut client, &src, ImportStart::Fresh, OnErrorReply::Count)?;
263 /// assert_eq!(again.sent + again.errors, 3);
264 /// # Ok::<(), Box<dyn std::error::Error>>(())
265 /// ```
266 #[default]
267 Fresh,
268 /// From the offset `<src>.progress` recorded (`--resume`).
269 ///
270 /// ```
271 /// use kevy_cli::migrate::{ImportStart, OnErrorReply, run_import};
272 /// # let port = include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/doc_server/serve.rs"));
273 /// let mut client = kevy_resp_client::RespClient::connect("127.0.0.1", port)?;
274 /// # let dir = kevy_tmpdir::TmpDir::new("migrate");
275 /// # let src = dir.path().join("cmds.resp");
276 /// # let mut raw = Vec::new();
277 /// # for argv in [&[&b"SET"[..], b"a", b"1"][..], &[b"SET", b"b", b"x"], &[b"INCR", b"b"]] {
278 /// # kevy_resp::encode_command_borrowed(&mut raw, argv);
279 /// # }
280 /// # std::fs::write(&src, raw)?;
281 /// run_import(&mut client, &src, ImportStart::Fresh, OnErrorReply::Count)?;
282 /// // resuming a finished import starts at its end and sends nothing
283 /// let resumed = run_import(&mut client, &src, ImportStart::Resume, OnErrorReply::Count)?;
284 /// assert_eq!(resumed.sent + resumed.errors, 0);
285 /// # Ok::<(), Box<dyn std::error::Error>>(())
286 /// ```
287 Resume,
288}
289
290/// What an import does when the server answers a command with an error.
291///
292/// ```
293/// use kevy_cli::migrate::OnErrorReply;
294/// // `import --strict`
295/// assert_ne!(OnErrorReply::Abort, OnErrorReply::default());
296/// ```
297#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
298#[non_exhaustive]
299pub enum OnErrorReply {
300 /// Count it in [`ImportReport::errors`] and carry on.
301 ///
302 /// ```
303 /// use kevy_cli::migrate::{ImportStart, OnErrorReply, run_import};
304 /// # let port = include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/doc_server/serve.rs"));
305 /// let mut client = kevy_resp_client::RespClient::connect("127.0.0.1", port)?;
306 /// # let dir = kevy_tmpdir::TmpDir::new("migrate");
307 /// # let src = dir.path().join("cmds.resp");
308 /// # let mut raw = Vec::new();
309 /// # for argv in [&[&b"SET"[..], b"a", b"1"][..], &[b"SET", b"b", b"x"], &[b"INCR", b"b"]] {
310 /// # kevy_resp::encode_command_borrowed(&mut raw, argv);
311 /// # }
312 /// # std::fs::write(&src, raw)?;
313 /// let r = run_import(&mut client, &src, ImportStart::Fresh, OnErrorReply::Count)?;
314 /// assert_eq!((r.sent, r.errors), (2, 1), "counted, and the import went on");
315 /// # Ok::<(), Box<dyn std::error::Error>>(())
316 /// ```
317 #[default]
318 Count,
319 /// Stop with an `InvalidData` error naming the reply (`--strict`).
320 ///
321 /// ```
322 /// use kevy_cli::migrate::{ImportStart, OnErrorReply, run_import};
323 /// # let port = include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/doc_server/serve.rs"));
324 /// let mut client = kevy_resp_client::RespClient::connect("127.0.0.1", port)?;
325 /// # let dir = kevy_tmpdir::TmpDir::new("migrate");
326 /// # let src = dir.path().join("cmds.resp");
327 /// # let mut raw = Vec::new();
328 /// # for argv in [&[&b"SET"[..], b"a", b"1"][..], &[b"SET", b"b", b"x"], &[b"INCR", b"b"]] {
329 /// # kevy_resp::encode_command_borrowed(&mut raw, argv);
330 /// # }
331 /// # std::fs::write(&src, raw)?;
332 /// let err = run_import(&mut client, &src, ImportStart::Fresh, OnErrorReply::Abort).unwrap_err();
333 /// assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
334 /// assert!(err.to_string().starts_with("server error (strict)"));
335 /// # Ok::<(), Box<dyn std::error::Error>>(())
336 /// ```
337 Abort,
338}
339
340/// Run `import` — stream `src` (a RESP command file) into the server,
341/// `PIPELINE` commands per batch. The progress file `<src>.progress`
342/// records the safely-applied byte offset after every batch (fsynced);
343/// [`ImportStart::Resume`] starts there. Idempotent replay.
344///
345/// ```
346/// use kevy_cli::migrate::{ImportStart, OnErrorReply, run_import};
347/// use kevy_resp_client::Reply;
348/// # let port = include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/doc_server/serve.rs"));
349/// let mut client = kevy_resp_client::RespClient::connect("127.0.0.1", port)?;
350/// let dir = kevy_tmpdir::TmpDir::new("import");
351/// let path = dir.path().join("dump.resp");
352/// let mut raw = Vec::new();
353/// kevy_resp::encode_command_borrowed(&mut raw, &[&b"SET"[..], b"greet", b"hello"]);
354/// std::fs::write(&path, raw)?;
355///
356/// let r = run_import(&mut client, &path, ImportStart::Resume, OnErrorReply::Abort)?;
357/// println!("{} sent, offset {}", r.sent, r.offset);
358/// assert_eq!(client.request_borrowed(&[b"GET", b"greet"])?, Reply::Bulk(b"hello".to_vec()));
359/// # Ok::<(), Box<dyn std::error::Error>>(())
360/// ```
361pub fn run_import(
362 client: &mut dyn Link,
363 src: &Path,
364 start: ImportStart,
365 on_error: OnErrorReply,
366) -> io::Result<ImportReport> {
367 // the source first: a missing one must not leave a progress file behind
368 let mut f = File::open(src)?;
369 let (mut progress, start) = open_progress(src, start)?;
370 f.seek(SeekFrom::Start(start))?;
371 let mut pending: Vec<u8> = Vec::with_capacity(1 << 20);
372 let mut report = ImportReport { sent: 0, errors: 0, offset: start };
373 let mut chunk = vec![0u8; 1 << 20];
374 let mut batch_bytes = 0usize;
375 let mut batch_cmds = 0usize;
376 loop {
377 let n = f.read(&mut chunk)?;
378 if n == 0 {
379 break;
380 }
381 pending.extend_from_slice(&chunk[..n]);
382 // carve complete commands off `pending`
383 while let Some(used) = command_len(&pending[batch_bytes..]) {
384 batch_bytes += used;
385 batch_cmds += 1;
386 if batch_cmds == PIPELINE {
387 flush_batch(client, &pending[..batch_bytes], batch_cmds, on_error, &mut report)?;
388 pending.drain(..batch_bytes);
389 write_progress(&mut progress, report.offset)?;
390 batch_bytes = 0;
391 batch_cmds = 0;
392 }
393 }
394 }
395 if batch_cmds > 0 {
396 flush_batch(client, &pending[..batch_bytes], batch_cmds, on_error, &mut report)?;
397 write_progress(&mut progress, report.offset)?;
398 }
399 Ok(report)
400}
401
402fn flush_batch(
403 client: &mut dyn Link,
404 raw: &[u8],
405 n: usize,
406 on_error: OnErrorReply,
407 report: &mut ImportReport,
408) -> io::Result<()> {
409 let replies = client.pipeline_raw(raw, n)?;
410 for r in replies {
411 if let Reply::Error(e) = r {
412 report.errors += 1;
413 if on_error == OnErrorReply::Abort {
414 return Err(io::Error::new(
415 io::ErrorKind::InvalidData,
416 format!("server error (strict): {}", String::from_utf8_lossy(&e)),
417 ));
418 }
419 } else {
420 report.sent += 1;
421 }
422 }
423 report.offset += raw.len() as u64;
424 Ok(())
425}
426
427/// The progress file, opened, and the offset to start from.
428///
429/// The name is `<src>.progress`, APPENDED — the doc always said so, but
430/// `with_extension` turned dump.kevy into dump.progress, and everything
431/// written against the documented name (the migration drill's cleanup
432/// included) touched a file this code never read.
433///
434/// A fresh (non-resume) import resets the file immediately, before any
435/// batch. A completed earlier import leaves offset = EOF on disk; kill a
436/// fresh import before its first batch lands and that stale EOF
437/// survives — a later `--resume` then seeks to the end, imports nothing,
438/// and reports success. The migration drill hit exactly that window.
439pub(crate) fn open_progress(src: &Path, start: ImportStart) -> io::Result<(File, u64)> {
440 let resume = start == ImportStart::Resume;
441 let path = {
442 let mut os = src.as_os_str().to_owned();
443 os.push(".progress");
444 std::path::PathBuf::from(os)
445 };
446 let mut start = 0u64;
447 if resume && let Ok(text) = std::fs::read_to_string(&path) {
448 start = text.trim().parse().unwrap_or(0);
449 }
450 let mut f = OpenOptions::new().create(true).truncate(false).write(true).open(&path)?;
451 if !resume {
452 write_progress(&mut f, 0)?;
453 }
454 Ok((f, start))
455}
456
457pub(crate) fn write_progress(f: &mut File, offset: u64) -> io::Result<()> {
458 f.set_len(0)?;
459 f.seek(SeekFrom::Start(0))?;
460 f.write_all(offset.to_string().as_bytes())?;
461 f.sync_data()
462}
463
464/// Crate-visible alias for [`command_len`] (bulk copy counts frames).
465pub(crate) fn command_len_pub(b: &[u8]) -> Option<usize> {
466 command_len(b)
467}
468
469/// Length of one complete RESP command at the head of `b`, or `None`.
470fn command_len(b: &[u8]) -> Option<usize> {
471 let mut pos = 0usize;
472 let line = take_line(b, &mut pos)?;
473 if line.first() != Some(&b'*') {
474 return None;
475 }
476 let n: usize = std::str::from_utf8(&line[1..]).ok()?.trim().parse().ok()?;
477 for _ in 0..n {
478 let hdr = take_line(b, &mut pos)?;
479 if hdr.first() != Some(&b'$') {
480 return None;
481 }
482 let len: usize = std::str::from_utf8(&hdr[1..]).ok()?.trim().parse().ok()?;
483 if b.len() < pos + len + 2 {
484 return None;
485 }
486 pos += len + 2;
487 }
488 Some(pos)
489}
490
491fn take_line<'b>(b: &'b [u8], pos: &mut usize) -> Option<&'b [u8]> {
492 let rest = &b[*pos..];
493 let idx = rest.windows(2).position(|w| w == b"\r\n")?;
494 let line = &rest[..idx];
495 *pos += idx + 2;
496 Some(line)
497}