Skip to main content

matter_kit/platform/
os.rs

1//! The platform traits on an operating system, with no async runtime.
2//!
3//! This is what a Linux or macOS build gets: real UDP sockets, a real clock, the system
4//! entropy source, and a file-backed key-value store. It deliberately does **not** depend
5//! on Tokio or any other runtime — the futures here are driven by whatever executor the
6//! consumer already has, including [`block_on`].
7//!
8//! The mechanism is a thread per blocking resource: a socket's receiver thread parks in
9//! `recv_from` and wakes the task when a datagram lands; a timer's thread sleeps and wakes
10//! the task when the deadline passes. That is not how a high-performance server is built —
11//! it is how a *runtime-agnostic* platform is built without an epoll reactor of our own,
12//! and a Matter node's socket count is measured in ones.
13//!
14//! A consumer with a runtime should implement the traits against it instead; that is a few
15//! dozen lines and it is what `examples/` does for Embassy.
16
17use std::collections::VecDeque;
18use std::fs;
19use std::future::Future;
20use std::io::{ErrorKind, Read as _, Write as _};
21use std::net::{Ipv6Addr, SocketAddr, SocketAddrV6, UdpSocket};
22use std::path::{Path, PathBuf};
23use std::sync::atomic::{AtomicBool, Ordering};
24use std::sync::{Arc, Condvar, Mutex};
25use std::task::{Poll, Waker};
26
27use super::{Clock, Granularity, Instant, KvStore, PeerAddr, Rng, Timer, Udp};
28use crate::config::MAX_UDP_MESSAGE;
29use crate::error::{Error, ErrorCode, Result};
30
31fn platform_error(_: impl core::fmt::Debug) -> Error {
32    Error::new(ErrorCode::Platform)
33}
34
35// --- Time ---------------------------------------------------------------------------
36
37/// The system's monotonic clock, and sleeping on it.
38///
39/// [`Timer::now`] is measured from the first `StdTimer` created in the process, so the
40/// numbers in a log stay small and comparable.
41#[derive(Debug, Clone)]
42pub struct StdTimer {
43    origin: std::time::Instant,
44}
45
46impl Default for StdTimer {
47    fn default() -> Self {
48        Self::new()
49    }
50}
51
52impl StdTimer {
53    /// Starts a timeline at this moment.
54    #[must_use]
55    pub fn new() -> Self {
56        Self {
57            origin: std::time::Instant::now(),
58        }
59    }
60}
61
62impl Timer for StdTimer {
63    fn now(&self) -> Instant {
64        Instant::from_micros(u64::try_from(self.origin.elapsed().as_micros()).unwrap_or(u64::MAX))
65    }
66
67    fn sleep_until(&self, deadline: Instant) -> impl Future<Output = ()> {
68        let origin = self.origin;
69        // One thread per sleep, started at the first poll that is not already due.
70        let mut started = false;
71        core::future::poll_fn(move |cx| {
72            let now = Instant::from_micros(
73                u64::try_from(origin.elapsed().as_micros()).unwrap_or(u64::MAX),
74            );
75            if deadline.is_elapsed_at(now) {
76                return Poll::Ready(());
77            }
78            if !started {
79                started = true;
80                let remaining = deadline.saturating_duration_since(now);
81                let waker = cx.waker().clone();
82                let _ = std::thread::Builder::new()
83                    .name("matter-kit-timer".into())
84                    .spawn(move || {
85                        std::thread::sleep(std::time::Duration::from_micros(remaining.as_micros()));
86                        waker.wake();
87                    });
88            }
89            Poll::Pending
90        })
91    }
92}
93
94/// The system wall clock, in the Matter epoch.
95#[derive(Debug, Clone, Copy, Default)]
96pub struct StdClock;
97
98/// Seconds between the Unix epoch (1970-01-01) and the Matter epoch (2000-01-01).
99const UNIX_TO_MATTER_EPOCH_SECS: u64 = 946_684_800;
100
101impl Clock for StdClock {
102    fn utc(&self) -> Option<u64> {
103        let unix = std::time::SystemTime::now()
104            .duration_since(std::time::UNIX_EPOCH)
105            .ok()?;
106        let secs = unix.as_secs().checked_sub(UNIX_TO_MATTER_EPOCH_SECS)?;
107        secs.checked_mul(1_000_000)
108            .and_then(|us| us.checked_add(u64::from(unix.subsec_micros())))
109    }
110
111    fn granularity(&self) -> Granularity {
112        Granularity::MicrosecondsGranularity
113    }
114}
115
116// --- Randomness ---------------------------------------------------------------------
117
118/// The operating system's entropy source.
119///
120/// Reads `/dev/urandom`, which on every platform this module builds for is a
121/// cryptographically secure generator seeded by the kernel. A short read is an error, not
122/// a partially-filled buffer: a nonce that is half predictable is not a nonce.
123#[derive(Debug, Clone, Copy, Default)]
124pub struct StdRng;
125
126impl Rng for StdRng {
127    fn fill(&self, out: &mut [u8]) -> Result<()> {
128        let mut f = fs::File::open("/dev/urandom").map_err(platform_error)?;
129        f.read_exact(out).map_err(platform_error)
130    }
131}
132
133// --- UDP ----------------------------------------------------------------------------
134
135#[derive(Debug, Default)]
136struct Inbox {
137    queue: VecDeque<(Vec<u8>, PeerAddr)>,
138    waker: Option<Waker>,
139    failed: bool,
140}
141
142/// An IPv6 UDP socket, with a receiver thread behind it.
143#[derive(Debug)]
144pub struct StdUdp {
145    socket: Arc<UdpSocket>,
146    inbox: Arc<Mutex<Inbox>>,
147    stop: Arc<AtomicBool>,
148    /// The interface index [`StdUdp::bind_mdns`] joined the group on.
149    mdns_scope: Option<u32>,
150}
151
152impl StdUdp {
153    /// Binds to `port` on every IPv6 interface, and starts receiving.
154    ///
155    /// Pass [`crate::PORT`] for an operational node; pass 0 to let the system choose,
156    /// which is what a commissioner and every test wants.
157    pub fn bind(port: u16) -> Result<Self> {
158        let addr = SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::UNSPECIFIED, port, 0, 0));
159        let socket = UdpSocket::bind(addr).map_err(platform_error)?;
160        Self::from_socket(socket)
161    }
162
163    /// Binds the mDNS port and joins Matter's link-local group (Core §4.3, RFC 6762).
164    ///
165    /// A responder has to *own* port 5353: mDNS queries are multicast to `ff02::fb:5353` and
166    /// a socket on any other port never sees them. That port is almost always already held —
167    /// by `mDNSResponder` on macOS, by Avahi on most Linux — so it is bound with
168    /// `SO_REUSEADDR` (and `SO_REUSEPORT` where it exists), which is what lets several
169    /// responders share it. This is the one thing in the crate that `std::net` cannot do:
170    /// a socket option has to be set *before* `bind`, and `std` gives no handle in between.
171    ///
172    /// `scope_id` is the interface index to join the group on, from `if_nametoindex`. It is
173    /// also the zone every *answer* must be sent with — see [`StdUdp::mdns_group`] — so `0`
174    /// is rarely what you want: some systems accept it for the join and then refuse every
175    /// send, because a link-local destination with no interface is ambiguous.
176    ///
177    /// The socket is IPv6-only. Matter's operational discovery is IPv6 (§4.3.1), and a
178    /// dual-stack socket would also receive the IPv4 mDNS traffic of every other protocol on
179    /// the link.
180    pub fn bind_mdns(scope_id: u32) -> Result<Self> {
181        use socket2::{Domain, Protocol, SockAddr, Socket, Type};
182
183        let socket =
184            Socket::new(Domain::IPV6, Type::DGRAM, Some(Protocol::UDP)).map_err(platform_error)?;
185        socket.set_only_v6(true).map_err(platform_error)?;
186        socket.set_reuse_address(true).map_err(platform_error)?;
187        #[cfg(unix)]
188        socket.set_reuse_port(true).map_err(platform_error)?;
189
190        let addr = SocketAddr::V6(SocketAddrV6::new(
191            Ipv6Addr::UNSPECIFIED,
192            crate::discovery::MDNS_PORT,
193            0,
194            scope_id,
195        ));
196        socket.bind(&SockAddr::from(addr)).map_err(platform_error)?;
197
198        let mut udp = Self::from_socket(socket.into())?;
199        udp.join_multicast(crate::discovery::MDNS_IPV6_GROUP, scope_id)?;
200        udp.mdns_scope = Some(scope_id);
201        Ok(udp)
202    }
203
204    /// The address to send mDNS answers to, zoned to the interface this socket joined.
205    ///
206    /// **Not a constant**, and that is the whole point. `ff02::fb` is *link-local*, and a
207    /// link-local destination without an interface to send it on is ambiguous: the operating
208    /// system rejects it rather than guessing. A responder that sent to the bare group
209    /// address would compute perfectly correct answers and transmit none of them — with the
210    /// error arriving from `send_to`, far from the discovery code that looks wrong.
211    ///
212    /// `None` when this socket was not created by [`StdUdp::bind_mdns`].
213    #[must_use]
214    pub fn mdns_group(&self) -> Option<PeerAddr> {
215        let scope = self.mdns_scope?;
216        let mut addr = PeerAddr::with_port(
217            crate::discovery::MDNS_IPV6_GROUP,
218            crate::discovery::MDNS_PORT,
219        );
220        addr.scope_id = scope;
221        Some(addr)
222    }
223
224    /// Takes over an already-bound socket.
225    pub fn from_socket(socket: UdpSocket) -> Result<Self> {
226        let socket = Arc::new(socket);
227        let inbox = Arc::new(Mutex::new(Inbox::default()));
228        let stop = Arc::new(AtomicBool::new(false));
229
230        // A read timeout so the thread notices `stop` rather than parking forever.
231        socket
232            .set_read_timeout(Some(std::time::Duration::from_millis(200)))
233            .map_err(platform_error)?;
234
235        let rx_socket = Arc::clone(&socket);
236        let rx_inbox = Arc::clone(&inbox);
237        let rx_stop = Arc::clone(&stop);
238        std::thread::Builder::new()
239            .name("matter-kit-udp".into())
240            .spawn(move || {
241                let mut buf = [0u8; MAX_UDP_MESSAGE];
242                while !rx_stop.load(Ordering::Relaxed) {
243                    match rx_socket.recv_from(&mut buf) {
244                        Ok((n, from)) => {
245                            let Some(data) = buf.get(..n) else { continue };
246                            let Ok(mut inbox) = rx_inbox.lock() else {
247                                return;
248                            };
249                            inbox.queue.push_back((data.to_vec(), to_peer(from)));
250                            if let Some(w) = inbox.waker.take() {
251                                w.wake();
252                            }
253                        }
254                        Err(e)
255                            if matches!(
256                                e.kind(),
257                                ErrorKind::WouldBlock
258                                    | ErrorKind::TimedOut
259                                    | ErrorKind::Interrupted
260                            ) => {}
261                        Err(_) => {
262                            let Ok(mut inbox) = rx_inbox.lock() else {
263                                return;
264                            };
265                            inbox.failed = true;
266                            if let Some(w) = inbox.waker.take() {
267                                w.wake();
268                            }
269                            return;
270                        }
271                    }
272                }
273            })
274            .map_err(platform_error)?;
275
276        Ok(Self {
277            socket,
278            inbox,
279            stop,
280            mdns_scope: None,
281        })
282    }
283
284    /// The address the socket is bound to, which is how a test finds the port.
285    pub fn local_addr(&self) -> Result<PeerAddr> {
286        self.socket
287            .local_addr()
288            .map(to_peer)
289            .map_err(platform_error)
290    }
291}
292
293impl Drop for StdUdp {
294    fn drop(&mut self) {
295        self.stop.store(true, Ordering::Relaxed);
296    }
297}
298
299fn to_peer(addr: SocketAddr) -> PeerAddr {
300    match addr {
301        SocketAddr::V6(v6) => PeerAddr {
302            addr: v6.ip().octets(),
303            port: v6.port(),
304            scope_id: v6.scope_id(),
305        },
306        // Matter is IPv6-only operationally (Core §2.5.6); an IPv4 peer is mapped so it
307        // is at least representable rather than silently becoming a different address.
308        SocketAddr::V4(v4) => PeerAddr {
309            addr: v4.ip().to_ipv6_mapped().octets(),
310            port: v4.port(),
311            scope_id: 0,
312        },
313    }
314}
315
316fn from_peer(addr: PeerAddr) -> SocketAddr {
317    SocketAddr::V6(SocketAddrV6::new(
318        Ipv6Addr::from(addr.addr),
319        addr.port,
320        0,
321        addr.scope_id,
322    ))
323}
324
325impl Udp for StdUdp {
326    fn recv_from(&self, buf: &mut [u8]) -> impl Future<Output = Result<(usize, PeerAddr)>> {
327        core::future::poll_fn(move |cx| {
328            let Ok(mut inbox) = self.inbox.lock() else {
329                return Poll::Ready(Err(Error::new(ErrorCode::Platform)));
330            };
331            if inbox.failed {
332                return Poll::Ready(Err(Error::new(ErrorCode::Platform)));
333            }
334            match inbox.queue.pop_front() {
335                Some((data, from)) => {
336                    let n = data.len().min(buf.len());
337                    let (Some(dst), Some(src)) = (buf.get_mut(..n), data.get(..n)) else {
338                        return Poll::Ready(Err(Error::new(ErrorCode::BufferTooSmall)));
339                    };
340                    dst.copy_from_slice(src);
341                    Poll::Ready(Ok((n, from)))
342                }
343                None => {
344                    inbox.waker = Some(cx.waker().clone());
345                    Poll::Pending
346                }
347            }
348        })
349    }
350
351    fn send_to(&self, buf: &[u8], addr: PeerAddr) -> impl Future<Output = Result<()>> {
352        let result = self
353            .socket
354            .send_to(buf, from_peer(addr))
355            .map_err(platform_error)
356            .and_then(|n| {
357                if n == buf.len() {
358                    Ok(())
359                } else {
360                    Err(Error::new(ErrorCode::Platform))
361                }
362            });
363        core::future::ready(result)
364    }
365
366    fn join_multicast(&self, group: [u8; 16], scope_id: u32) -> Result<()> {
367        self.socket
368            .join_multicast_v6(&Ipv6Addr::from(group), scope_id)
369            .map_err(platform_error)
370    }
371
372    fn leave_multicast(&self, group: [u8; 16], scope_id: u32) -> Result<()> {
373        self.socket
374            .leave_multicast_v6(&Ipv6Addr::from(group), scope_id)
375            .map_err(platform_error)
376    }
377}
378
379// --- Storage ------------------------------------------------------------------------
380
381/// A key-value store as one file per key in a directory.
382///
383/// Writes go to a temporary file and are renamed into place, so a power cut leaves either
384/// the old value or the new one and never half of either — which is the property the
385/// fail-safe of Core §11.10 is built on.
386#[derive(Debug, Clone)]
387pub struct FileKv {
388    root: PathBuf,
389}
390
391impl FileKv {
392    /// Opens (and creates) a store rooted at `path`.
393    pub fn open(path: impl AsRef<Path>) -> Result<Self> {
394        let root = path.as_ref().to_path_buf();
395        fs::create_dir_all(&root).map_err(platform_error)?;
396        Ok(Self { root })
397    }
398
399    /// Maps a key to a file name in the root directory.
400    ///
401    /// Keys are hierarchical (`attrs/1/6`) but the store is flat: the whole key becomes
402    /// one file name. The encoding is `[a-zA-Z0-9-]` verbatim and every other byte as
403    /// `_XX` in hex, which has the two properties that matter.
404    ///
405    /// It is **injective**, so two different keys cannot land on one file — a mapping
406    /// that turned both `a.b` and `a/b` into `a%b` would silently alias two fabrics.
407    ///
408    /// And it can never produce `.`, `..`, a separator or the empty string, so a key
409    /// cannot escape the root no matter what it contains — an empty name would make the
410    /// path the root directory itself. Keys come from this crate today, but a key that
411    /// reaches a file path is exactly the sort of thing that later gets built out of
412    /// something a peer said.
413    fn path_of(&self, key: &str) -> PathBuf {
414        // The leading `k` is what keeps the empty key from naming the root.
415        let mut name = String::with_capacity(key.len().saturating_add(1));
416        name.push('k');
417        for b in key.as_bytes() {
418            match b {
419                b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'-' => name.push(char::from(*b)),
420                _ => {
421                    name.push('_');
422                    name.push(hex_digit(b >> 4));
423                    name.push(hex_digit(b & 0x0f));
424                }
425            }
426        }
427        self.root.join(name)
428    }
429}
430
431/// One lowercase hex digit for a nibble, for [`FileKv::path_of`].
432///
433/// Takes the low four bits itself, so there is no value of `nibble` for which this has no
434/// answer — which is what lets it return a `char` rather than an `Option`.
435const fn hex_digit(nibble: u8) -> char {
436    match nibble & 0x0f {
437        0 => '0',
438        1 => '1',
439        2 => '2',
440        3 => '3',
441        4 => '4',
442        5 => '5',
443        6 => '6',
444        7 => '7',
445        8 => '8',
446        9 => '9',
447        10 => 'a',
448        11 => 'b',
449        12 => 'c',
450        13 => 'd',
451        14 => 'e',
452        _ => 'f',
453    }
454}
455
456impl KvStore for FileKv {
457    fn get(&self, key: &str, out: &mut [u8]) -> impl Future<Output = Result<Option<usize>>> {
458        let result = match fs::read(self.path_of(key)) {
459            Ok(data) => match out.get_mut(..data.len()) {
460                Some(dst) => {
461                    dst.copy_from_slice(&data);
462                    Ok(Some(data.len()))
463                }
464                None => Err(Error::new(ErrorCode::BufferTooSmall)),
465            },
466            Err(e) if e.kind() == ErrorKind::NotFound => Ok(None),
467            Err(e) => Err(platform_error(e)),
468        };
469        core::future::ready(result)
470    }
471
472    fn set(&self, key: &str, value: &[u8]) -> impl Future<Output = Result<()>> {
473        let path = self.path_of(key);
474        let result = (|| {
475            let tmp = path.with_extension("tmp");
476            let mut f = fs::File::create(&tmp).map_err(platform_error)?;
477            f.write_all(value).map_err(platform_error)?;
478            f.sync_all().map_err(platform_error)?;
479            fs::rename(&tmp, &path).map_err(platform_error)
480        })();
481        core::future::ready(result)
482    }
483
484    fn remove(&self, key: &str) -> impl Future<Output = Result<()>> {
485        let result = match fs::remove_file(self.path_of(key)) {
486            Ok(()) => Ok(()),
487            Err(e) if e.kind() == ErrorKind::NotFound => Ok(()),
488            Err(e) => Err(platform_error(e)),
489        };
490        core::future::ready(result)
491    }
492
493    fn remove_prefix(&self, prefix: &str) -> impl Future<Output = Result<()>> {
494        let encoded = self.path_of(prefix);
495        let Some(encoded) = encoded.file_name().and_then(|s| s.to_str()) else {
496            return core::future::ready(Err(Error::new(ErrorCode::InvalidArgument)));
497        };
498        let result = (|| {
499            let entries = fs::read_dir(&self.root).map_err(platform_error)?;
500            for entry in entries.flatten() {
501                let name = entry.file_name();
502                let Some(name) = name.to_str() else { continue };
503                if name.starts_with(encoded) {
504                    let _ = fs::remove_file(entry.path());
505                }
506            }
507            Ok(())
508        })();
509        core::future::ready(result)
510    }
511}
512
513// --- Executor -----------------------------------------------------------------------
514
515/// Runs a future to completion on the current thread, parking between wakeups.
516///
517/// A consumer with a runtime uses theirs; this is for tests, examples and small daemons
518/// that would rather not take a dependency for one `block_on`.
519pub fn block_on<F: Future>(fut: F) -> F::Output {
520    struct Park {
521        awake: Mutex<bool>,
522        condvar: Condvar,
523    }
524
525    impl std::task::Wake for Park {
526        fn wake(self: Arc<Self>) {
527            self.wake_by_ref();
528        }
529        fn wake_by_ref(self: &Arc<Self>) {
530            if let Ok(mut awake) = self.awake.lock() {
531                *awake = true;
532                self.condvar.notify_one();
533            }
534        }
535    }
536
537    let park = Arc::new(Park {
538        awake: Mutex::new(false),
539        condvar: Condvar::new(),
540    });
541    let waker = Waker::from(Arc::clone(&park));
542    let mut cx = std::task::Context::from_waker(&waker);
543    let mut fut = core::pin::pin!(fut);
544
545    'outer: loop {
546        if let Poll::Ready(v) = fut.as_mut().poll(&mut cx) {
547            return v;
548        }
549        let Ok(mut awake) = park.awake.lock() else {
550            // A poisoned lock cannot be recovered from here; go round and poll again so
551            // the future's own error handling gets a chance rather than aborting.
552            continue;
553        };
554        while !*awake {
555            match park.condvar.wait(awake) {
556                Ok(next) => awake = next,
557                // The wait failed; fall back to polling, which is always safe. The guard
558                // is gone with the failed wait, so there is nothing to reset here.
559                Err(_) => continue 'outer,
560            }
561        }
562        // `awake` is still held from the wait; reset it through that guard rather than
563        // locking again, which would deadlock on a non-reentrant mutex.
564        *awake = false;
565    }
566}
567
568#[cfg(test)]
569#[allow(clippy::arithmetic_side_effects, clippy::indexing_slicing)]
570mod tests {
571    use super::*;
572    use crate::platform::Duration;
573
574    #[test]
575    fn udp_round_trips_on_loopback() {
576        let a = StdUdp::bind(0).expect("bind a");
577        let b = StdUdp::bind(0).expect("bind b");
578        let mut b_addr = b.local_addr().expect("addr");
579        b_addr.addr = Ipv6Addr::LOCALHOST.octets();
580
581        block_on(async {
582            a.send_to(b"matter", b_addr).await.expect("send");
583            let mut buf = [0u8; 64];
584            let (n, _from) = b.recv_from(&mut buf).await.expect("recv");
585            assert_eq!(&buf[..n], b"matter");
586        });
587    }
588
589    #[test]
590    fn the_timer_sleeps_about_the_right_amount() {
591        let t = StdTimer::new();
592        let start = t.now();
593        block_on(t.sleep(Duration::from_millis(20)));
594        let slept = t.now().saturating_duration_since(start);
595        assert!(slept >= Duration::from_millis(20), "slept {slept:?}");
596        assert!(slept < Duration::from_secs(2), "slept {slept:?}");
597    }
598
599    #[test]
600    fn the_clock_is_in_the_matter_epoch() {
601        let utc = StdClock.utc().expect("a clock");
602        // 2020-01-01 in the Matter epoch; any real clock is past it and short of 2100.
603        assert!(utc > 631_152_000_000_000, "{utc}");
604        assert!(utc < 3_155_760_000_000_000, "{utc}");
605    }
606
607    #[test]
608    fn random_bytes_differ() {
609        let mut a = [0u8; 32];
610        let mut b = [0u8; 32];
611        StdRng.fill(&mut a).expect("entropy");
612        StdRng.fill(&mut b).expect("entropy");
613        assert_ne!(a, b);
614    }
615
616    #[test]
617    fn the_file_store_round_trips_and_isolates_keys() {
618        let dir = std::env::temp_dir().join(std::format!("matter-kit-kv-{}", std::process::id()));
619        let kv = FileKv::open(&dir).expect("open");
620        block_on(async {
621            let mut buf = [0u8; 64];
622            assert_eq!(kv.get("fabrics", &mut buf).await.expect("get"), None);
623            kv.set("fabrics", b"abc").await.expect("set");
624            assert_eq!(kv.get("fabrics", &mut buf).await.expect("get"), Some(3));
625            assert_eq!(&buf[..3], b"abc");
626
627            kv.set("app/one", b"1").await.expect("set");
628            kv.set("app/two", b"2").await.expect("set");
629            kv.remove_prefix("app/").await.expect("remove_prefix");
630            assert_eq!(kv.get("app/one", &mut buf).await.expect("get"), None);
631            assert_eq!(kv.get("fabrics", &mut buf).await.expect("get"), Some(3));
632        });
633        let _ = fs::remove_dir_all(&dir);
634    }
635
636    #[test]
637    fn a_key_cannot_escape_the_root() {
638        let dir = std::env::temp_dir().join("matter-kit-kv-escape");
639        let kv = FileKv::open(&dir).expect("open");
640        for key in ["../../etc/passwd", "..", ".", "/", "a/../b", ""] {
641            let path = kv.path_of(key);
642            assert!(path.starts_with(&dir), "{key:?} -> {path:?}");
643            let name = path
644                .file_name()
645                .unwrap_or_default()
646                .to_string_lossy()
647                .into_owned();
648            assert!(!name.contains('.'), "{key:?} -> {name}");
649            assert!(!name.contains('/'), "{key:?} -> {name}");
650            assert_eq!(path.parent(), Some(dir.as_path()), "{key:?}");
651        }
652        let _ = fs::remove_dir_all(&dir);
653    }
654
655    #[test]
656    fn distinct_keys_get_distinct_files() {
657        // The first cut mapped every non-alphanumeric byte to `%`, so `a.b` and `a/b`
658        // became the same file and two different fabrics shared one blob.
659        let dir = std::env::temp_dir().join("matter-kit-kv-injective");
660        let kv = FileKv::open(&dir).expect("open");
661        let keys = ["a.b", "a/b", "a_b", "a-b", "attrs/1/6", "attrs/1_6"];
662        for (i, a) in keys.iter().enumerate() {
663            for b in keys.iter().skip(i + 1) {
664                assert_ne!(kv.path_of(a), kv.path_of(b), "{a} and {b} collide");
665            }
666        }
667        let _ = fs::remove_dir_all(&dir);
668    }
669}