From 8c07486ef571cfa9d139bc394adf3bb8d916c8b4 Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Tue, 24 Nov 2026 14:31:53 +0100 Subject: [PATCH 1/2] uapi16: rename the Decoder's step() and end() We're going to add operations that are done in steps. They are driven with process() and closed with end(). Make the naming of the Decoder consistent with that before we publish it: - Decoder::step() -> Decoder::process() - Decoder::end() -> Decoder::end_feed() The Decoder's end() doesn't close anything. It only says that the input ended. So it becomes end_feed() which pairs with feed(). process() still returns a Step. No functional changes. Signed-off-by: Christian Brauner (Amutable) --- src/uapi16/blocking.rs | 4 ++-- src/uapi16/lib.rs | 8 ++++---- src/uapi16/reader.rs | 43 +++++++++++++++++++++--------------------- 3 files changed, 28 insertions(+), 27 deletions(-) diff --git a/src/uapi16/blocking.rs b/src/uapi16/blocking.rs index b7c4418..104c1d5 100644 --- a/src/uapi16/blocking.rs +++ b/src/uapi16/blocking.rs @@ -139,7 +139,7 @@ impl Reader { /// Feeds the decoder until it takes a step other than [`Step::Input`]. fn pull(&mut self) -> Result { loop { - match self.decoder.step()? { + match self.decoder.process()? { Step::Input => self.fill()?, step => return Ok(step), } @@ -158,7 +158,7 @@ impl Reader { }; let input = input.map_err(|e| self.decoder.input_error(e))?; if input.is_empty() { - self.decoder.end(); + self.decoder.end_feed(); } else { let taken = self.decoder.feed(input); self.input.consume(taken); diff --git a/src/uapi16/lib.rs b/src/uapi16/lib.rs index f86d0cc..3ac43b6 100644 --- a/src/uapi16/lib.rs +++ b/src/uapi16/lib.rs @@ -41,12 +41,12 @@ //! against the manifest with a [`DataCheck`]. //! //! A manifest that does not come through a [`Read`], such as one from an -//! async runtime, goes to a [`Decoder`] as it comes. [`Decoder::step`] says -//! what comes next. When it asks for more of the manifest with +//! async runtime, goes to a [`Decoder`] as it comes. [`Decoder::process`] +//! says what comes next. When it asks for more of the manifest with //! [`Step::Input`], [`Decoder::feed`] takes the bytes that came, up to the //! end of the record it reads, and returns how many it took. The others go -//! in with a later call. [`Decoder::end`] says that there are no more. The -//! other steps hand out the root file object, the objects after it, and +//! in with a later call. [`Decoder::end_feed`] says that there are no more. +//! The other steps hand out the root file object, the objects after it, and //! the end of the manifest. A record ends where the next one starts, so an //! object comes once the separator of the record after it was fed, or the //! input ended, and the end of the manifest once the input ended. A step diff --git a/src/uapi16/reader.rs b/src/uapi16/reader.rs index d2b91a3..883d027 100644 --- a/src/uapi16/reader.rs +++ b/src/uapi16/reader.rs @@ -253,36 +253,37 @@ enum Stage { /// [`Step::Input`] asks for more of the manifest, [`Step::End`] says that /// there is nothing more, and the other steps hand something out. A step /// the caller does not know needs nothing from it but another call to -/// [`Decoder::step`], so the caller can pass over it. Steps that come in +/// [`Decoder::process`], so the caller can pass over it. Steps that come in /// later releases only hand something out. #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum Step { /// More of the manifest: [`Decoder::feed`] takes it, and - /// [`Decoder::end`] says that the input ended. + /// [`Decoder::end_feed`] says that the input ended. Input, /// The root file object. It comes first, once. Root(Box), /// A file object or a signature object. Object(Object), /// The end of the manifest, after its trailer object. Once - /// [`Decoder::step`] returned an error, it returns this as well. + /// [`Decoder::process`] returned an error, it returns this as well. End, } /// Reads a manifest from the bytes it is fed, and does no I/O itself. /// -/// [`Decoder::step`] says what comes next. [`Step::Input`] asks for more +/// [`Decoder::process`] says what comes next. [`Step::Input`] asks for more /// of the manifest: [`Decoder::feed`] takes the bytes that come next, and -/// [`Decoder::end`] says that there are no more. [`Step::Root`] is the root -/// file object, [`Step::Object`] each object after it, and [`Step::End`] -/// the end of the manifest. +/// [`Decoder::end_feed`] says that there are no more. [`Step::Root`] is the +/// root file object, [`Step::Object`] each object after it, and +/// [`Step::End`] the end of the manifest. /// /// A record ends where the next one starts, so an object comes once the -/// separator of the record after it was fed, or [`Decoder::end`] was +/// separator of the record after it was fed, or [`Decoder::end_feed`] was /// called. Nothing may follow the trailer object, so [`Step::End`] comes -/// only after [`Decoder::end`]. [`Decoder::step`] reads a whole record, of -/// up to [`MAX_RECORD_SIZE`] bytes with its record separator, in one call. +/// only after [`Decoder::end_feed`]. [`Decoder::process`] reads a whole +/// record, of up to [`MAX_RECORD_SIZE`] bytes with its record separator, in +/// one call. /// /// A decoder checks and fills in what a [`Reader`] does, which is a /// decoder fed from a [`Read`]. It takes the bytes of one record at a time, @@ -304,8 +305,8 @@ pub enum Step { /// let mut decoder = Decoder::new(); /// let mut names = Vec::new(); /// loop { -/// match decoder.step()? { -/// Step::Input if input.is_empty() => decoder.end(), +/// match decoder.process()? { +/// Step::Input if input.is_empty() => decoder.end_feed(), /// // The manifest comes in pieces of at most five bytes. /// Step::Input => { /// let taken = decoder.feed(&input[..input.len().min(5)]); @@ -364,14 +365,14 @@ impl Decoder { /// Says that the input ended, after [`Step::Input`]. #[inline] - pub fn end(&mut self) { + pub fn end_feed(&mut self) { self.splitter.end_input(); } /// What comes next. Once it returned an error, it returns /// [`Step::End`]. #[inline] - pub fn step(&mut self) -> Result { + pub fn process(&mut self) -> Result { if !matches!(self.stage, Stage::Done) { // The next record goes on in input that was not fed yet, as it // does right after every object that was handed out. @@ -1002,11 +1003,11 @@ mod tests { let mut whole = None; let mut numbers = Vec::new(); loop { - match decoder.step()? { + match decoder.process()? { Step::Input => { if piece.is_empty() { let Some(next) = pieces.next() else { - decoder.end(); + decoder.end_feed(); continue; }; piece = next; @@ -1107,8 +1108,8 @@ mod tests { let mut decoder = Decoder::new(); let mut taken = 0; loop { - match decoder.step().unwrap() { - Step::Input if taken == bytes.len() => decoder.end(), + match decoder.process().unwrap() { + Step::Input if taken == bytes.len() => decoder.end_feed(), Step::Input => taken += decoder.feed(&bytes[taken..][..size.min(bytes.len() - taken)]), Step::Object(_) => assert_eq!(decoder.splitter.record.len(), MAX_RECORD_TEXT), Step::Root(_) => {} @@ -1195,8 +1196,8 @@ mod tests { let mut decoder = Decoder::new(); let mut taken = 0; let e = loop { - match decoder.step() { - Ok(Step::Input) if taken == bytes.len() => decoder.end(), + match decoder.process() { + Ok(Step::Input) if taken == bytes.len() => decoder.end_feed(), Ok(Step::Input) => taken += decoder.feed(&bytes[taken..][..size.min(bytes.len() - taken)]), Ok(Step::Root(_)) => {} Ok(step) => panic!("{} at a time: {:?}", size, step), @@ -1214,7 +1215,7 @@ mod tests { // no more than the largest record, and does not print it. assert_eq!(taken, start.len() + READ_LIMIT, "{} at a time", size); assert_eq!(decoder.feed(&bytes[taken..]), 0); - assert_eq!(decoder.step().unwrap(), Step::End); + assert_eq!(decoder.process().unwrap(), Step::End); assert!( decoder.splitter.record.capacity() <= MAX_RECORD_TEXT, "{} at a time", From 6f128389e8e2f1de8c320448d6c32d0bd952a1fe Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Tue, 24 Nov 2026 15:04:58 +0100 Subject: [PATCH 2/2] uapi16: split Name into Name and NameBuf Currently, a Name owns its string and Name::ROOT is a constant of that type. A constant of a type that has something to drop isn't promoted to a static. So &Name::ROOT is a reference to a temporary that is dropped at the end of its statement. Whatever keeps a borrowed name for longer than that fails to compile with E0716, "temporary value dropped while borrowed", unless the caller puts the root into a variable of its own first. The operations in steps that we're going to add borrow the name they are given for as long as they run. So they would hit this right away. We haven't published anything yet so let's do the correct thing and do what std does for String and str, PathBuf and Path, CString and CStr. Add an unsized type for a borrowed name next to the type that owns one, let the functions take the borrowed form and make the root a &'static of it. Name becomes the borrowed type and NameBuf is the owned one, as Path and PathBuf are, since a name is a path. The borrowed type is the one nearly every function takes. This way their signatures, Name::ROOT and Name::MAX_LEN keep their spelling. What changes for callers: - A function that reads a name takes a &Name as before. A &NameBuf is a &Name wherever one is taken. - A function that keeps a name takes a NameBuf. These are FileObject::new(), FileObject::from_metadata() and FileObject::set_name(). ContentsSource::File holds one, and FileObject::into_name() and Name::join() return one. - Name::new() checks a &str where it is and returns a &Name without a copy. It fails with a NameProblem as before. - NameBuf::new() makes an owned name. If the string isn't a name it fails with the new NameError, which says why and hands the string back as NulError and FromUtf8Error do. FromStr and TryFrom for NameBuf fail with it as well. - Name::parent() returns an Option<&Name> as Path::parent() does. The name of the directory a file is in is the first part of its own name so nothing is copied. - Name::ROOT is a &'static Name and the default of a &Name. An owned root is NameBuf::default(). - Both forms are equal, ordered and hashed the same. So a map with NameBuf keys is looked up with a &Name. They compare with each other as PathBuf and Path do, and == takes a str with either one on the left. There is no order against a str as names aren't in the order of their strings. Both still print as Name("a/b") with Debug. While at it, drop the crate's own Name::parent_str(). It gave the one caller that didn't want a copy the parent as a string and parent() does that now. Also make Display pad and truncate a name as it does a str. Rust has no safe way to turn a &str into a reference to an unsized type around a str. It takes a pointer cast and std has the same one for Path. The cast is in the private Name::from_str_unchecked() and that is the only function that is allowed to have unsafe code. The crate keeps deny(unsafe_code). Note that the cast is sound for any string so the checks of a name are no part of its safety. Signed-off-by: Christian Brauner (Amutable) --- src/uapi16/blocking.rs | 4 +- src/uapi16/content.rs | 7 +- src/uapi16/decode.rs | 31 +- src/uapi16/directory.rs | 8 +- src/uapi16/lib.rs | 14 +- src/uapi16/metadata.rs | 6 +- src/uapi16/name.rs | 712 ++++++++++++++++++++++++++++++++++++---- src/uapi16/object.rs | 44 +-- src/uapi16/sequence.rs | 6 +- src/uapi16/writer.rs | 26 +- 10 files changed, 716 insertions(+), 142 deletions(-) diff --git a/src/uapi16/blocking.rs b/src/uapi16/blocking.rs index 104c1d5..fc849d4 100644 --- a/src/uapi16/blocking.rs +++ b/src/uapi16/blocking.rs @@ -242,11 +242,11 @@ impl FusedIterator for Reader {} /// text where it can. The writer refuses such a record. /// /// ``` -/// use uapi16::{FileObject, Name, Object, Order, Reader, RootObject, Writer}; +/// use uapi16::{FileObject, NameBuf, Object, Order, Reader, RootObject, Writer}; /// /// let mut root = RootObject::default(); /// root.set_order(Some(Order::CodePoint)); -/// let mut file = FileObject::new(Name::new("a")?); +/// let mut file = FileObject::new(NameBuf::new("a")?); /// file.set_size(Some(3)); /// let mut writer = Writer::begin(Vec::new(), &root)?; /// writer.file(&file)?; diff --git a/src/uapi16/content.rs b/src/uapi16/content.rs index 5cf937f..2115f43 100644 --- a/src/uapi16/content.rs +++ b/src/uapi16/content.rs @@ -375,9 +375,9 @@ impl ContentsObject { /// and calls [`DataCheck::finish`] after the last one. /// /// ``` -/// use uapi16::{DataCheck, FileObject, Name, Sha256}; +/// use uapi16::{DataCheck, FileObject, NameBuf, Sha256}; /// -/// let mut object = FileObject::new(Name::new("hello.txt")?); +/// let mut object = FileObject::new(NameBuf::new("hello.txt")?); /// object.set_size(Some(5)); /// object.set_sha256(Some(Sha256::digest(b"hello"))); /// let mut check = DataCheck::new(&object); @@ -1190,6 +1190,7 @@ mod tests { use super::*; use crate::error::Problem; use crate::testing::{json, manifest, read_whole, sequence, HELLO, TRAILER, WORLD}; + use crate::NameBuf; use std::cell::{Cell, RefCell}; use std::rc::Rc; @@ -2451,7 +2452,7 @@ mod tests { assert_eq!(check(&sized, b"hello").unwrap(), b"hello"); assert_eq!(check(&sized, b"world").unwrap_err().kind(), hash); // An object that is all of its file without a hash of its own. - let mut whole = FileObject::new(Name::new("x").unwrap()); + let mut whole = FileObject::new(NameBuf::new("x").unwrap()); whole.size = Some(5); let mut contents = ContentsObject::new(ContentsSource::Implied); contents.original_size = Some(5); diff --git a/src/uapi16/decode.rs b/src/uapi16/decode.rs index cdfd476..6a10060 100644 --- a/src/uapi16/decode.rs +++ b/src/uapi16/decode.rs @@ -28,7 +28,8 @@ use crate::object::{ }; use crate::strict::{FieldTable, Key, Members, Skip, Strict}; use crate::{ - Features, Name, Order, Sha256, MAX_CONTENTS, MEDIA_TYPE, SIGNATURE_MEDIA_TYPE, TRAILER_MEDIA_TYPE, USER_NAMESPACE, + Features, Name, NameBuf, Order, Sha256, MAX_CONTENTS, MEDIA_TYPE, SIGNATURE_MEDIA_TYPE, TRAILER_MEDIA_TYPE, + USER_NAMESPACE, }; /// The user and group ID that is -1 as an unsigned 32-bit integer, @@ -260,7 +261,7 @@ impl Field { /// draft and every other record a [`FileObject`]. struct Draft { object: Box, - name: Option, + name: Option, /// The name as the record has it, when it is not a valid one. invalid_name: Option, inode_type: Option, @@ -281,7 +282,7 @@ impl Draft { /// The draft of a record no member of which was read yet. fn new() -> Draft { Draft { - object: Box::new(FileObject::new(Name::ROOT)), + object: Box::new(FileObject::new(NameBuf::default())), name: None, invalid_name: None, inode_type: None, @@ -298,7 +299,7 @@ impl Draft { if !self.object.name.is_root() { return Some(self.object.name.as_str()); } - self.name.as_ref().map(Name::as_str).or(self.invalid_name.as_deref()) + self.name.as_deref().map(Name::as_str).or(self.invalid_name.as_deref()) } /// The fields of a partition, which are made when the first of them is @@ -1488,7 +1489,7 @@ impl<'a> RecordDecoder<'a> { Field::Name => { if let Some(name) = self.string(field, value) { match Name::new(name.as_ref()) { - Ok(name) => draft.name = Some(name), + Ok(name) => draft.name = Some(name.to_owned()), Err(reason) => { let subject = self.subject(); self.note_error(Problem::InvalidName, field, || { @@ -1872,7 +1873,7 @@ impl<'a> Part<'a> for ContentsElement { let name = Name::new(file.as_ref()) .map_err(|reason| Error::invalid_file_reference(subject, reason, &file)); if let Some(name) = decoder.note_err(name) { - contents.source = ContentsSource::File(name); + contents.source = ContentsSource::File(name.to_owned()); places += 1; } } @@ -2272,7 +2273,7 @@ mod tests { fn what_a_field_can_look_like() { // An object says as little as its name. let o = object(r#"{"name":"x"}"#); - assert_eq!(o, FileObject::new(Name::new("x").unwrap())); + assert_eq!(o, FileObject::new(NameBuf::new("x").unwrap())); // A field that is null is not there. Fields this crate does not // know are passed over, whatever they hold. let nulls = concat!( @@ -2505,7 +2506,7 @@ mod tests { object.check_consistency(subject, contents_data.into_iter()) }; let file = |size: Option, contents: ContentsObject| { - let mut object = FileObject::new(Name::new("x").unwrap()); + let mut object = FileObject::new(NameBuf::new("x").unwrap()); object.size = size; object.contents = vec![contents]; object @@ -2520,7 +2521,7 @@ mod tests { ); let mut beyond = hello(); beyond.offset = 7; - let mut headers = ContentsObject::new(ContentsSource::File(Name::new("a").unwrap())); + let mut headers = ContentsObject::new(ContentsSource::File(NameBuf::new("a").unwrap())); headers.http_headers = vec![("A".to_string(), "b".to_string())]; let mut empty = file(Some(3), hello()); empty.contents.clear(); @@ -2560,7 +2561,7 @@ mod tests { #[test] fn set_contents_with_an_offset_beyond_the_data() { let file = |offset: u64, original_size: u64| { - let mut contents = ContentsObject::new(ContentsSource::File(Name::new("a").unwrap())); + let mut contents = ContentsObject::new(ContentsSource::File(NameBuf::new("a").unwrap())); contents.set_offset(offset); contents.set_original_size(Some(original_size)); contents @@ -2573,7 +2574,7 @@ mod tests { encoded.set_encoding(Some("gzip".to_string())); encoded.set_original_size(Some(3)); encoded.set_offset(4); - let whole = ContentsObject::new(ContentsSource::File(Name::new("a").unwrap())); + let whole = ContentsObject::new(ContentsSource::File(NameBuf::new("a").unwrap())); for (size, contents) in [ (None, vec![file(6, 5)]), (Some(1), vec![file(6, 5)]), @@ -2582,7 +2583,7 @@ mod tests { (None, vec![whole, file(5, 4)]), (None, vec![file(u64::MAX, 0)]), ] { - let mut object = FileObject::new(Name::new("x").unwrap()); + let mut object = FileObject::new(NameBuf::new("x").unwrap()); object.set_size(size); object.set_contents(contents); assert_eq!(object.size(), size, "{:?}", object); @@ -2948,9 +2949,9 @@ mod tests { let hello: Option = HELLO.parse().ok(); let world: Option = WORLD.parse().ok(); let literal = || ContentsObject::new(ContentsSource::Literal(b"hello".to_vec())); - let file = || ContentsObject::new(ContentsSource::File(Name::new("a").unwrap())); + let file = || ContentsObject::new(ContentsSource::File(NameBuf::new("a").unwrap())); let set = |size: Option, sha256: Option, contents: Vec| { - let mut object = FileObject::new(Name::new("x").unwrap()); + let mut object = FileObject::new(NameBuf::new("x").unwrap()); object.set_size(size); object.set_sha256(sha256); object.set_contents(contents); @@ -3136,7 +3137,7 @@ mod tests { r#"{"name":"x","contents":[{"file":"","originalSize":5}]}"#, ContentsObject { original_size: Some(5), - ..ContentsObject::new(ContentsSource::File(Name::ROOT)) + ..ContentsObject::new(ContentsSource::File(NameBuf::default())) }, Field::File, ), diff --git a/src/uapi16/directory.rs b/src/uapi16/directory.rs index f6de553..c18addb 100644 --- a/src/uapi16/directory.rs +++ b/src/uapi16/directory.rs @@ -204,7 +204,7 @@ mod tests { /// What `dir` has under `name`: the text of a regular file, or why it /// has none. fn text(dir: &PinnedDirectory, name: &str) -> Result { - let (mut file, len) = dir.open(&Name::new(name).unwrap()).map_err(Opened::from)?; + let (mut file, len) = dir.open(Name::new(name).unwrap()).map_err(Opened::from)?; let mut text = String::new(); file.read_to_string(&mut text).unwrap(); assert_eq!(text.len() as u64, len, "{}", name); @@ -250,7 +250,7 @@ mod tests { // itself, which the root file object names. assert_eq!(text(&plain, "sub"), Err(Opened::NotRegular)); assert_eq!( - plain.open(&Name::ROOT).map(|_| ()).map_err(Opened::from), + plain.open(Name::ROOT).map(|_| ()).map_err(Opened::from), Err(Opened::NotRegular) ); assert_eq!(text(&plain, "missing"), Err(Opened::Errno(libc::ENOENT))); @@ -303,7 +303,7 @@ mod tests { }; for state in [EmptyPath::UNKNOWN, EmptyPath::MISSING] { EMPTYPATH.store(state, Ordering::Relaxed); - let (handle, _) = directory.pin(&Name::new("file").unwrap()).unwrap(); + let (handle, _) = directory.pin(Name::new("file").unwrap()).unwrap(); fs::rename(dir.join("file"), dir.join("moved")).unwrap(); fs::write(dir.join("file"), b"impostor").unwrap(); assert_eq!(read(&mut PinnedDirectory::reopen(&handle).unwrap()), "pinned"); @@ -340,7 +340,7 @@ mod tests { assert_eq!(text(&directory, "fifo"), Err(Opened::NotRegular)); assert_eq!(text(&directory, "file").as_deref(), Ok("data")); // The file is the one that was pinned, open for reading only. - let (file, len) = directory.open(&Name::new("file").unwrap()).unwrap(); + let (file, len) = directory.open(Name::new("file").unwrap()).unwrap(); assert_eq!(len, 4); let flags = rustix::fs::fcntl_getfl(&file).unwrap(); assert_eq!(flags & OFlags::RWMODE, OFlags::RDONLY); diff --git a/src/uapi16/lib.rs b/src/uapi16/lib.rs index 3ac43b6..df8978e 100644 --- a/src/uapi16/lib.rs +++ b/src/uapi16/lib.rs @@ -137,7 +137,7 @@ pub use digest::{InvalidDigest, Sha256, Sha256Context}; pub use directory::PinnedDirectory; pub use error::{DataProblem, Error, ErrorKind, Field, Problem, SourceProblem, UnsupportedData, ValidityProblem}; pub use features::{Features, Order, UnknownFeature}; -pub use name::{Name, NameProblem}; +pub use name::{Name, NameBuf, NameError, NameProblem}; pub use object::{ ContentsObject, ContentsSource, FatSerial, FileObject, FileSystemIdentity, FilledIn, GptPartition, InodeAttributes, InodeType, InvalidFatSerial, InvalidMode, InvalidUuid, Mode, RootObject, SignatureObject, UnknownInodeType, Uuid, @@ -183,7 +183,7 @@ pub(crate) mod testing { use super::blocking::READ_SIZE; use super::object::{DosFlags, InodeFlags}; use super::{ - ContentsObject, ContentsSource, Error, Features, FileObject, GptPartition, InodeType, Mode, Name, Object, + ContentsObject, ContentsSource, Error, Features, FileObject, GptPartition, InodeType, Mode, NameBuf, Object, Reader, RootObject, Sha256, SignatureObject, Uuid, Validity, Writer, RECORD_END, RECORD_SEPARATOR, }; use crate::strict::{ParseError, Skip, Strict}; @@ -302,9 +302,9 @@ pub(crate) mod testing { /// The names of the full tree in which every directory has an entry /// for each of `pieces`, down to `depth` components: every name of at /// most `depth` components made of `pieces`, the root among them. - pub(crate) fn full_tree_names(pieces: &[&str], depth: usize) -> Vec { - let mut names = vec![Name::ROOT]; - let mut level = vec![Name::ROOT]; + pub(crate) fn full_tree_names(pieces: &[&str], depth: usize) -> Vec { + let mut names = vec![NameBuf::default()]; + let mut level = vec![NameBuf::default()]; for _ in 0..depth { level = level .iter() @@ -327,8 +327,8 @@ pub(crate) mod testing { writer.finish() } - pub(crate) fn name(name: &str) -> Name { - Name::new(name).unwrap() + pub(crate) fn name(name: &str) -> NameBuf { + NameBuf::new(name).unwrap() } /// The records `writer` wrote after `root`, without the frame of diff --git a/src/uapi16/metadata.rs b/src/uapi16/metadata.rs index 24c2135..37461f9 100644 --- a/src/uapi16/metadata.rs +++ b/src/uapi16/metadata.rs @@ -5,7 +5,7 @@ use std::fs::Metadata; use std::os::unix::fs::MetadataExt; use crate::object::{FileObject, InodeType, Mode, UnknownInodeType}; -use crate::{Features, Name}; +use crate::{Features, NameBuf}; impl FileObject { /// A file object for the file `name`, whose metadata is `meta`, with @@ -27,7 +27,7 @@ impl FileObject { /// It fails for a file whose type is not an inode type. /// /// [`RootObject::recorded_features`]: crate::RootObject::recorded_features - pub fn from_metadata(name: Name, meta: &Metadata, features: Features) -> Result { + pub fn from_metadata(name: NameBuf, meta: &Metadata, features: Features) -> Result { let mut object = FileObject::new(name); object.inode_type = InodeType::try_from(meta.file_type())?; let inode = &mut object.inode; @@ -98,7 +98,7 @@ mod tests { let mut writer = Writer::begin(Vec::new(), &root).unwrap(); for (name, path, inode_type) in &files { let meta = fs::symlink_metadata(path).unwrap(); - let mut object = FileObject::from_metadata(Name::new(*name).unwrap(), &meta, features).unwrap(); + let mut object = FileObject::from_metadata(NameBuf::new(*name).unwrap(), &meta, features).unwrap(); assert_eq!(object.inode_type(), *inode_type, "{}", name); let has = |feature: Features| features.contains(feature); let mut inode = InodeAttributes { diff --git a/src/uapi16/name.rs b/src/uapi16/name.rs index 74a93f5..2aa26da 100644 --- a/src/uapi16/name.rs +++ b/src/uapi16/name.rs @@ -1,9 +1,16 @@ // SPDX-License-Identifier: LGPL-2.1-or-later -//! The names of file objects. +//! The names of file objects: [`Name`] borrows one, and [`NameBuf`] owns +//! one. +//! +//! The crate denies unsafe code, with one exception that is here: the cast +//! that makes a `&Name` of a `&str`, in `Name::from_str_unchecked()`. +use std::borrow::Borrow; use std::cmp::Ordering; use std::fmt; +use std::hash::{Hash, Hasher}; use std::iter; +use std::ops::Deref; use std::str::FromStr; use crate::strict::StringRules; @@ -34,6 +41,10 @@ const RULES: StringRules = STRING_RULES.without(StringRules::NO_NUL); /// The name of a file object: the path of the file below the root of the /// tree the manifest describes. /// +/// A `Name` is used behind a reference, like a `str` or a `Path`: a `&Name` +/// borrows a name, and a [`NameBuf`] owns one. [`Name::new`] checks a +/// string where it is, and [`NameBuf::new`] makes an owned name. +/// /// A name is a normalized relative path. Its components are separated by /// single slashes, and none of them is empty, `.` or `..`. It has no /// control characters and no noncharacters, and it is at most @@ -50,20 +61,42 @@ const RULES: StringRules = STRING_RULES.without(StringRules::NO_NUL); /// /// The root file object has no name. Its name here is the empty one, /// [`Name::ROOT`], which no file has, and which comes before every other -/// name. +/// name. It is the default of a `&Name` and of a [`NameBuf`], so an owned +/// root is `NameBuf::default()`. /// /// ``` -/// use uapi16::{Name, NameProblem}; +/// use uapi16::{Name, NameBuf, NameProblem}; /// /// let name = Name::new("EFI/BOOT")?; -/// assert_eq!(name.join("BOOTX64.EFI")?, "EFI/BOOT/BOOTX64.EFI"); -/// assert_eq!("EFI//BOOT".parse::(), Err(NameProblem::EmptyComponent)); +/// let file: NameBuf = name.join("BOOTX64.EFI")?; +/// assert_eq!(file, "EFI/BOOT/BOOTX64.EFI"); +/// assert_eq!(file.parent(), Some(name)); +/// assert_eq!(Name::new("EFI//BOOT"), Err(NameProblem::EmptyComponent)); /// assert_eq!(Name::new("../etc/passwd"), Err(NameProblem::ContainsDotComponent)); /// assert!(Name::new("a/x")? < Name::new("a-b")?); /// # Ok::<(), NameProblem>(()) /// ``` -#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] -pub struct Name(String); +#[derive(PartialEq, Eq, Hash)] +#[repr(transparent)] +pub struct Name(str); + +/// The name of a file object, owned. It is a [`Name`] wherever one is +/// borrowed, and has its methods. +/// +/// ``` +/// use uapi16::{FileObject, Name, NameBuf}; +/// +/// let owned = NameBuf::new("EFI/BOOT/BOOTX64.EFI")?; +/// assert_eq!(owned.file_name(), Some("BOOTX64.EFI")); +/// let name: &Name = &owned; +/// assert_eq!(name.to_owned(), owned); +/// // A file object keeps the name it is given, and lends it. +/// let object = FileObject::new(owned); +/// assert_eq!(object.name(), "EFI/BOOT/BOOTX64.EFI"); +/// # Ok::<(), uapi16::NameError>(()) +/// ``` +#[derive(Clone, Default, PartialEq, Eq)] +pub struct NameBuf(String); /// Why a string is not the name of a file object, see [`Name`]. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] @@ -110,44 +143,103 @@ impl fmt::Display for NameProblem { impl std::error::Error for NameProblem {} +/// A string that is not the name of a file object. It is the error of +/// [`NameBuf::new`] and of the conversions of a string into a [`NameBuf`]. +/// It says why the string is not a name, and hands the string back. +/// +/// ``` +/// use uapi16::{NameBuf, NameProblem}; +/// +/// let error = NameBuf::new(String::from("EFI//BOOT")).unwrap_err(); +/// assert_eq!(error.name_problem(), NameProblem::EmptyComponent); +/// assert_eq!(error.to_string(), "name has an empty component"); +/// assert_eq!(error.into_string(), "EFI//BOOT"); +/// ``` +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct NameError { + /// The string that is not a name. + name: String, + /// Why it is not one. + problem: NameProblem, +} + +impl NameError { + /// Why the string is not a name. + pub fn name_problem(&self) -> NameProblem { + self.problem + } + + /// The string that is not a name. + pub fn as_str(&self) -> &str { + &self.name + } + + /// The string that is not a name, handed back without a copy. + pub fn into_string(self) -> String { + self.name + } +} + +impl fmt::Display for NameError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(&self.problem, f) + } +} + +impl std::error::Error for NameError {} + impl Name { /// The name of the root file object: the empty one. - pub const ROOT: Name = Name(String::new()); + pub const ROOT: &'static Name = Name::from_str_unchecked(""); /// The most bytes a name has, as the specification says. pub const MAX_LEN: usize = 4095; - /// Takes `name` as the name of a file object, if it is one. If it is - /// not, the error says why. - pub fn new(name: impl Into) -> Result { - let name = name.into(); + /// Takes `name` as the name of a file object, if it is one, without a + /// copy. If it is not, the error says why. + pub fn new(name: &str) -> Result<&Name, NameProblem> { if name.is_empty() { return Err(NameProblem::Empty); } if name.len() > Name::MAX_LEN { return Err(NameProblem::TooLong); } - if Name::is_reserved(&name) { + if Name::is_reserved(name) { return Err(NameProblem::Reserved); } // The separator is neither a control character nor a noncharacter, // so the text of the components is checked all at once. - Name::check_text(&name)?; + Name::check_text(name)?; for component in name.as_bytes().split(|&b| b == SEPARATOR_BYTE) { Name::check_component(component)?; } - Ok(Name(name)) + Ok(Name::from_str_unchecked(name)) + } + + /// The string `name` as a name. Nothing is checked: the caller knows + /// that it is a name, or the empty string of the root. + #[allow(unsafe_code)] + const fn from_str_unchecked(name: &str) -> &Name { + // SAFETY: `Name` is `#[repr(transparent)]` over `str`, so the two + // have the same layout, and a pointer to either carries the same + // length. The pointer comes from a reference, so it is valid for + // reads for as long as that reference is. The reference made of it + // is shared as well, and has the lifetime of the argument by the + // signature of this function. No unsafe code relies on a `Name` + // being a valid name, so a string that is none makes a wrong name + // and nothing worse. + unsafe { &*(name as *const str as *const Name) } } /// The name of the entry `component` of the directory this name is /// the name of. Only the new component is looked at, so the names of /// a deep tree are cheap to make on the way down. - pub fn join(&self, component: &str) -> Result { + pub fn join(&self, component: &str) -> Result { if component.contains(SEPARATOR) { return Err(NameProblem::ContainsSeparator); } if self.is_root() { - return Name::new(component); + return Name::new(component).map(Name::to_owned); } let len = self.0.len() + SEPARATOR.len_utf8() + component.len(); if len > Name::MAX_LEN { @@ -161,7 +253,7 @@ impl Name { name.push_str(&self.0); name.push(SEPARATOR); name.push_str(component); - Ok(Name(name)) + Ok(NameBuf(name)) } /// Checks that `text` can be in a name: it has no control characters, @@ -204,20 +296,15 @@ impl Name { /// The name of the directory the file is in, [`Name::ROOT`] for a file /// at the top. The root has none. - pub fn parent(&self) -> Option { - // The first component of a name is not reserved, and that is the - // only check a part of a name could fail. So every directory a name - // is in has a name, which is not checked again. - self.parent_str().map(|parent| Name(parent.to_owned())) - } - - /// The name of the directory the file is in, as [`Name::parent`] has - /// it, without a copy. - pub(crate) fn parent_str(&self) -> Option<&str> { + pub fn parent(&self) -> Option<&Name> { if self.is_root() { return None; } - Some(self.0.rsplit_once(SEPARATOR).map_or("", |(parent, _)| parent)) + // The first component of a name is not reserved, and that is the + // only check a part of a name could fail. So every directory a name + // is in has a name, which is not checked again. + let parent = self.0.rsplit_once(SEPARATOR); + Some(parent.map_or(Name::ROOT, |(parent, _)| Name::from_str_unchecked(parent))) } /// The name of the file in its directory, its last component. The @@ -247,6 +334,24 @@ impl Name { } } +impl NameBuf { + /// Takes `name` as the name of a file object, if it is one. A `String` + /// is taken as it is. If it is not a name, the error says why and hands + /// the string back. + pub fn new(name: impl Into) -> Result { + let name = name.into(); + match Name::new(&name) { + Ok(_) => Ok(NameBuf(name)), + Err(problem) => Err(NameError { name, problem }), + } + } + + /// The name, borrowed. + pub fn as_name(&self) -> &Name { + Name::from_str_unchecked(&self.0) + } +} + impl Ord for Name { fn cmp(&self, other: &Name) -> Ordering { NamePair::new(&self.0, &other.0).ordering() @@ -333,57 +438,205 @@ impl PartialOrd for Name { } } +// An owned name is ordered and hashed as the borrowed name it is, which +// `Borrow` asks for: a map with owned names as its keys is looked up with +// a borrowed one. +impl Ord for NameBuf { + fn cmp(&self, other: &NameBuf) -> Ordering { + self.as_name().cmp(other.as_name()) + } +} + +impl PartialOrd for NameBuf { + fn partial_cmp(&self, other: &NameBuf) -> Option { + Some(self.cmp(other)) + } +} + +impl Hash for NameBuf { + fn hash(&self, state: &mut H) { + self.as_name().hash(state); + } +} + +/// An owned name and a borrowed one are compared and ordered as two +/// borrowed names are, with either one on the left. These are the +/// comparisons std has between `PathBuf` and `Path`. +macro_rules! compare_as_names { + ($left:ty, $right:ty) => { + impl PartialEq<$right> for $left { + fn eq(&self, other: &$right) -> bool { + ::eq(self, other) + } + } + + impl PartialEq<$left> for $right { + fn eq(&self, other: &$left) -> bool { + ::eq(self, other) + } + } + + impl PartialOrd<$right> for $left { + fn partial_cmp(&self, other: &$right) -> Option { + ::partial_cmp(self, other) + } + } + + impl PartialOrd<$left> for $right { + fn partial_cmp(&self, other: &$left) -> Option { + ::partial_cmp(self, other) + } + } + }; +} + +compare_as_names!(NameBuf, Name); +compare_as_names!(NameBuf, &Name); + +/// A name is equal to the string it is, with either one on the left, as +/// std has it for `String` and `str`. `&Name == &str` and `&str == &Name` +/// follow from the first of these through the impl std has for two +/// references. Written out they would clash with it. A name is not ordered +/// against a string, since names are not in the order of their strings. +macro_rules! equal_to_strings { + ($name:ty, $string:ty) => { + impl PartialEq<$string> for $name { + fn eq(&self, other: &$string) -> bool { + self.as_str() == &other[..] + } + } + + impl PartialEq<$name> for $string { + fn eq(&self, other: &$name) -> bool { + &self[..] == other.as_str() + } + } + }; +} + +equal_to_strings!(Name, str); +equal_to_strings!(NameBuf, str); +equal_to_strings!(NameBuf, &str); + +impl Deref for NameBuf { + type Target = Name; + + fn deref(&self) -> &Name { + self.as_name() + } +} + +impl Borrow for NameBuf { + fn borrow(&self) -> &Name { + self.as_name() + } +} + +impl ToOwned for Name { + type Owned = NameBuf; + + fn to_owned(&self) -> NameBuf { + NameBuf(self.0.to_owned()) + } +} + +impl AsRef for Name { + fn as_ref(&self) -> &Name { + self + } +} + +impl AsRef for NameBuf { + fn as_ref(&self) -> &Name { + self.as_name() + } +} + impl AsRef for Name { fn as_ref(&self) -> &str { &self.0 } } +impl AsRef for NameBuf { + fn as_ref(&self) -> &str { + &self.0 + } +} + +impl From<&Name> for NameBuf { + fn from(name: &Name) -> NameBuf { + name.to_owned() + } +} + +impl From for String { + fn from(name: NameBuf) -> String { + name.0 + } +} + +impl Default for &Name { + fn default() -> Self { + Name::ROOT + } +} + impl fmt::Display for Name { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str(&self.0) + f.pad(self.as_str()) } } -impl FromStr for Name { - type Err = NameProblem; - - fn from_str(name: &str) -> Result { - Name::new(name) +impl fmt::Display for NameBuf { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(self.as_name(), f) } } -impl TryFrom for Name { - type Error = NameProblem; +// Both forms print the same, so that a name reads the same wherever it +// is printed, such as on the two sides of a failed assertion. +impl fmt::Debug for Name { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_tuple("Name").field(&self.as_str()).finish() + } +} - fn try_from(name: String) -> Result { - Name::new(name) +impl fmt::Debug for NameBuf { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(self.as_name(), f) } } -impl TryFrom<&str> for Name { +impl<'a> TryFrom<&'a str> for &'a Name { type Error = NameProblem; - fn try_from(name: &str) -> Result { + fn try_from(name: &'a str) -> Result<&'a Name, NameProblem> { Name::new(name) } } -impl From for String { - fn from(name: Name) -> String { - name.0 +impl FromStr for NameBuf { + type Err = NameError; + + fn from_str(name: &str) -> Result { + NameBuf::new(name) } } -impl PartialEq for Name { - fn eq(&self, other: &str) -> bool { - self.0 == other +impl TryFrom for NameBuf { + type Error = NameError; + + fn try_from(name: String) -> Result { + NameBuf::new(name) } } -impl PartialEq<&str> for Name { - fn eq(&self, other: &&str) -> bool { - self.0 == *other +impl TryFrom<&str> for NameBuf { + type Error = NameError; + + fn try_from(name: &str) -> Result { + NameBuf::new(name) } } @@ -391,6 +644,11 @@ impl PartialEq<&str> for Name { mod tests { use super::*; use crate::testing::full_tree_names; + use std::borrow::Cow; + use std::collections::hash_map::DefaultHasher; + use std::collections::{BTreeMap, HashMap}; + use std::error::Error as _; + use std::ops::Bound; #[test] fn names() { @@ -412,15 +670,19 @@ mod tests { "xUapi16Manifest.sig", ] { let parsed = Name::new(name).unwrap_or_else(|_| panic!("{:?}", name)); - check_parent(&parsed); + check_parent(parsed); assert_eq!(parsed, name); assert_eq!(parsed.as_str(), name); assert_eq!(parsed.to_string(), name); assert!(!parsed.is_root()); - assert_eq!(name.parse::(), Ok(parsed.clone())); - assert_eq!(Name::try_from(name), Ok(parsed.clone())); - assert_eq!(Name::try_from(name.to_string()), Ok(parsed.clone())); - assert_eq!(String::from(parsed), name); + assert_eq!(<&Name>::try_from(name), Ok(parsed)); + // The owned form is made of the same strings. + let owned = NameBuf::new(name).unwrap_or_else(|_| panic!("{:?}", name)); + assert_eq!(owned, parsed); + assert_eq!(name.parse::(), Ok(owned.clone())); + assert_eq!(NameBuf::try_from(name), Ok(owned.clone())); + assert_eq!(NameBuf::try_from(name.to_string()), Ok(owned.clone())); + assert_eq!(String::from(owned), name); } for (name, reason) in [ ("", NameProblem::Empty), @@ -452,7 +714,13 @@ mod tests { ("Uapi16Manifest/a/b", NameProblem::Reserved), ] { assert_eq!(Name::new(name), Err(reason), "{:?}", name); - assert_eq!(name.parse::(), Err(reason), "{:?}", name); + assert_eq!(<&Name>::try_from(name), Err(reason), "{:?}", name); + // The owned form refuses the same strings for the same reasons. + let error = NameBuf::new(name).unwrap_err(); + assert_eq!((error.name_problem(), error.as_str()), (reason, name)); + assert_eq!(name.parse::(), Err(error.clone()), "{:?}", name); + assert_eq!(NameBuf::try_from(name), Err(error.clone()), "{:?}", name); + assert_eq!(NameBuf::try_from(name.to_string()), Err(error), "{:?}", name); } // The control characters of Latin-1 are not ASCII control // characters. @@ -487,20 +755,20 @@ mod tests { // The whole name is limited, its components are not on their own. let longest = "x".repeat(Name::MAX_LEN); assert!(Name::new(longest.as_str()).is_ok()); - assert_eq!(Name::new(format!("{}x", longest)), Err(NameProblem::TooLong)); + assert_eq!(Name::new(&format!("{}x", longest)), Err(NameProblem::TooLong)); let component = "y".repeat(1000); let deep = [component.as_str(); 4].join("/"); assert!(Name::new(deep.as_str()).is_ok()); let fits = format!("{}/{}", deep, "z".repeat(Name::MAX_LEN - deep.len() - 1)); assert_eq!(fits.len(), Name::MAX_LEN); assert!(Name::new(fits.as_str()).is_ok()); - assert_eq!(Name::new(format!("{}z", fits)), Err(NameProblem::TooLong)); + assert_eq!(Name::new(&format!("{}z", fits)), Err(NameProblem::TooLong)); // The limit counts bytes, not characters. let euro = '\u{20ac}'; assert_eq!(euro.len_utf8(), 3); - assert!(Name::new(euro.to_string().repeat(Name::MAX_LEN / 3)).is_ok()); + assert!(Name::new(&euro.to_string().repeat(Name::MAX_LEN / 3)).is_ok()); assert_eq!( - Name::new(euro.to_string().repeat(Name::MAX_LEN / 3 + 1)), + Name::new(&euro.to_string().repeat(Name::MAX_LEN / 3 + 1)), Err(NameProblem::TooLong) ); } @@ -508,7 +776,7 @@ mod tests { #[test] fn order() { // In the order the specification sorts the names of a manifest in. - let names: Vec = [ + let names: Vec<&Name> = [ "", "a", "a/b", @@ -531,14 +799,41 @@ mod tests { } }) .collect(); + let owned: Vec = names.iter().map(|&name| name.to_owned()).collect(); for (i, a) in names.iter().enumerate() { for (j, b) in names.iter().enumerate() { - assert_eq!(a.cmp(b), i.cmp(&j), "{:?} {:?}", a, b); - assert_eq!(a.partial_cmp(b), Some(i.cmp(&j))); + let order = i.cmp(&j); + assert_eq!(a.cmp(b), order, "{:?} {:?}", a, b); + assert_eq!(a.partial_cmp(b), Some(order)); + // The owned form is in the same order. + assert_eq!(owned[i].cmp(&owned[j]), order); + assert_eq!(owned[i].partial_cmp(&owned[j]), Some(order)); + // So are the two forms against each other, with either one + // on the left, and the borrowed one behind a reference or + // not. + assert_eq!(PartialOrd::partial_cmp(&owned[i], *b), Some(order)); + assert_eq!(PartialOrd::partial_cmp(&owned[i], b), Some(order)); + assert_eq!(PartialOrd::partial_cmp(*a, &owned[j]), Some(order)); + assert_eq!(PartialOrd::partial_cmp(a, &owned[j]), Some(order)); + assert_eq!(owned[i] < *b, i < j); + assert_eq!(*a < owned[j], i < j); + assert_eq!(owned[i] == **b, i == j); + assert_eq!(owned[i] == *b, i == j); + assert_eq!(**a == owned[j], i == j); + assert_eq!(*a == owned[j], i == j); + assert_eq!(owned[i] == owned[j], i == j); + assert_eq!(a == b, i == j); } } // As strings they are not in that order. assert!(names[5].as_str() < names[4].as_str()); + // Sorting puts both forms in the order of a manifest. + let mut sorted: Vec<&Name> = names.iter().rev().copied().collect(); + sorted.sort(); + assert_eq!(sorted, names); + let mut sorted: Vec = owned.iter().rev().cloned().collect(); + sorted.sort(); + assert_eq!(sorted, owned); } /// The components the names of the tests below are made of: one that @@ -559,11 +854,11 @@ mod tests { // The separator comes before any other byte, also before those // that are lower as bytes: the space to the full stop. for byte in b' '..SEPARATOR_BYTE { - let other = Name::new(format!("a{}b", char::from(byte))).unwrap(); + let other = NameBuf::new(format!("a{}b", char::from(byte))).unwrap(); for name in ["a/b", "a/x", "a/b/c", "a/\u{e9}"] { assert!(Name::new(name).unwrap() < other, "{:?} {:?}", name, other); } - let other = Name::new(format!("a{}", char::from(byte))).unwrap(); + let other = NameBuf::new(format!("a{}", char::from(byte))).unwrap(); assert!(Name::new("a/b").unwrap() < other, "{:?}", other); } // A name comes before the names it is the first part of. @@ -578,8 +873,8 @@ mod tests { ("\u{e9}", "\u{e9}/a"), ] { let (first, second) = (Name::new(first).unwrap(), Name::new(second).unwrap()); - assert_eq!(first.cmp(&second), Ordering::Less, "{:?} {:?}", first, second); - assert_eq!(second.cmp(&first), Ordering::Greater, "{:?} {:?}", first, second); + assert_eq!(first.cmp(second), Ordering::Less, "{:?} {:?}", first, second); + assert_eq!(second.cmp(first), Ordering::Greater, "{:?} {:?}", first, second); } } @@ -664,7 +959,7 @@ mod tests { match Name::new(name.as_str()) { Ok(valid) => { assert!(reasons.is_empty(), "{:?} {:?}", name, reasons); - check_parent(&valid); + check_parent(valid); } Err(reason) => assert!(reasons.contains(&reason), "{:?} {:?} {:?}", name, reason, reasons), } @@ -699,6 +994,8 @@ mod tests { assert_eq!(name.components().collect::>(), ["a", "b", "c"]); assert_eq!(name.components().next_back(), Some("c")); assert_eq!(name.parent(), Some(Name::new("a/b").unwrap())); + // The parent is a part of the name itself. Nothing is copied. + assert_eq!(name.parent().unwrap().as_str().as_ptr(), name.as_str().as_ptr()); assert_eq!(name.file_name(), Some("c")); let top = Name::new("a").unwrap(); assert_eq!(top.parent(), Some(Name::ROOT)); @@ -706,6 +1003,17 @@ mod tests { assert_eq!(Name::ROOT.components().count(), 0); assert_eq!(Name::ROOT.parent(), None); assert_eq!(Name::ROOT.file_name(), None); + // Every directory a name is in has a parent, up to the root. + let up: Vec<&Name> = iter::successors(Some(name), |name| name.parent()).collect(); + assert_eq!(up, ["a/b/c", "a/b", "a", ""]); + // The parent of an owned name borrows from it. A copy outlives it. + let owned = NameBuf::new("x/y").unwrap(); + let kept: NameBuf = owned.parent().unwrap().to_owned(); + drop(owned); + assert_eq!(kept, "x"); + // The root has no parent. The default of a borrowed name, which is + // the root, can stand in for it. + assert!(Name::ROOT.parent().unwrap_or_default().is_root()); // A component is not always a name: the last one of a name can be // one that is reserved at the top. let below = Name::new("a/Uapi16Manifest").unwrap(); @@ -728,10 +1036,20 @@ mod tests { #[test] fn the_root() { - assert!(Name::ROOT.is_root()); + // The root lives as long as the program, so whatever borrows a name + // can keep it. + let root: &'static Name = Name::ROOT; + assert!(root.is_root()); assert_eq!(Name::ROOT, ""); - assert_eq!(Name::default(), Name::ROOT); + assert_eq!(Name::ROOT.as_str(), ""); + // It is the default of both forms. + assert_eq!(<&Name>::default(), Name::ROOT); + assert_eq!(NameBuf::default(), Name::ROOT); + assert!(NameBuf::default().is_root()); + assert_eq!(Name::ROOT.to_owned(), NameBuf::default()); + // The empty string is not a name: the root is not made of a string. assert_eq!(Name::new(""), Err(NameProblem::Empty)); + assert_eq!(NameBuf::new("").unwrap_err().name_problem(), NameProblem::Empty); } #[test] @@ -798,14 +1116,14 @@ mod tests { let expected = if component.contains(SEPARATOR) { Err(NameProblem::ContainsSeparator) } else { - Name::new(whole) + Name::new(&whole).map(Name::to_owned) }; assert_eq!(parent.join(component), expected, "{:?} {:?}", parent, component); } } assert_eq!(Name::ROOT.join("a").unwrap().join("b").unwrap(), "a/b"); // The length of the whole name counts. - let mut deep = Name::ROOT; + let mut deep = NameBuf::default(); while deep.as_str().len() + 2 * (long.len() + 1) <= Name::MAX_LEN { deep = deep.join(&long).unwrap(); } @@ -817,6 +1135,254 @@ mod tests { // refused for its length, as the whole name is. let wrong = format!("{}\n", "y".repeat(room)); assert_eq!(deep.join(&wrong), Err(NameProblem::TooLong)); - assert_eq!(Name::new(format!("{}/{}", deep, wrong)), Err(NameProblem::TooLong)); + assert_eq!(Name::new(&format!("{}/{}", deep, wrong)), Err(NameProblem::TooLong)); + } + + /// A borrowed name is the string it was checked in, and nothing is + /// copied. An owned name is made of a `String` as it is, and of a copy + /// of anything else. + #[test] + fn construction() { + let text = String::from("EFI/BOOT/BOOTX64.EFI"); + let borrowed = Name::new(&text).unwrap(); + assert_eq!(borrowed.as_str().as_ptr(), text.as_ptr()); + assert_eq!(borrowed.as_str().len(), text.len()); + let copied = NameBuf::new(text.as_str()).unwrap(); + assert_ne!(copied.as_str().as_ptr(), text.as_ptr()); + assert_eq!(copied, borrowed); + let at = text.as_ptr(); + let taken = NameBuf::new(text).unwrap(); + assert_eq!(taken.as_str().as_ptr(), at); + assert_eq!(taken, copied); + // An owned name gives its string back as it is. + let back = String::from(taken); + assert_eq!(back.as_ptr(), at); + } + + /// What makes an owned name of a string says why a string is not a + /// name, and hands the string back. + #[test] + fn owned_errors() { + let text = String::from("a//b"); + let at = text.as_ptr(); + let error = NameBuf::new(text).unwrap_err(); + assert_eq!(error.name_problem(), NameProblem::EmptyComponent); + assert_eq!(error.as_str(), "a//b"); + // The error prints as its reason, and has no other error behind it. + assert_eq!(error.to_string(), "name has an empty component"); + assert!(error.source().is_none()); + assert_eq!(error.clone(), error); + assert_ne!(error, NameBuf::new("a//c").unwrap_err()); + assert_ne!(error, NameBuf::new("").unwrap_err()); + // The string comes back as it went in, without a copy. + let back = error.into_string(); + assert_eq!(back, "a//b"); + assert_eq!(back.as_ptr(), at); + // Every way to an owned name fails the same way. + for (text, problem) in [ + ("", NameProblem::Empty), + ("../a", NameProblem::ContainsDotComponent), + ("a\nb", NameProblem::ContainsControlCharacter), + ("a\u{fffe}", NameProblem::ContainsNoncharacter), + ("Uapi16Manifest", NameProblem::Reserved), + ] { + let error = NameBuf::new(text).unwrap_err(); + assert_eq!(error.name_problem(), problem, "{:?}", text); + assert_eq!(error.as_str(), text); + assert_eq!(error.to_string(), problem.to_string()); + assert_eq!(text.parse::(), Err(error.clone())); + assert_eq!(NameBuf::try_from(text), Err(error.clone())); + assert_eq!(NameBuf::try_from(text.to_string()), Err(error.clone())); + assert_eq!(error.into_string(), text); + } + let too_long = "x".repeat(Name::MAX_LEN + 1); + let error = NameBuf::new(too_long.clone()).unwrap_err(); + assert_eq!(error.name_problem(), NameProblem::TooLong); + assert_eq!(error.into_string(), too_long); + // The error goes wherever an error of any kind goes. + let boxed: Box = NameBuf::new("a/").unwrap_err().into(); + assert_eq!(boxed.to_string(), "name has an empty component"); + } + + /// An owned name is a borrowed one wherever one is taken, and a + /// borrowed name is copied into an owned one where one is kept. + #[test] + fn between_the_forms() { + fn len_of(name: &Name) -> usize { + name.as_str().len() + } + fn len_of_either(name: impl AsRef) -> usize { + name.as_ref().as_str().len() + } + let owned = NameBuf::new("EFI/BOOT").unwrap(); + let borrowed: &Name = &owned; + assert_eq!(borrowed.as_str().as_ptr(), owned.as_str().as_ptr()); + assert_eq!(owned.as_name(), borrowed); + assert_eq!(len_of(&owned), 8); + assert_eq!(len_of(owned.as_name()), 8); + assert_eq!(len_of_either(&owned), 8); + assert_eq!(len_of_either(borrowed), 8); + let lent: &Name = owned.borrow(); + assert_eq!(lent, borrowed); + let text: &str = owned.as_ref(); + assert_eq!(text, "EFI/BOOT"); + let text: &str = borrowed.as_ref(); + assert_eq!(text, "EFI/BOOT"); + // The methods of the borrowed form are there on the owned one. + assert_eq!(owned.components().collect::>(), ["EFI", "BOOT"]); + assert_eq!(owned.file_name(), Some("BOOT")); + assert_eq!(owned.parent(), Some(Name::new("EFI").unwrap())); + assert_eq!(owned.join("BOOTX64.EFI").unwrap(), "EFI/BOOT/BOOTX64.EFI"); + assert!(!owned.is_root()); + // A copy of a borrowed name is an owned one. + assert_eq!(borrowed.to_owned(), owned); + assert_eq!(NameBuf::from(borrowed), owned); + assert_ne!(borrowed.to_owned().as_str().as_ptr(), owned.as_str().as_ptr()); + // A list of owned names lends a list of borrowed ones, and an + // owned name that may be missing lends one that may be missing. + let list = [owned.clone(), NameBuf::default()]; + let lent: Vec<&Name> = list.iter().map(NameBuf::as_name).collect(); + assert_eq!(lent, [borrowed, Name::ROOT]); + let maybe = Some(owned.clone()); + assert_eq!(maybe.as_deref(), Some(borrowed)); + // A name that is borrowed or owned, as it comes. + let cow: Cow<'_, Name> = Cow::Borrowed(borrowed); + assert_eq!(cow.into_owned(), owned); + } + + /// The value `value`, hashed. + fn hash_of(value: &T) -> u64 { + let mut hasher = DefaultHasher::new(); + value.hash(&mut hasher); + hasher.finish() + } + + /// Both forms are equal, ordered and hashed the same, so a map with + /// owned names as its keys is looked up with a borrowed one. + #[test] + fn maps() { + // In the order of a manifest. + let texts = ["a", "a/b", "a/b/c", "a/x", "a-b", "b", "\u{e9}"]; + let owned: Vec = texts.iter().map(|text| NameBuf::new(*text).unwrap()).collect(); + let by_hash: HashMap = owned.iter().cloned().zip(0..).collect(); + let by_order: BTreeMap = owned.iter().cloned().zip(0..).collect(); + for (i, text) in texts.iter().enumerate() { + let name = Name::new(text).unwrap(); + assert_eq!(hash_of(name), hash_of(&owned[i]), "{:?}", name); + assert_eq!(by_hash.get(name), Some(&i), "{:?}", name); + assert_eq!(by_order.get(name), Some(&i), "{:?}", name); + } + assert_eq!(hash_of(Name::ROOT), hash_of(&NameBuf::default())); + assert_eq!(by_hash.get(Name::ROOT), None); + assert_eq!(by_order.get(Name::new("c").unwrap()), None); + // The map is in the order of a manifest, so the names below a + // directory are one range of it. + let keys: Vec<&NameBuf> = by_order.keys().collect(); + assert_eq!(keys, owned.iter().collect::>()); + let below = ( + Bound::Excluded(Name::new("a").unwrap()), + Bound::Excluded(Name::new("a-b").unwrap()), + ); + let below: Vec<&str> = by_order + .range::(below) + .map(|(name, _)| name.as_str()) + .collect(); + assert_eq!(below, ["a/b", "a/b/c", "a/x"]); + } + + /// A name is equal to the string it is, with either one on the left. + #[test] + fn equal_to_strings() { + let owned = NameBuf::new("a/b").unwrap(); + let borrowed: &Name = &owned; + let text = "a/b"; + assert_eq!(*borrowed, *text); + assert_eq!(borrowed, text); + assert_eq!(owned, *text); + assert_eq!(owned, text); + // The string on the left. + assert_eq!(*text, *borrowed); + assert_eq!(text, borrowed); + assert_eq!(*text, owned); + assert_eq!(text, owned); + for other in ["a/c", "a", "a/b/c", "a/B", ""] { + assert_ne!(*borrowed, *other); + assert_ne!(borrowed, other); + assert_ne!(owned, *other); + assert_ne!(owned, other); + assert_ne!(*other, *borrowed); + assert_ne!(other, borrowed); + assert_ne!(*other, owned); + assert_ne!(other, owned); + } + assert_eq!(Name::ROOT, ""); + assert_eq!("", Name::ROOT); + assert_eq!(NameBuf::default(), ""); + assert_eq!("", NameBuf::default()); + // A string of its own is compared as the string it is. + let string = String::from("a/b"); + assert_eq!(borrowed, string.as_str()); + assert_eq!(string.as_str(), borrowed); + assert_eq!(owned, string.as_str()); + assert_eq!(string.as_str(), owned); + // Lists of names and lists of strings, either way round. + let names = vec![NameBuf::new("a").unwrap(), NameBuf::new("b").unwrap()]; + assert_eq!(names, ["a", "b"]); + assert_eq!(vec!["a", "b"], names); + let lent: Vec<&Name> = names.iter().map(NameBuf::as_name).collect(); + assert_eq!(lent, ["a", "b"]); + assert_eq!(vec!["a", "b"], lent); + } + + /// Both forms print the same: the name itself, and for debugging the + /// name as a `Name`. + #[test] + fn printing() { + let owned = NameBuf::new("a/\"b\" \u{e9}").unwrap(); + let borrowed: &Name = &owned; + assert_eq!(owned.to_string(), "a/\"b\" \u{e9}"); + assert_eq!(borrowed.to_string(), "a/\"b\" \u{e9}"); + assert_eq!(format!("{}/{}", borrowed, owned), "a/\"b\" \u{e9}/a/\"b\" \u{e9}"); + assert_eq!(format!("{:?}", owned), "Name(\"a/\\\"b\\\" \u{e9}\")"); + assert_eq!(format!("{:?}", borrowed), format!("{:?}", owned)); + assert_eq!(format!("{:#?}", borrowed), format!("{:#?}", owned)); + assert_eq!(format!("{:#?}", Name::new("a").unwrap()), "Name(\n \"a\",\n)"); + assert_eq!(Name::ROOT.to_string(), ""); + assert_eq!(format!("{:?}", Name::ROOT), "Name(\"\")"); + assert_eq!(format!("{:?}", NameBuf::default()), "Name(\"\")"); + } + + /// Both forms are padded and truncated as a string is: the width and + /// the precision count characters. + #[test] + fn padding() { + let text = "EFI/\u{e9}"; + let owned = NameBuf::new(text).unwrap(); + let borrowed: &Name = &owned; + let padded = " EFI/\u{e9}|EFI/\u{e9} |EFI|***EFI/****"; + assert_eq!(format!("{0:>12}|{0:<12}|{0:.3}|{0:*^11.4}", borrowed), padded); + assert_eq!(format!("{0:>12}|{0:<12}|{0:.3}|{0:*^11.4}", owned), padded); + assert_eq!(format!("{0:>12}|{0:<12}|{0:.3}|{0:*^11.4}", text), padded); + // A name that is as wide as asked for, or wider, is printed as it is. + assert_eq!(format!("{:5}", borrowed), text); + assert_eq!(format!("{:>2}", owned), text); + assert_eq!(format!("{:.5}", borrowed), text); + // The root is all padding. + assert_eq!(format!("{0:>3}|{0:<3}|{0:.3}|", Name::ROOT), " | ||"); + assert_eq!(format!("{0:>3}|{0:<3}|{0:.3}|", NameBuf::default()), " | ||"); + } + + /// A borrowed name is as large as a `&str` and an owned one as large as + /// a `String`, and both go to other threads, as the error of an owned + /// name does. + #[test] + fn sizes_and_threads() { + assert_eq!(size_of::<&Name>(), size_of::<&str>()); + assert_eq!(size_of::>(), size_of::<&str>()); + assert_eq!(size_of::(), size_of::()); + fn send_and_sync() {} + send_and_sync::<&'static Name>(); + send_and_sync::(); + send_and_sync::(); } } diff --git a/src/uapi16/object.rs b/src/uapi16/object.rs index 4eec52e..53bd945 100644 --- a/src/uapi16/object.rs +++ b/src/uapi16/object.rs @@ -13,7 +13,7 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH}; use crate::decode::ROOT_RECORD; use crate::error::{Error, ErrorKind, Field, Problem, ValidityProblem}; use crate::hex::Hex; -use crate::{Features, Name, Order, Sha256, STRING_RULES}; +use crate::{Features, Name, NameBuf, Order, Sha256, STRING_RULES}; /// The inode type of a file object, its `type` field. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] @@ -1094,7 +1094,7 @@ pub enum ContentsSource { #[default] Implied, /// `file`: the data is in this file next to the manifest. - File(Name), + File(NameBuf), /// `url`: the data is at this http or https URL. Url(String), /// `literal`: the data is in the manifest, and here. @@ -1700,7 +1700,7 @@ impl InodeAttributes { #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct FileObject { - pub(crate) name: Name, + pub(crate) name: NameBuf, pub(crate) inode_type: InodeType, pub(crate) size: Option, pub(crate) sha256: Option, @@ -1741,7 +1741,7 @@ impl FileObject { /// A file object for the regular file `name` that says nothing else /// about it. - pub fn new(name: Name) -> FileObject { + pub fn new(name: NameBuf) -> FileObject { FileObject { name, inode_type: InodeType::Regular, @@ -1765,12 +1765,12 @@ impl FileObject { } /// Sets `name`. - pub fn set_name(&mut self, name: Name) { + pub fn set_name(&mut self, name: NameBuf) { self.name = name; } /// The name, the object taken apart for it. - pub fn into_name(self) -> Name { + pub fn into_name(self) -> NameBuf { self.name } @@ -1931,7 +1931,7 @@ impl FileObject { /// [`FilledIn`]. /// /// ``` - /// use uapi16::{FileObject, Name, Object, Reader, Sha256}; + /// use uapi16::{FileObject, NameBuf, Object, Reader, Sha256}; /// /// let manifest = concat!( /// "\x1e{\"mediaType\":\"application/vnd.uapi.16.manifest\"}\n", @@ -1943,7 +1943,7 @@ impl FileObject { /// panic!("no file object"); /// }; /// // The reader filled in the hash of no data for the size 0. - /// let mut set = FileObject::new(Name::new("e")?); + /// let mut set = FileObject::new(NameBuf::new("e")?); /// set.set_size(Some(0)); /// set.set_sha256(Some(Sha256::EMPTY)); /// assert!(read.eq_ignore_filled_in(&set)); @@ -2555,7 +2555,7 @@ mod tests { assert_eq!(Validity::Revoked.to_string(), "revoked"); assert_eq!(ValidityWindow::default().state, Validity::Good); let kind = |object: &FileObject, now| object.check_validity(now).map_err(|e| e.kind()); - let mut object = FileObject::new(Name::new("d/x").unwrap()); + let mut object = FileObject::new(NameBuf::new("d/x").unwrap()); assert_eq!(kind(&object, 0), Ok(())); assert_eq!(kind(&object, u64::MAX), Ok(())); object.validity.since_usec = 10; @@ -2700,7 +2700,7 @@ mod tests { assert_eq!(attributes.flags.get(flag), state, "{:?}", flag); } for (flag, get, set) in dos { - let mut object = FileObject::new(Name::new("f").unwrap()); + let mut object = FileObject::new(NameBuf::new("f").unwrap()); set(&mut object, state); assert_eq!(get(&object), state, "{:?}", flag); let stated = if state.is_some() { flag } else { DosFlags::default() }; @@ -2738,7 +2738,7 @@ mod tests { assert_eq!(every, Features::ALL); // A field makes a file object state its feature. assert_eq!( - FileObject::new(Name::new("f").unwrap()).stated_features(), + FileObject::new(NameBuf::new("f").unwrap()).stated_features(), Features::NONE ); let partition = |set: Give| { @@ -2769,7 +2769,7 @@ mod tests { (|o| o.inode.read_only = Some(false), Features::READ_ONLY), ]; for (set, feature) in cases { - let mut object = FileObject::new(Name::new("f").unwrap()); + let mut object = FileObject::new(NameBuf::new("f").unwrap()); set(&mut object); assert_eq!(object.stated_features(), feature, "{:?}", object); } @@ -2785,27 +2785,27 @@ mod tests { ), ]; for (set, feature) in partitions { - let mut object = FileObject::new(Name::new("f").unwrap()); + let mut object = FileObject::new(NameBuf::new("f").unwrap()); object.gpt = partition(set); assert_eq!(object.stated_features(), feature, "{:?}", object); } - let mut object = FileObject::new(Name::new("f").unwrap()); + let mut object = FileObject::new(NameBuf::new("f").unwrap()); (object.inode.gid, object.inode.group_name) = (Some(0), Some("g".into())); assert_eq!(object.stated_features(), Features::GID | Features::GROUP_NAME); for &(flag, _, feature) in InodeFlags::FIELDS { - let mut object = FileObject::new(Name::new("f").unwrap()); + let mut object = FileObject::new(NameBuf::new("f").unwrap()); object.inode.flags.put(flag, Some(true)); assert_eq!(object.stated_features(), feature, "{:?}", flag); } // The contents of a symbolic link are its target, which a feature // records. Those of other files are not. - let mut object = FileObject::new(Name::new("f").unwrap()); + let mut object = FileObject::new(NameBuf::new("f").unwrap()); object.contents = vec![ContentsObject::new(ContentsSource::Literal(b"t".to_vec()))]; assert_eq!(object.stated_features(), Features::NONE); object.inode_type = InodeType::Symlink; assert_eq!(object.stated_features(), Features::SYMLINK); // What a reader filled in does not count. - let mut object = FileObject::new(Name::new("f").unwrap()); + let mut object = FileObject::new(NameBuf::new("f").unwrap()); (object.size, object.sha256) = (Some(0), Some(Sha256::EMPTY)); object.filled_in.insert(Field::Size); assert_eq!(object.stated_features(), Features::SHA256); @@ -2848,7 +2848,7 @@ mod tests { let literal = ContentsObject::new(ContentsSource::Literal(b"data".to_vec())); assert_eq!(literal.literal(), Some(&b"data"[..])); assert_eq!((literal.file(), literal.url(), literal.offset), (None, None, 0)); - let file = ContentsObject::new(ContentsSource::File(Name::new("blob").unwrap())); + let file = ContentsObject::new(ContentsSource::File(NameBuf::new("blob").unwrap())); assert_eq!(file.file().map(Name::as_str), Some("blob")); let url = ContentsObject::new(ContentsSource::Url("https://example.com/x".to_string())); assert_eq!(url.url(), Some("https://example.com/x")); @@ -2881,7 +2881,7 @@ mod tests { /// The fields of a partition change in place, and come out whole. #[test] fn gpt_in_place() { - let mut object = FileObject::new(Name::new("a").unwrap()); + let mut object = FileObject::new(NameBuf::new("a").unwrap()); assert!(object.gpt_mut().is_none()); object.set_gpt(Some(GptPartition::default())); object.gpt_mut().unwrap().set_label(Some("esp".to_string())); @@ -2963,7 +2963,7 @@ mod tests { let object = read(r#"{"name":"a","contents":[{"literal":"aGVsbG8="}]}"#); let mut contents = object.contents()[0].clone(); assert_eq!((contents.encoded_size(), contents.original_size()), (Some(5), Some(5))); - contents.set_source(ContentsSource::File(Name::new("blob").unwrap())); + contents.set_source(ContentsSource::File(NameBuf::new("blob").unwrap())); assert_eq!( (contents.encoded_size(), contents.original_size(), contents.filled_in()), (None, None, none) @@ -3053,7 +3053,7 @@ mod tests { filled_in: FilledIn::default(), }; let object = FileObject { - name: Name::new("f").unwrap(), + name: NameBuf::new("f").unwrap(), inode_type: InodeType::Regular, size: Some(5), sha256: Some(Sha256::digest(b"hello")), @@ -3113,7 +3113,7 @@ mod tests { each_differs( &object, &[ - |o| o.name = Name::new("g").unwrap(), + |o| o.name = NameBuf::new("g").unwrap(), |o| o.inode_type = InodeType::Symlink, |o| o.size = None, |o| o.sha256 = None, diff --git a/src/uapi16/sequence.rs b/src/uapi16/sequence.rs index 35cca49..32b9c81 100644 --- a/src/uapi16/sequence.rs +++ b/src/uapi16/sequence.rs @@ -117,7 +117,7 @@ impl SequenceCheck { // at once. let pair = NamePair::new(&self.last, name); if !pair.second_is_in_open_directory(self.last_type) { - let directory = object.name.parent_str().unwrap_or_default(); + let directory = object.name.parent().unwrap_or_default().as_str(); return Err(Error::manifest( Problem::Misplaced, format!( @@ -159,14 +159,14 @@ mod tests { use crate::error::ErrorKind; use crate::object::{DosFlags, InodeFlags}; use crate::testing::full_tree_names; - use crate::{ContentsObject, ContentsSource, FatSerial, Mode, Name, Uuid}; + use crate::{ContentsObject, ContentsSource, FatSerial, Mode, Name, NameBuf, Uuid}; use std::num::NonZeroU64; /// Gives an object a field. type Give = fn(&mut T); fn object(name: &str, inode_type: InodeType) -> FileObject { - let mut object = FileObject::new(Name::new(name).unwrap()); + let mut object = FileObject::new(NameBuf::new(name).unwrap()); object.inode_type = inode_type; object } diff --git a/src/uapi16/writer.rs b/src/uapi16/writer.rs index ee0a793..e91d74f 100644 --- a/src/uapi16/writer.rs +++ b/src/uapi16/writer.rs @@ -58,12 +58,12 @@ enum Stage { /// trailer object, so after [`Encoder::finish`] every method fails. /// /// ``` -/// use uapi16::{Encoder, FileObject, Name, RootObject}; +/// use uapi16::{Encoder, FileObject, NameBuf, RootObject}; /// /// let mut text = String::new(); /// let mut encoder = Encoder::begin(&RootObject::default(), &mut text)?; /// for name in ["a", "b"] { -/// encoder.file(&FileObject::new(Name::new(name)?), &mut text)?; +/// encoder.file(&FileObject::new(NameBuf::new(name)?), &mut text)?; /// } /// encoder.finish(&mut text)?; /// assert_eq!( @@ -851,7 +851,7 @@ mod tests { directory, everything, json, name, read_whole, record, recording_all, sequence, write_whole, written, Whole, EMPTY, HELLO, ROOT, SIGNATURE, TRAILER, WORLD, }; - use crate::{Sha256, Writer}; + use crate::{NameBuf, Sha256, Writer}; use std::collections::BTreeMap; /// What `systemd-manifest` writes, see the manifests in tests/fixtures: @@ -1206,14 +1206,14 @@ mod tests { // Every other file object has a name, and comes before the // signatures. let mut writer = Writer::begin(Vec::new(), &RootObject::default()).unwrap(); - let e = writer.file(&FileObject::new(Name::ROOT)).unwrap_err(); + let e = writer.file(&FileObject::new(NameBuf::default())).unwrap_err(); assert_eq!(kind(e), (Problem::NoName, Some(1), Some(Field::Name))); writer.file(&FileObject::new(name("a"))).unwrap(); writer.signature(&SignatureObject::new("pkcs7")).unwrap(); let e = writer.file(&FileObject::new(name("b"))).unwrap_err(); assert_eq!(kind(e), (Problem::FileAfterSignature, Some(3), None)); // As for a reader, that comes before a missing name. - let e = writer.file(&FileObject::new(Name::ROOT)).unwrap_err(); + let e = writer.file(&FileObject::new(NameBuf::default())).unwrap_err(); assert_eq!(kind(e), (Problem::FileAfterSignature, Some(3), None)); writer.signature(&SignatureObject::new("openpgp")).unwrap(); let bytes = writer.finish().unwrap(); @@ -1652,7 +1652,7 @@ mod tests { // A value, before a missing name. ( r#"{"uid":65535}"#.into(), - |o| (o.name, o.inode.uid) = (Name::ROOT, Some(65535)), + |o| (o.name, o.inode.uid) = (NameBuf::default(), Some(65535)), Problem::FieldOutOfRange, ), // A value, before a field the inode type does not permit. @@ -1728,7 +1728,7 @@ mod tests { assert_eq!(e.kind(), ErrorKind::Manifest(Problem::FileAfterSignature)); let mut writer = Writer::begin(Vec::new(), &root).unwrap(); writer.signature(&SignatureObject::new("pkcs7")).unwrap(); - let mut nameless = FileObject::new(Name::ROOT); + let mut nameless = FileObject::new(NameBuf::default()); nameless.inode.uid = Some(65535); let w = writer.file(&nameless).unwrap_err(); assert_eq!((w.kind(), w.record_number()), (e.kind(), e.record_number())); @@ -1863,7 +1863,7 @@ mod tests { Field::Contents, ), ( - |o| o.contents = vec![ContentsObject::new(ContentsSource::File(Name::ROOT))], + |o| o.contents = vec![ContentsObject::new(ContentsSource::File(NameBuf::default()))], Problem::InvalidContents, Field::File, ), @@ -1886,7 +1886,11 @@ mod tests { // root. A reader refuses the record a writer would write for such an // object with the same error, only without the name of the object, // which it doesn't know yet. - for file in [Name::ROOT, Name::default(), name("a").parent().unwrap()] { + for file in [ + Name::ROOT.to_owned(), + NameBuf::default(), + name("a").parent().unwrap().to_owned(), + ] { let mut object = FileObject::new(name("x")); object.contents = vec![ContentsObject::new(ContentsSource::File(file))]; let mut writer = Writer::begin(Vec::new(), &root).unwrap(); @@ -2250,7 +2254,9 @@ mod tests { let appended = text.len(); for e in [ encoder.file(&FileObject::new(name("z")), &mut text).unwrap_err(), - encoder.file(&FileObject::new(Name::ROOT), &mut text).unwrap_err(), + encoder + .file(&FileObject::new(NameBuf::default()), &mut text) + .unwrap_err(), encoder .signature(&SignatureObject::new("pkcs7"), &mut text) .unwrap_err(),