Skip to main content

hyprstream_9p/
msg.rs

1//! 9P2000.L message types and wire format serialization.
2//!
3//! Minimal implementation — only the message types needed for a 9P client
4//! to walk, open, read, write, readdir, stat, and clunk.
5//!
6//! Wire format: all little-endian, length-prefixed.
7//! ```text
8//! [4 bytes: total size including this field]
9//! [1 byte: message type]
10//! [2 bytes: tag]
11//! [... type-specific fields ...]
12//! ```
13
14use std::io::{Cursor, Read};
15
16// ─────────────────────────────────────────────────────────────────────────────
17// Message type constants (9P2000.L)
18// ─────────────────────────────────────────────────────────────────────────────
19
20pub const TVERSION: u8 = 100;
21pub const RVERSION: u8 = 101;
22pub const TATTACH: u8 = 104;
23pub const RATTACH: u8 = 105;
24pub const RLERROR: u8 = 7;
25pub const TWALK: u8 = 110;
26pub const RWALK: u8 = 111;
27pub const TLOPEN: u8 = 12;
28pub const RLOPEN: u8 = 13;
29pub const TREAD: u8 = 116;
30pub const RREAD: u8 = 117;
31pub const TWRITE: u8 = 118;
32pub const RWRITE: u8 = 119;
33pub const TCLUNK: u8 = 120;
34pub const RCLUNK: u8 = 121;
35pub const TGETATTR: u8 = 24;
36pub const RGETATTR: u8 = 25;
37pub const TREADDIR: u8 = 40;
38pub const RREADDIR: u8 = 41;
39
40// ─────────────────────────────────────────────────────────────────────────────
41// QID — unique file identifier
42// ─────────────────────────────────────────────────────────────────────────────
43
44#[derive(Clone, Debug, Default)]
45pub struct Qid {
46    pub qtype: u8,
47    pub version: u32,
48    pub path: u64,
49}
50
51impl Qid {
52    pub fn read_from(r: &mut Cursor<&[u8]>) -> anyhow::Result<Self> {
53        Ok(Qid {
54            qtype: read_u8(r)?,
55            version: read_u32(r)?,
56            path: read_u64(r)?,
57        })
58    }
59
60    pub fn write_to(&self, w: &mut Vec<u8>) {
61        w.push(self.qtype);
62        w.extend_from_slice(&self.version.to_le_bytes());
63        w.extend_from_slice(&self.path.to_le_bytes());
64    }
65
66    pub fn is_dir(&self) -> bool {
67        self.qtype & 0x80 != 0
68    }
69}
70
71// ─────────────────────────────────────────────────────────────────────────────
72// Wire format helpers
73// ─────────────────────────────────────────────────────────────────────────────
74
75fn read_u8(r: &mut Cursor<&[u8]>) -> anyhow::Result<u8> {
76    let mut buf = [0u8; 1];
77    r.read_exact(&mut buf)?;
78    Ok(buf[0])
79}
80
81fn read_u16(r: &mut Cursor<&[u8]>) -> anyhow::Result<u16> {
82    let mut buf = [0u8; 2];
83    r.read_exact(&mut buf)?;
84    Ok(u16::from_le_bytes(buf))
85}
86
87fn read_u32(r: &mut Cursor<&[u8]>) -> anyhow::Result<u32> {
88    let mut buf = [0u8; 4];
89    r.read_exact(&mut buf)?;
90    Ok(u32::from_le_bytes(buf))
91}
92
93fn read_u64(r: &mut Cursor<&[u8]>) -> anyhow::Result<u64> {
94    let mut buf = [0u8; 8];
95    r.read_exact(&mut buf)?;
96    Ok(u64::from_le_bytes(buf))
97}
98
99fn read_string(r: &mut Cursor<&[u8]>) -> anyhow::Result<String> {
100    let len = read_u16(r)? as usize;
101    let mut buf = vec![0u8; len];
102    r.read_exact(&mut buf)?;
103    Ok(String::from_utf8_lossy(&buf).to_string())
104}
105
106fn read_data(r: &mut Cursor<&[u8]>) -> anyhow::Result<Vec<u8>> {
107    let len = read_u32(r)? as usize;
108    let mut buf = vec![0u8; len];
109    r.read_exact(&mut buf)?;
110    Ok(buf)
111}
112
113fn write_string(w: &mut Vec<u8>, s: &str) {
114    w.extend_from_slice(&(s.len() as u16).to_le_bytes());
115    w.extend_from_slice(s.as_bytes());
116}
117
118#[allow(dead_code)]
119fn write_data(w: &mut Vec<u8>, data: &[u8]) {
120    w.extend_from_slice(&(data.len() as u32).to_le_bytes());
121    w.extend_from_slice(data);
122}
123
124// ─────────────────────────────────────────────────────────────────────────────
125// T-messages (client → server)
126// ─────────────────────────────────────────────────────────────────────────────
127
128/// Serialize a T-message to wire format (including length prefix).
129pub fn encode_tmessage(tag: u16, msg_type: u8, body: &[u8]) -> Vec<u8> {
130    let size = 4 + 1 + 2 + body.len();
131    let mut buf = Vec::with_capacity(size);
132    buf.extend_from_slice(&(size as u32).to_le_bytes());
133    buf.push(msg_type);
134    buf.extend_from_slice(&tag.to_le_bytes());
135    buf.extend_from_slice(body);
136    buf
137}
138
139pub fn tversion(tag: u16, msize: u32, version: &str) -> Vec<u8> {
140    let mut body = Vec::new();
141    body.extend_from_slice(&msize.to_le_bytes());
142    write_string(&mut body, version);
143    encode_tmessage(tag, TVERSION, &body)
144}
145
146pub fn tattach(tag: u16, fid: u32, afid: u32, uname: &str, aname: &str) -> Vec<u8> {
147    let mut body = Vec::new();
148    body.extend_from_slice(&fid.to_le_bytes());
149    body.extend_from_slice(&afid.to_le_bytes());
150    write_string(&mut body, uname);
151    write_string(&mut body, aname);
152    // 9P2000.L: n_uname
153    body.extend_from_slice(&0u32.to_le_bytes());
154    encode_tmessage(tag, TATTACH, &body)
155}
156
157pub fn twalk(tag: u16, fid: u32, newfid: u32, wnames: &[&str]) -> Vec<u8> {
158    let mut body = Vec::new();
159    body.extend_from_slice(&fid.to_le_bytes());
160    body.extend_from_slice(&newfid.to_le_bytes());
161    body.extend_from_slice(&(wnames.len() as u16).to_le_bytes());
162    for name in wnames {
163        write_string(&mut body, name);
164    }
165    encode_tmessage(tag, TWALK, &body)
166}
167
168pub fn tlopen(tag: u16, fid: u32, flags: u32) -> Vec<u8> {
169    let mut body = Vec::new();
170    body.extend_from_slice(&fid.to_le_bytes());
171    body.extend_from_slice(&flags.to_le_bytes());
172    encode_tmessage(tag, TLOPEN, &body)
173}
174
175pub fn tread(tag: u16, fid: u32, offset: u64, count: u32) -> Vec<u8> {
176    let mut body = Vec::new();
177    body.extend_from_slice(&fid.to_le_bytes());
178    body.extend_from_slice(&offset.to_le_bytes());
179    body.extend_from_slice(&count.to_le_bytes());
180    encode_tmessage(tag, TREAD, &body)
181}
182
183pub fn twrite(tag: u16, fid: u32, offset: u64, data: &[u8]) -> Vec<u8> {
184    let mut body = Vec::new();
185    body.extend_from_slice(&fid.to_le_bytes());
186    body.extend_from_slice(&offset.to_le_bytes());
187    body.extend_from_slice(&(data.len() as u32).to_le_bytes());
188    body.extend_from_slice(data);
189    encode_tmessage(tag, TWRITE, &body)
190}
191
192pub fn tclunk(tag: u16, fid: u32) -> Vec<u8> {
193    encode_tmessage(tag, TCLUNK, &fid.to_le_bytes())
194}
195
196pub fn tgetattr(tag: u16, fid: u32, request_mask: u64) -> Vec<u8> {
197    let mut body = Vec::new();
198    body.extend_from_slice(&fid.to_le_bytes());
199    body.extend_from_slice(&request_mask.to_le_bytes());
200    encode_tmessage(tag, TGETATTR, &body)
201}
202
203pub fn treaddir(tag: u16, fid: u32, offset: u64, count: u32) -> Vec<u8> {
204    let mut body = Vec::new();
205    body.extend_from_slice(&fid.to_le_bytes());
206    body.extend_from_slice(&offset.to_le_bytes());
207    body.extend_from_slice(&count.to_le_bytes());
208    encode_tmessage(tag, TREADDIR, &body)
209}
210
211// ─────────────────────────────────────────────────────────────────────────────
212// T-messages (client → server) — parsed requests  [server-side codec]
213// ─────────────────────────────────────────────────────────────────────────────
214
215/// Parsed T-message from a client.
216///
217/// Mirrors [`Response`] for the server side. Every variant carries the `tag`
218/// out-of-band via [`parse_request`]'s return so callers don't have to thread
219/// it through each arm.
220#[derive(Debug)]
221pub enum Request {
222    Version {
223        msize: u32,
224        version: String,
225    },
226    Attach {
227        fid: u32,
228        afid: u32,
229        uname: String,
230        aname: String,
231    },
232    Flush {
233        oldtag: u16,
234    },
235    Walk {
236        fid: u32,
237        newfid: u32,
238        wnames: Vec<String>,
239    },
240    Lopen {
241        fid: u32,
242        flags: u32,
243    },
244    Read {
245        fid: u32,
246        offset: u64,
247        count: u32,
248    },
249    Write {
250        fid: u32,
251        offset: u64,
252        data: Vec<u8>,
253    },
254    Clunk {
255        fid: u32,
256    },
257    Getattr {
258        fid: u32,
259        request_mask: u64,
260    },
261    Readdir {
262        fid: u32,
263        offset: u64,
264        count: u32,
265    },
266}
267
268/// Parse a T-message from wire bytes (including length prefix).
269///
270/// Server-side counterpart to [`parse_response`]. Unknown message types bail
271/// with an error; the caller may encode an `Rlerror` instead.
272pub fn parse_request(buf: &[u8]) -> anyhow::Result<(u16, Request)> {
273    if buf.len() < 7 {
274        anyhow::bail!("9P request too short: {} bytes", buf.len());
275    }
276
277    let mut r = Cursor::new(buf);
278    let _size = read_u32(&mut r)?;
279    let msg_type = read_u8(&mut r)?;
280    let tag = read_u16(&mut r)?;
281
282    let request = match msg_type {
283        TVERSION => {
284            let msize = read_u32(&mut r)?;
285            let version = read_string(&mut r)?;
286            Request::Version { msize, version }
287        }
288        TATTACH => {
289            let fid = read_u32(&mut r)?;
290            let afid = read_u32(&mut r)?;
291            let uname = read_string(&mut r)?;
292            let aname = read_string(&mut r)?;
293            // 9P2000.L: n_uname (ignored)
294            let _n_uname = read_u32(&mut r)?;
295            Request::Attach {
296                fid,
297                afid,
298                uname,
299                aname,
300            }
301        }
302        TFLUSH => {
303            let oldtag = read_u16(&mut r)?;
304            Request::Flush { oldtag }
305        }
306        TWALK => {
307            let fid = read_u32(&mut r)?;
308            let newfid = read_u32(&mut r)?;
309            let nwname = read_u16(&mut r)?;
310            let mut wnames = Vec::with_capacity(nwname as usize);
311            for _ in 0..nwname {
312                wnames.push(read_string(&mut r)?);
313            }
314            Request::Walk {
315                fid,
316                newfid,
317                wnames,
318            }
319        }
320        TLOPEN => {
321            let fid = read_u32(&mut r)?;
322            let flags = read_u32(&mut r)?;
323            Request::Lopen { fid, flags }
324        }
325        TREAD => {
326            let fid = read_u32(&mut r)?;
327            let offset = read_u64(&mut r)?;
328            let count = read_u32(&mut r)?;
329            Request::Read { fid, offset, count }
330        }
331        TWRITE => {
332            let fid = read_u32(&mut r)?;
333            let offset = read_u64(&mut r)?;
334            let data = read_data(&mut r)?;
335            Request::Write { fid, offset, data }
336        }
337        TCLUNK => {
338            let fid = read_u32(&mut r)?;
339            Request::Clunk { fid }
340        }
341        TGETATTR => {
342            let fid = read_u32(&mut r)?;
343            let request_mask = read_u64(&mut r)?;
344            Request::Getattr { fid, request_mask }
345        }
346        TREADDIR => {
347            let fid = read_u32(&mut r)?;
348            let offset = read_u64(&mut r)?;
349            let count = read_u32(&mut r)?;
350            Request::Readdir { fid, offset, count }
351        }
352        _ => anyhow::bail!("unknown 9P request type: {msg_type}"),
353    };
354
355    Ok((tag, request))
356}
357
358/// 9P2000.L Tflush — not exercised by the client codec but defined for symmetry.
359pub const TFLUSH: u8 = 108;
360pub const RFLUSH: u8 = 109;
361
362// ─────────────────────────────────────────────────────────────────────────────
363// R-messages (server → client) — serialized responses  [server-side codec]
364// ─────────────────────────────────────────────────────────────────────────────
365
366/// Serialize an R-message (including length prefix) from a [`Response`].
367///
368/// This is the server-side write path; the client-side reader uses
369/// [`parse_response`]. `tag` is threaded in explicitly since it is a property
370/// of the request being answered, not of the response payload.
371pub fn encode_response(tag: u16, response: &Response) -> Vec<u8> {
372    match response {
373        Response::Error { ecode } => rlerror(tag, *ecode),
374        Response::Version { msize, version } => rversion(tag, *msize, version),
375        Response::Attach { qid } => rattach(tag, qid),
376        Response::Walk { qids } => rwalk(tag, qids),
377        Response::Lopen { qid, iounit } => rlopen(tag, qid, *iounit),
378        Response::Read { data } => rread(tag, data),
379        Response::Write { count } => rwrite(tag, *count),
380        Response::Clunk => rclunk(tag),
381        Response::Getattr {
382            qid,
383            mode,
384            size,
385            mtime_sec,
386        } => rgetattr(tag, qid, *mode, *size, *mtime_sec),
387        // Rreaddir shares Rread's `count[4] · data[count]` body shape but MUST
388        // carry the RREADDIR (41) message type — a standard 9P2000.L client
389        // (e.g. Wanix `p9kit.ClientFS` over `progrium/p9`) rejects an Rread (117)
390        // reply to a Treaddir. `data` is already a run of standard dirent records
391        // (`qid[13] offset[8] type[1] name[s]`); see [`encode_readdir_page`].
392        Response::Readdir { data } => rreaddir(tag, data),
393    }
394}
395
396fn encode_rmessage(tag: u16, msg_type: u8, body: &[u8]) -> Vec<u8> {
397    // identical framing to T-messages
398    encode_tmessage(tag, msg_type, body)
399}
400
401pub fn rlerror(tag: u16, ecode: u32) -> Vec<u8> {
402    encode_rmessage(tag, RLERROR, &ecode.to_le_bytes())
403}
404
405pub fn rversion(tag: u16, msize: u32, version: &str) -> Vec<u8> {
406    let mut body = Vec::new();
407    body.extend_from_slice(&msize.to_le_bytes());
408    write_string(&mut body, version);
409    encode_rmessage(tag, RVERSION, &body)
410}
411
412pub fn rattach(tag: u16, qid: &Qid) -> Vec<u8> {
413    let mut body = Vec::new();
414    qid.write_to(&mut body);
415    encode_rmessage(tag, RATTACH, &body)
416}
417
418pub fn rwalk(tag: u16, qids: &[Qid]) -> Vec<u8> {
419    let mut body = Vec::new();
420    body.extend_from_slice(&(qids.len() as u16).to_le_bytes());
421    for q in qids {
422        q.write_to(&mut body);
423    }
424    encode_rmessage(tag, RWALK, &body)
425}
426
427pub fn rlopen(tag: u16, qid: &Qid, iounit: u32) -> Vec<u8> {
428    let mut body = Vec::new();
429    qid.write_to(&mut body);
430    body.extend_from_slice(&iounit.to_le_bytes());
431    encode_rmessage(tag, RLOPEN, &body)
432}
433
434pub fn rread(tag: u16, data: &[u8]) -> Vec<u8> {
435    let mut body = Vec::new();
436    body.extend_from_slice(&(data.len() as u32).to_le_bytes());
437    body.extend_from_slice(data);
438    encode_rmessage(tag, RREAD, &body)
439}
440
441/// Encode an Rreaddir. Body is `count[4] · data[count]` (identical framing to
442/// [`rread`]) but the message type is RREADDIR (41). `data` must already be a
443/// packed run of standard dirent records — build it with [`encode_readdir_page`].
444pub fn rreaddir(tag: u16, data: &[u8]) -> Vec<u8> {
445    let mut body = Vec::new();
446    body.extend_from_slice(&(data.len() as u32).to_le_bytes());
447    body.extend_from_slice(data);
448    encode_rmessage(tag, RREADDIR, &body)
449}
450
451pub fn rwrite(tag: u16, count: u32) -> Vec<u8> {
452    encode_rmessage(tag, RWRITE, &count.to_le_bytes())
453}
454
455pub fn rclunk(tag: u16) -> Vec<u8> {
456    encode_rmessage(tag, RCLUNK, &[])
457}
458
459pub fn rflush(tag: u16) -> Vec<u8> {
460    encode_rmessage(tag, RFLUSH, &[])
461}
462
463/// Encode an Rgetattr. Only the fields carried by [`Response::Getattr`] are
464/// populated; the rest are zero (matches the subset the client decoder reads).
465#[allow(clippy::too_many_lines)]
466pub fn rgetattr(tag: u16, qid: &Qid, mode: u32, size: u64, mtime_sec: u64) -> Vec<u8> {
467    // valid mask: P9_GETATTR_BASIC = 0x7ff (mode, nlink, uid, gid, rdev, size,
468    // atime, mtime, ctime). We advertise all-basic so Linux clients decode the
469    // fields we do fill.
470    let valid: u64 = 0x7ff;
471    let mut body = Vec::with_capacity(153);
472    body.extend_from_slice(&valid.to_le_bytes());
473    qid.write_to(&mut body);
474    body.extend_from_slice(&mode.to_le_bytes());
475    body.extend_from_slice(&0u32.to_le_bytes()); // uid
476    body.extend_from_slice(&0u32.to_le_bytes()); // gid
477    body.extend_from_slice(&1u64.to_le_bytes()); // nlink
478    body.extend_from_slice(&0u64.to_le_bytes()); // rdev
479    body.extend_from_slice(&size.to_le_bytes());
480    body.extend_from_slice(&4096u64.to_le_bytes()); // blksize
481    body.extend_from_slice(&0u64.to_le_bytes()); // blocks
482    body.extend_from_slice(&mtime_sec.to_le_bytes()); // atime_sec
483    body.extend_from_slice(&0u64.to_le_bytes()); // atime_nsec
484    body.extend_from_slice(&mtime_sec.to_le_bytes()); // mtime_sec
485    body.extend_from_slice(&0u64.to_le_bytes()); // mtime_nsec
486    body.extend_from_slice(&mtime_sec.to_le_bytes()); // ctime_sec
487    body.extend_from_slice(&0u64.to_le_bytes()); // ctime_nsec
488    body.extend_from_slice(&0u64.to_le_bytes()); // btime_sec
489    body.extend_from_slice(&0u64.to_le_bytes()); // btime_nsec
490    body.extend_from_slice(&0u64.to_le_bytes()); // gen
491    body.extend_from_slice(&0u64.to_le_bytes()); // data_version
492    encode_rmessage(tag, RGETATTR, &body)
493}
494
495// ─────────────────────────────────────────────────────────────────────────────
496// R-messages (server → client) — parsed responses  [client-side codec]
497// ─────────────────────────────────────────────────────────────────────────────
498
499/// Parsed R-message from server.
500#[derive(Debug)]
501pub enum Response {
502    Version {
503        msize: u32,
504        version: String,
505    },
506    Attach {
507        qid: Qid,
508    },
509    Walk {
510        qids: Vec<Qid>,
511    },
512    Lopen {
513        qid: Qid,
514        iounit: u32,
515    },
516    Read {
517        data: Vec<u8>,
518    },
519    Write {
520        count: u32,
521    },
522    Clunk,
523    Getattr {
524        qid: Qid,
525        mode: u32,
526        size: u64,
527        mtime_sec: u64,
528    },
529    Readdir {
530        data: Vec<u8>,
531    },
532    Error {
533        ecode: u32,
534    },
535}
536
537/// Parse an R-message from wire bytes (including length prefix).
538pub fn parse_response(buf: &[u8]) -> anyhow::Result<(u16, Response)> {
539    if buf.len() < 7 {
540        anyhow::bail!("9P response too short: {} bytes", buf.len());
541    }
542
543    let mut r = Cursor::new(buf);
544    let _size = read_u32(&mut r)?;
545    let msg_type = read_u8(&mut r)?;
546    let tag = read_u16(&mut r)?;
547
548    let response = match msg_type {
549        RLERROR => {
550            let ecode = read_u32(&mut r)?;
551            Response::Error { ecode }
552        }
553        RVERSION => {
554            let msize = read_u32(&mut r)?;
555            let version = read_string(&mut r)?;
556            Response::Version { msize, version }
557        }
558        RATTACH => {
559            let qid = Qid::read_from(&mut r)?;
560            Response::Attach { qid }
561        }
562        RWALK => {
563            let nwqid = read_u16(&mut r)?;
564            let mut qids = Vec::with_capacity(nwqid as usize);
565            for _ in 0..nwqid {
566                qids.push(Qid::read_from(&mut r)?);
567            }
568            Response::Walk { qids }
569        }
570        RLOPEN => {
571            let qid = Qid::read_from(&mut r)?;
572            let iounit = read_u32(&mut r)?;
573            Response::Lopen { qid, iounit }
574        }
575        RREAD => {
576            let data = read_data(&mut r)?;
577            Response::Read { data }
578        }
579        RWRITE => {
580            let count = read_u32(&mut r)?;
581            Response::Write { count }
582        }
583        RCLUNK => Response::Clunk,
584        RGETATTR => {
585            let _valid = read_u64(&mut r)?;
586            let qid = Qid::read_from(&mut r)?;
587            let mode = read_u32(&mut r)?;
588            let _uid = read_u32(&mut r)?;
589            let _gid = read_u32(&mut r)?;
590            let _nlink = read_u64(&mut r)?;
591            let _rdev = read_u64(&mut r)?;
592            let size = read_u64(&mut r)?;
593            let _blksize = read_u64(&mut r)?;
594            let _blocks = read_u64(&mut r)?;
595            let _atime_sec = read_u64(&mut r)?;
596            let _atime_nsec = read_u64(&mut r)?;
597            let mtime_sec = read_u64(&mut r)?;
598            let _mtime_nsec = read_u64(&mut r)?;
599            let _ctime_sec = read_u64(&mut r)?;
600            let _ctime_nsec = read_u64(&mut r)?;
601            let _btime_sec = read_u64(&mut r)?;
602            let _btime_nsec = read_u64(&mut r)?;
603            let _gen = read_u64(&mut r)?;
604            let _data_version = read_u64(&mut r)?;
605            Response::Getattr {
606                qid,
607                mode,
608                size,
609                mtime_sec,
610            }
611        }
612        RREADDIR => {
613            let data = read_data(&mut r)?;
614            Response::Readdir { data }
615        }
616        _ => anyhow::bail!("unknown 9P response type: {msg_type}"),
617    };
618
619    Ok((tag, response))
620}
621
622// ─────────────────────────────────────────────────────────────────────────────
623// Readdir entry parsing
624// ─────────────────────────────────────────────────────────────────────────────
625
626/// A parsed directory entry from Rreaddir data.
627#[derive(Debug)]
628pub struct DirEntryP9 {
629    pub qid: Qid,
630    pub offset: u64,
631    pub dtype: u8,
632    pub name: String,
633}
634
635/// One directory entry to encode into an Rreaddir payload.
636///
637/// The inverse of [`DirEntryP9`]: the server builds these, the client parses
638/// the resulting bytes back into `DirEntryP9`s. `qid` carries the entry's
639/// identity (its `qtype` also supplies the dirent type byte); `name` is the
640/// single path component.
641#[derive(Debug, Clone)]
642pub struct ReaddirEntry {
643    pub qid: Qid,
644    pub name: String,
645}
646
647/// Encode a directory listing as a page of **standard 9P2000.L Rreaddir dirent
648/// records** with cookie-based paging.
649///
650/// Each record is `qid[13] · offset[8] · type[1] · name[s]` — the exact shape
651/// [`parse_readdir_entries`] (and any standard client such as `progrium/p9`)
652/// decodes. `entries` is the *full* listing in a stable order; the record's
653/// `offset` is a resumption cookie equal to the entry's 1-based index.
654///
655/// Paging contract (as required by 9P2000.L, distinct from a byte-offset read):
656/// - `offset` is a dirent cookie — only entries whose cookie is `> offset` are
657///   emitted (so a client resumes by passing back the last cookie it saw).
658/// - `count` is a byte budget — records are packed **whole** (never split) until
659///   the next record would exceed it. A single record larger than `count` is
660///   still emitted alone so the client can always make progress.
661///
662/// The dirent `type` byte is the entry's qid type (`QTDIR`=0x80 / `QTFILE`=0x00);
663/// `progrium/p9` reads it as a `QIDType`, and Wanix's `p9kit` re-walks each name
664/// anyway, so this is the interoperable choice.
665pub fn encode_readdir_page(entries: &[ReaddirEntry], offset: u64, count: u32) -> Vec<u8> {
666    let budget = count as usize;
667    let mut out = Vec::new();
668    for (i, e) in entries.iter().enumerate() {
669        let cookie = i as u64 + 1;
670        if cookie <= offset {
671            continue;
672        }
673        let mut rec = Vec::new();
674        e.qid.write_to(&mut rec); // qid[13]
675        rec.extend_from_slice(&cookie.to_le_bytes()); // offset[8]
676        rec.push(e.qid.qtype); // type[1] — dirent type = qid type
677        write_string(&mut rec, &e.name); // name[2+len]
678        if !out.is_empty() && out.len() + rec.len() > budget {
679            break;
680        }
681        out.extend_from_slice(&rec);
682    }
683    out
684}
685
686/// Parse Rreaddir data into directory entries.
687pub fn parse_readdir_entries(data: &[u8]) -> anyhow::Result<Vec<DirEntryP9>> {
688    let mut entries = Vec::new();
689    let mut r = Cursor::new(data);
690
691    while (r.position() as usize) < data.len() {
692        let qid = Qid::read_from(&mut r)?;
693        let offset = read_u64(&mut r)?;
694        let dtype = read_u8(&mut r)?;
695        let name = read_string(&mut r)?;
696        entries.push(DirEntryP9 {
697            qid,
698            offset,
699            dtype,
700            name,
701        });
702    }
703
704    Ok(entries)
705}