nix_compat/store_path/
mod.rs

1use crate::nixbase32;
2use data_encoding::DecodeError;
3#[cfg(feature = "serde")]
4use serde::{Deserialize, Serialize};
5use std::{
6    fmt,
7    str::{self, FromStr},
8};
9use thiserror;
10
11mod utils;
12
13pub use utils::*;
14
15pub const DIGEST_SIZE: usize = 20;
16pub const ENCODED_DIGEST_SIZE: usize = nixbase32::encode_len(DIGEST_SIZE);
17
18// The store dir prefix, without trailing slash.
19// That's usually where the Nix store is mounted at.
20pub const STORE_DIR: &str = "/nix/store";
21pub const STORE_DIR_WITH_SLASH: &str = "/nix/store/";
22
23/// Errors that can occur when parsing a literal store path
24#[derive(Debug, PartialEq, Eq, thiserror::Error)]
25pub enum Error {
26    #[error("Dash is missing between hash and name")]
27    MissingDash,
28    #[error("Hash encoding is invalid: {0}")]
29    InvalidHashEncoding(#[from] DecodeError),
30    #[error("Invalid length")]
31    InvalidLength,
32    #[error("Invalid name")]
33    InvalidName,
34    #[error("Tried to parse an absolute path which was missing the store dir prefix.")]
35    MissingStoreDir,
36}
37
38/// Represents a path in the Nix store (a direct child of [STORE_DIR]).
39///
40/// It consists of a digest (20 bytes), and a name, which is a string.
41/// The name may only contain ASCII alphanumeric, or one of the following
42/// characters: `-`, `_`, `.`, `+`, `?`, `=`.
43/// The name is usually used to describe the pname and version of a package.
44/// Derivation paths can also be represented as store paths, their names just
45/// end with the `.drv` prefix.
46///
47/// A [StorePath] does not encode any additional subpath "inside" the store
48/// path.
49#[derive(Clone, Debug)]
50pub struct StorePath<S> {
51    digest: [u8; DIGEST_SIZE],
52    name: S,
53}
54
55impl<S> PartialEq for StorePath<S>
56where
57    S: AsRef<str>,
58{
59    fn eq(&self, other: &Self) -> bool {
60        self.digest() == other.digest() && self.name().as_ref() == other.name().as_ref()
61    }
62}
63
64impl<S> Eq for StorePath<S> where S: AsRef<str> {}
65
66impl<S> std::hash::Hash for StorePath<S>
67where
68    S: AsRef<str>,
69{
70    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
71        state.write(&self.digest);
72        state.write(self.name.as_ref().as_bytes());
73    }
74}
75
76// Ensures it's possible to get() from a HashMap using StorePathRef<'_>,
77// even if it itself uses StorePath<String>
78#[cfg(feature = "hashbrown")]
79impl hashbrown::Equivalent<StorePath<String>> for StorePathRef<'_> {
80    fn equivalent(&self, key: &StorePath<String>) -> bool {
81        self.digest == key.digest && self.name == key.name
82    }
83}
84
85/// Like [StorePath], but without a heap allocation for the name.
86/// Used by [StorePath] for parsing.
87pub type StorePathRef<'a> = StorePath<&'a str>;
88
89impl<S> StorePath<S>
90where
91    S: AsRef<str>,
92{
93    pub fn digest(&self) -> &[u8; DIGEST_SIZE] {
94        &self.digest
95    }
96
97    pub fn name(&self) -> &S {
98        &self.name
99    }
100
101    pub fn as_ref(&self) -> StorePathRef<'_> {
102        StorePathRef {
103            digest: self.digest,
104            name: self.name.as_ref(),
105        }
106    }
107
108    pub fn to_owned(&self) -> StorePath<String> {
109        StorePath {
110            digest: self.digest,
111            name: self.name.as_ref().to_string(),
112        }
113    }
114
115    /// Construct a [StorePath] by passing the `$digest-$name` string
116    /// that comes after [STORE_DIR_WITH_SLASH].
117    pub fn from_bytes<'a>(s: &'a [u8]) -> Result<Self, Error>
118    where
119        S: From<&'a str>,
120    {
121        // the whole string needs to be at least:
122        //
123        // - 32 characters (encoded hash)
124        // - 1 dash
125        // - 1 character for the name
126        if s.len() < ENCODED_DIGEST_SIZE + 2 {
127            Err(Error::InvalidLength)?
128        }
129
130        let digest = nixbase32::decode_fixed(&s[..ENCODED_DIGEST_SIZE])?;
131
132        if s[ENCODED_DIGEST_SIZE] != b'-' {
133            return Err(Error::MissingDash);
134        }
135
136        Ok(StorePath {
137            digest,
138            name: validate_name(&s[ENCODED_DIGEST_SIZE + 1..])?.into(),
139        })
140    }
141
142    /// Construct a [StorePathRef] from a name and digest.
143    /// The name is validated, and the digest checked for size.
144    pub fn from_name_and_digest<'a>(name: &'a str, digest: &[u8]) -> Result<Self, Error>
145    where
146        S: From<&'a str>,
147    {
148        let digest_fixed = digest.try_into().map_err(|_| Error::InvalidLength)?;
149        Self::from_name_and_digest_fixed(name, digest_fixed)
150    }
151
152    /// Construct a [StorePathRef] from a name and digest of correct length.
153    /// The name is validated.
154    pub fn from_name_and_digest_fixed<'a>(
155        name: &'a str,
156        digest: [u8; DIGEST_SIZE],
157    ) -> Result<Self, Error>
158    where
159        S: From<&'a str>,
160    {
161        Ok(Self {
162            name: validate_name(name)?.into(),
163            digest,
164        })
165    }
166
167    /// Construct a [StorePathRef] from an absolute store path string.
168    /// This is equivalent to calling [StorePathRef::from_bytes], but stripping
169    /// the [STORE_DIR_WITH_SLASH] prefix before.
170    pub fn from_absolute_path<'a>(s: &'a [u8]) -> Result<Self, Error>
171    where
172        S: From<&'a str>,
173    {
174        match s.strip_prefix(STORE_DIR_WITH_SLASH.as_bytes()) {
175            Some(s_stripped) => Self::from_bytes(s_stripped),
176            None => Err(Error::MissingStoreDir),
177        }
178    }
179
180    /// Decompose a string into a [StorePath] and a [std::path::Path] containing
181    /// the rest of the path, or an error.
182    pub fn from_absolute_path_full<'p: 'sp, 'sp, P>(
183        path: &'p P,
184    ) -> Result<(Self, &'p std::path::Path), Error>
185    where
186        S: From<&'sp str>,
187        P: AsRef<std::path::Path> + 'p + ?Sized,
188    {
189        // strip [STORE_DIR_WITH_SLASH] from path
190        let p = path
191            .as_ref()
192            .strip_prefix(STORE_DIR_WITH_SLASH)
193            .map_err(|_| Error::MissingStoreDir)?;
194
195        let mut components = p.components();
196
197        use bstr::ByteSlice;
198        let first_component =
199            <[u8]>::from_os_str(components.next().ok_or(Error::InvalidLength)?.as_os_str())
200                .ok_or(Error::InvalidName)?;
201
202        // The first component must be parse-able as a [StorePath].
203        if first_component.len() < 34 {
204            return Err(Error::InvalidLength);
205        }
206
207        let store_path = StorePath::from_bytes(first_component)?;
208
209        Ok((store_path, components.as_path()))
210    }
211
212    /// Returns an absolute store path string.
213    /// That is just the string representation, prefixed with the store prefix
214    /// ([STORE_DIR_WITH_SLASH]),
215    pub fn to_absolute_path(&self) -> String {
216        format!("{STORE_DIR_WITH_SLASH}{self}")
217    }
218}
219
220impl<S> PartialOrd for StorePath<S>
221where
222    S: AsRef<str>,
223{
224    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
225        Some(self.cmp(other))
226    }
227}
228
229/// `StorePath`s are sorted by their reverse digest to match the sorting order
230/// of the nixbase32-encoded string.
231impl<S> Ord for StorePath<S>
232where
233    S: AsRef<str>,
234{
235    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
236        self.digest.iter().rev().cmp(other.digest.iter().rev())
237    }
238}
239
240impl FromStr for StorePath<String> {
241    type Err = Error;
242
243    /// Construct a [StorePath] by passing the `$digest-$name` string
244    /// that comes after [STORE_DIR_WITH_SLASH].
245    fn from_str(s: &str) -> Result<Self, Self::Err> {
246        StorePath::<String>::from_bytes(s.as_bytes())
247    }
248}
249
250#[cfg(feature = "serde")]
251impl<'a, 'de: 'a, S> Deserialize<'de> for StorePath<S>
252where
253    S: AsRef<str> + From<&'a str>,
254{
255    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
256    where
257        D: serde::Deserializer<'de>,
258    {
259        let string: &'de str = Deserialize::deserialize(deserializer)?;
260        let stripped: Option<&str> = string.strip_prefix(STORE_DIR_WITH_SLASH);
261        let stripped: &str = stripped.ok_or_else(|| {
262            serde::de::Error::invalid_value(
263                serde::de::Unexpected::Str(string),
264                &"store path prefix",
265            )
266        })?;
267        StorePath::from_bytes(stripped.as_bytes()).map_err(|_| {
268            serde::de::Error::invalid_value(serde::de::Unexpected::Str(string), &"StorePath")
269        })
270    }
271}
272
273#[cfg(feature = "serde")]
274impl<S> Serialize for StorePath<S>
275where
276    S: AsRef<str>,
277{
278    fn serialize<SR>(&self, serializer: SR) -> Result<SR::Ok, SR::Error>
279    where
280        SR: serde::Serializer,
281    {
282        let string: String = self.to_absolute_path();
283        string.serialize(serializer)
284    }
285}
286
287/// NAME_CHARS contains `true` for bytes that are valid in store path names.
288static NAME_CHARS: [bool; 256] = {
289    let mut tbl = [false; 256];
290    let mut c = 0;
291
292    loop {
293        tbl[c as usize] = matches!(c, b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'+' | b'-' | b'_' | b'?' | b'=' | b'.');
294
295        if c == u8::MAX {
296            break;
297        }
298
299        c += 1;
300    }
301
302    tbl
303};
304
305/// Checks a given &[u8] to match the restrictions for [StorePath::name], and
306/// returns the name as &str if successful.
307pub fn validate_name(s: &(impl AsRef<[u8]> + ?Sized)) -> Result<&str, Error> {
308    let s = s.as_ref();
309
310    // Empty or excessively long names are not allowed.
311    if s.is_empty() || s.len() > 211 {
312        return Err(Error::InvalidLength);
313    }
314
315    let mut valid = true;
316    for &c in s {
317        valid = valid && NAME_CHARS[c as usize];
318    }
319
320    if !valid {
321        for &c in s.iter() {
322            if !NAME_CHARS[c as usize] {
323                return Err(Error::InvalidName);
324            }
325        }
326
327        unreachable!();
328    }
329
330    // SAFETY: We permit a subset of ASCII, which guarantees valid UTF-8.
331    Ok(unsafe { str::from_utf8_unchecked(s) })
332}
333
334/// Checks a given OsStr to match the restrictions for [StorePath::name], and
335/// returns the name as &str if successful.
336pub fn validate_name_as_os_str(s: &(impl AsRef<std::ffi::OsStr> + ?Sized)) -> Result<&str, Error> {
337    let s = s.as_ref().to_str().ok_or(Error::InvalidName)?;
338
339    validate_name(s)
340}
341
342impl<S> fmt::Display for StorePath<S>
343where
344    S: AsRef<str>,
345{
346    /// The string representation of a store path starts with a digest (20
347    /// bytes), [crate::nixbase32]-encoded, followed by a `-`,
348    /// and ends with the name.
349    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
350        write!(
351            f,
352            "{}-{}",
353            nixbase32::encode(&self.digest),
354            self.name.as_ref()
355        )
356    }
357}
358
359#[cfg(test)]
360mod tests {
361    use super::Error;
362    use std::cmp::Ordering;
363
364    use crate::store_path::{DIGEST_SIZE, StorePath, StorePathRef};
365    use hex_literal::hex;
366    use pretty_assertions::assert_eq;
367    use rstest::rstest;
368    #[cfg(feature = "serde")]
369    use serde::Deserialize;
370
371    /// An example struct, holding a StorePathRef.
372    /// Used to test deserializing StorePathRef.
373    #[cfg(feature = "serde")]
374    #[derive(Deserialize)]
375    struct Container<'a> {
376        #[serde(borrow)]
377        store_path: StorePathRef<'a>,
378    }
379
380    #[test]
381    fn happy_path() {
382        let example_nix_path_str =
383            "00bgd045z0d4icpbc2yyz4gx48ak44la-net-tools-1.60_p20170221182432";
384        let nixpath = StorePathRef::from_bytes(example_nix_path_str.as_bytes())
385            .expect("Error parsing example string");
386
387        let expected_digest: [u8; DIGEST_SIZE] = hex!("8a12321522fd91efbd60ebb2481af88580f61600");
388
389        assert_eq!("net-tools-1.60_p20170221182432", *nixpath.name());
390        assert_eq!(nixpath.digest, expected_digest);
391
392        assert_eq!(example_nix_path_str, nixpath.to_string())
393    }
394
395    #[test]
396    fn store_path_ordering() {
397        let store_paths = [
398            "/nix/store/0lk5dgi01r933abzfj9c9wlndg82yd3g-psutil-5.9.6.tar.gz.drv",
399            "/nix/store/1xj43bva89f9qmwm37zl7r3d7m67i9ck-shorttoc-1.3-tex.drv",
400            "/nix/store/2gb633czchi20jq1kqv70rx2yvvgins8-lifted-base-0.2.3.12.tar.gz.drv",
401            "/nix/store/2vksym3r3zqhp15q3fpvw2mnvffv11b9-docbook-xml-4.5.zip.drv",
402            "/nix/store/5q918awszjcz5720xvpc2czbg1sdqsf0-rust_renaming-0.1.0-lib",
403            "/nix/store/7jw30i342sr2p1fmz5xcfnch65h4zbd9-dbus-1.14.10.tar.xz.drv",
404            "/nix/store/96yqwqhnp3qya4rf4n0rcl0lwvrylp6k-eap8021x-222.40.1.tar.gz.drv",
405            "/nix/store/9gjqg36a1v0axyprbya1hkaylmnffixg-virtualenv-20.24.5.tar.gz.drv",
406            "/nix/store/a4i5mci2g9ada6ff7ks38g11dg6iqyb8-perl-5.32.1.drv",
407            "/nix/store/a5g76ljava4h5pxlggz3aqdhs3a4fk6p-ToolchainInfo.plist.drv",
408            "/nix/store/db46l7d6nswgz4ffp1mmd56vjf9g51v6-version.plist.drv",
409            "/nix/store/g6f7w20sd7vwy0rc1r4bfsw4ciclrm4q-crates-io-num_cpus-1.12.0.drv",
410            "/nix/store/iw82n1wwssb8g6772yddn8c3vafgv9np-bootstrap-stage1-sysctl-stdenv-darwin.drv",
411            "/nix/store/lp78d1y5wxpcn32d5c4r7xgbjwiw0cgf-logo.svg.drv",
412            "/nix/store/mf00ank13scv1f9l1zypqdpaawjhfr3s-python3.11-psutil-5.9.6.drv",
413            "/nix/store/mpfml61ra7pz90124jx9r3av0kvkz2w1-perl5.36.0-Encode-Locale-1.05",
414            "/nix/store/qhsvwx4h87skk7c4mx0xljgiy3z93i23-source.drv",
415            "/nix/store/riv7d73adim8hq7i04pr8kd0jnj93nav-fdk-aac-2.0.2.tar.gz.drv",
416            "/nix/store/s64b9031wga7vmpvgk16xwxjr0z9ln65-human-signals-5.0.0.tgz-extracted",
417            "/nix/store/w6svg3m2xdh6dhx0gl1nwa48g57d3hxh-thiserror-1.0.49",
418        ];
419
420        for w in store_paths.windows(2) {
421            if w.len() < 2 {
422                continue;
423            }
424            let (pa, _) = StorePathRef::from_absolute_path_full(w[0]).expect("parseable");
425            let (pb, _) = StorePathRef::from_absolute_path_full(w[1]).expect("parseable");
426            assert_eq!(
427                Ordering::Less,
428                pa.cmp(&pb),
429                "{:?} not less than {:?}",
430                w[0],
431                w[1]
432            );
433        }
434    }
435
436    /// This is the store path *accepted* when `nix-store --add`'ing an
437    /// empty `.gitignore` file.
438    ///
439    /// Nix 2.4 accidentally permitted this behaviour, but the revert came
440    /// too late to beat Hyrum's law. It is now considered permissible.
441    ///
442    /// https://github.com/NixOS/nix/pull/9095 (revert)
443    /// https://github.com/NixOS/nix/pull/9867 (revert-of-revert)
444    #[test]
445    fn starts_with_dot() {
446        StorePathRef::from_bytes(b"fli4bwscgna7lpm7v5xgnjxrxh0yc7ra-.gitignore")
447            .expect("must succeed");
448    }
449
450    #[test]
451    fn empty_name() {
452        StorePathRef::from_bytes(b"00bgd045z0d4icpbc2yy-").expect_err("must fail");
453    }
454
455    #[test]
456    fn excessive_length() {
457        StorePathRef::from_bytes(b"00bgd045z0d4icpbc2yy-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
458            .expect_err("must fail");
459    }
460
461    #[test]
462    fn invalid_hash_length() {
463        StorePathRef::from_bytes(b"00bgd045z0d4icpbc2yy-net-tools-1.60_p20170221182432")
464            .expect_err("must fail");
465    }
466
467    #[test]
468    fn invalid_encoding_hash() {
469        StorePathRef::from_bytes(
470            b"00bgd045z0d4icpbc2yyz4gx48aku4la-net-tools-1.60_p20170221182432",
471        )
472        .expect_err("must fail");
473    }
474
475    #[test]
476    fn more_than_just_the_bare_nix_store_path() {
477        StorePathRef::from_bytes(
478            b"00bgd045z0d4icpbc2yyz4gx48aku4la-net-tools-1.60_p20170221182432/bin/arp",
479        )
480        .expect_err("must fail");
481    }
482
483    #[test]
484    fn no_dash_between_hash_and_name() {
485        StorePathRef::from_bytes(b"00bgd045z0d4icpbc2yyz4gx48ak44lanet-tools-1.60_p20170221182432")
486            .expect_err("must fail");
487    }
488
489    #[test]
490    fn absolute_path() {
491        let example_nix_path_str =
492            "00bgd045z0d4icpbc2yyz4gx48ak44la-net-tools-1.60_p20170221182432";
493        let nixpath_expected =
494            StorePathRef::from_bytes(example_nix_path_str.as_bytes()).expect("must parse");
495
496        let nixpath_actual = StorePathRef::from_absolute_path(
497            "/nix/store/00bgd045z0d4icpbc2yyz4gx48ak44la-net-tools-1.60_p20170221182432".as_bytes(),
498        )
499        .expect("must parse");
500
501        assert_eq!(nixpath_expected, nixpath_actual);
502
503        assert_eq!(
504            "/nix/store/00bgd045z0d4icpbc2yyz4gx48ak44la-net-tools-1.60_p20170221182432",
505            nixpath_actual.to_absolute_path(),
506        );
507    }
508
509    #[test]
510    fn absolute_path_missing_prefix() {
511        assert_eq!(
512            Error::MissingStoreDir,
513            StorePathRef::from_absolute_path(b"foobar-123").expect_err("must fail")
514        );
515    }
516
517    #[cfg(feature = "serde")]
518    #[test]
519    fn serialize_ref() {
520        let nixpath_actual = StorePathRef::from_bytes(
521            b"00bgd045z0d4icpbc2yyz4gx48ak44la-net-tools-1.60_p20170221182432",
522        )
523        .expect("can parse");
524
525        let serialized = serde_json::to_string(&nixpath_actual).expect("can serialize");
526
527        assert_eq!(
528            "\"/nix/store/00bgd045z0d4icpbc2yyz4gx48ak44la-net-tools-1.60_p20170221182432\"",
529            &serialized
530        );
531    }
532
533    #[cfg(feature = "serde")]
534    #[test]
535    fn serialize_owned() {
536        let nixpath_actual = StorePathRef::from_bytes(
537            b"00bgd045z0d4icpbc2yyz4gx48ak44la-net-tools-1.60_p20170221182432",
538        )
539        .expect("can parse");
540
541        let serialized = serde_json::to_string(&nixpath_actual).expect("can serialize");
542
543        assert_eq!(
544            "\"/nix/store/00bgd045z0d4icpbc2yyz4gx48ak44la-net-tools-1.60_p20170221182432\"",
545            &serialized
546        );
547    }
548
549    #[cfg(feature = "serde")]
550    #[test]
551    fn deserialize_ref() {
552        let store_path_str_json =
553            "\"/nix/store/00bgd045z0d4icpbc2yyz4gx48ak44la-net-tools-1.60_p20170221182432\"";
554
555        let store_path: StorePathRef<'_> =
556            serde_json::from_str(store_path_str_json).expect("valid json");
557
558        assert_eq!(
559            "/nix/store/00bgd045z0d4icpbc2yyz4gx48ak44la-net-tools-1.60_p20170221182432",
560            store_path.to_absolute_path()
561        );
562    }
563
564    #[cfg(feature = "serde")]
565    #[test]
566    fn deserialize_ref_container() {
567        let str_json = "{\"store_path\":\"/nix/store/00bgd045z0d4icpbc2yyz4gx48ak44la-net-tools-1.60_p20170221182432\"}";
568
569        let container: Container<'_> = serde_json::from_str(str_json).expect("must deserialize");
570
571        assert_eq!(
572            "/nix/store/00bgd045z0d4icpbc2yyz4gx48ak44la-net-tools-1.60_p20170221182432",
573            container.store_path.to_absolute_path()
574        );
575    }
576
577    #[cfg(feature = "serde")]
578    #[test]
579    fn deserialize_owned() {
580        let store_path_str_json =
581            "\"/nix/store/00bgd045z0d4icpbc2yyz4gx48ak44la-net-tools-1.60_p20170221182432\"";
582
583        let store_path: StorePath<String> =
584            serde_json::from_str(store_path_str_json).expect("valid json");
585
586        assert_eq!(
587            "/nix/store/00bgd045z0d4icpbc2yyz4gx48ak44la-net-tools-1.60_p20170221182432",
588            store_path.to_absolute_path()
589        );
590    }
591
592    #[rstest]
593    #[case::without_prefix(
594        "/nix/store/00bgd045z0d4icpbc2yyz4gx48ak44la-net-tools-1.60_p20170221182432",
595        StorePath::from_bytes(b"00bgd045z0d4icpbc2yyz4gx48ak44la-net-tools-1.60_p20170221182432").unwrap(), "")]
596    #[case::without_prefix_but_trailing_slash(
597        "/nix/store/00bgd045z0d4icpbc2yyz4gx48ak44la-net-tools-1.60_p20170221182432/",
598        StorePath::from_bytes(b"00bgd045z0d4icpbc2yyz4gx48ak44la-net-tools-1.60_p20170221182432").unwrap(), "")]
599    #[case::with_prefix(
600        "/nix/store/00bgd045z0d4icpbc2yyz4gx48ak44la-net-tools-1.60_p20170221182432/bin/arp",
601        StorePath::from_bytes(b"00bgd045z0d4icpbc2yyz4gx48ak44la-net-tools-1.60_p20170221182432").unwrap(), "bin/arp")]
602    #[case::with_prefix_and_trailing_slash(
603        "/nix/store/00bgd045z0d4icpbc2yyz4gx48ak44la-net-tools-1.60_p20170221182432/bin/arp/",
604        StorePath::from_bytes(b"00bgd045z0d4icpbc2yyz4gx48ak44la-net-tools-1.60_p20170221182432").unwrap(), "bin/arp/")]
605    fn from_absolute_path_full(
606        #[case] s: &str,
607        #[case] exp_store_path: StorePath<&str>,
608        #[case] exp_rest_str: &str,
609    ) {
610        let (actual_store_path, actual_rest) =
611            StorePath::from_absolute_path_full(s).expect("must succeed");
612
613        assert_eq!(exp_store_path, actual_store_path);
614        assert_eq!(exp_rest_str, actual_rest);
615    }
616
617    #[test]
618    fn from_absolute_path_errors() {
619        assert_eq!(
620            Error::InvalidLength,
621            StorePathRef::from_absolute_path_full("/nix/store/").expect_err("must fail")
622        );
623        assert_eq!(
624            Error::InvalidLength,
625            StorePathRef::from_absolute_path_full("/nix/store/foo").expect_err("must fail")
626        );
627        assert_eq!(
628            Error::MissingStoreDir,
629            StorePathRef::from_absolute_path_full(
630                "00bgd045z0d4icpbc2yyz4gx48ak44la-net-tools-1.60_p20170221182432"
631            )
632            .expect_err("must fail")
633        );
634    }
635}