From 9608bbce8ceac354f07b30b1fa24756ee158a516 Mon Sep 17 00:00:00 2001 From: sokorototo Date: Tue, 21 May 2024 21:38:19 +0300 Subject: [PATCH] Removed redundant error documentation --- vach/src/crypto_utils/mod.rs | 10 ----- vach/src/global/flags.rs | 3 -- vach/src/global/header.rs | 8 ---- vach/src/global/reg_entry.rs | 4 +- vach/src/lib.rs | 4 +- vach/src/loader/archive.rs | 56 +++++++++++----------------- vach/src/{tests/mod.rs => tests.rs} | 22 +++++------ vach/src/writer/config.rs | 2 - vach/src/writer/mod.rs | 20 ++-------- vach/src/writer/prepared.rs | 14 +++---- vach/test_data/signed/target.vach | Bin 190972 -> 190720 bytes 11 files changed, 45 insertions(+), 98 deletions(-) rename vach/src/{tests/mod.rs => tests.rs} (96%) diff --git a/vach/src/crypto_utils/mod.rs b/vach/src/crypto_utils/mod.rs index 54a9be16..81c61824 100644 --- a/vach/src/crypto_utils/mod.rs +++ b/vach/src/crypto_utils/mod.rs @@ -22,8 +22,6 @@ pub fn gen_keypair() -> crypto::SigningKey { } /// Use this to read and parse a `Keypair` from a read stream -/// ### Errors -/// - If the data can't be parsed into a keypair pub fn read_keypair(mut handle: R) -> InternalResult { let mut keypair_bytes = [0; crate::SECRET_KEY_LENGTH + crate::PUBLIC_KEY_LENGTH]; handle.read_exact(&mut keypair_bytes)?; @@ -31,20 +29,12 @@ pub fn read_keypair(mut handle: R) -> InternalResult(mut handle: T) -> InternalResult { let mut keypair_bytes = [0; crate::PUBLIC_KEY_LENGTH]; handle.read_exact(&mut keypair_bytes)?; crypto::VerifyingKey::from_bytes(&keypair_bytes).map_err(|err| InternalError::ParseError(err.to_string())) } /// Read and parse a secret key from a read stream -/// -/// ### Errors -/// - If parsing of the secret key fails -/// - `io` errors pub fn read_secret_key(mut handle: T) -> InternalResult { let mut secret_bytes = [0; crate::SECRET_KEY_LENGTH]; handle.read_exact(&mut secret_bytes)?; diff --git a/vach/src/global/flags.rs b/vach/src/global/flags.rs index 50786c09..6df708bc 100644 --- a/vach/src/global/flags.rs +++ b/vach/src/global/flags.rs @@ -77,9 +77,6 @@ impl Flags { /// flag.set(0b0000_1000_0000_0001, false).unwrap(); // 0 flags remain zero /// assert_eq!(flag.bits(), 0b1000_0000_0000_0000); /// ``` - /// - /// ### Errors - /// - Trying to set a bit in the forbidden section of the flags pub fn set(&mut self, bit: u32, toggle: bool) -> InternalResult { if (Flags::RESERVED_MASK & bit) != 0 { return Err(InternalError::RestrictedFlagAccessError); diff --git a/vach/src/global/header.rs b/vach/src/global/header.rs index b971be38..00fc513a 100644 --- a/vach/src/global/header.rs +++ b/vach/src/global/header.rs @@ -50,10 +50,6 @@ impl ArchiveConfig { /// // config.load_public_key(&keypair_bytes).unwrap(); /// config.load_public_key(&keypair_bytes[32..]).unwrap(); /// ``` - /// - /// ### Errors - /// - If parsing of the public key fails - /// - `io` errors #[inline] #[cfg(feature = "crypto")] #[cfg_attr(docsrs, doc(cfg(feature = "crypto")))] @@ -147,8 +143,6 @@ impl Header { pub const CAPACITY_SIZE: usize = 2; /// Validates a `Header` with a template [ArchiveConfig] - /// ### Errors - /// - (in)validation of magic and archive version pub(crate) fn validate(config: &ArchiveConfig, header: &Header) -> InternalResult { // Validate magic if header.magic != config.magic { @@ -163,8 +157,6 @@ impl Header { Ok(()) } - /// ### Errors - /// - `io` errors pub(crate) fn from_handle(mut handle: T) -> InternalResult
{ let mut buffer: [u8; Header::BASE_SIZE] = [0u8; Header::BASE_SIZE]; handle.read_exact(&mut buffer)?; diff --git a/vach/src/global/reg_entry.rs b/vach/src/global/reg_entry.rs index f4c15e49..fbb6b219 100644 --- a/vach/src/global/reg_entry.rs +++ b/vach/src/global/reg_entry.rs @@ -42,8 +42,6 @@ impl RegistryEntry { } /// Given a read handle, will proceed to read and parse bytes into a [`RegistryEntry`] struct. (de-serialization) - /// ### Errors - /// Produces `io` errors and if the bytes in the id section is not valid UTF-8 pub(crate) fn from_handle(mut handle: T) -> InternalResult { let mut buffer: [u8; RegistryEntry::MIN_SIZE] = [0u8; RegistryEntry::MIN_SIZE]; handle.read_exact(&mut buffer)?; @@ -98,7 +96,7 @@ impl RegistryEntry { } /// Serializes a [`RegistryEntry`] struct into an array of bytes - pub(crate) fn encode(&self, skip_signature: bool) -> InternalResult> { + pub(crate) fn to_bytes(&self, skip_signature: bool) -> InternalResult> { // Make sure the ID is not too big or else it will break the archive let id = self.id.as_ref(); diff --git a/vach/src/lib.rs b/vach/src/lib.rs index dae476b4..e351f66d 100644 --- a/vach/src/lib.rs +++ b/vach/src/lib.rs @@ -187,9 +187,7 @@ pub mod builder { #[cfg_attr(docsrs, doc(cfg(feature = "archive")))] pub mod archive { pub use crate::loader::{archive::Archive, resource::Resource}; - pub use crate::global::{ - reg_entry::RegistryEntry, header::ArchiveConfig, error::*, flags::Flags, - }; + pub use crate::global::{reg_entry::RegistryEntry, header::ArchiveConfig, error::*, flags::Flags}; #[cfg(feature = "compression")] pub use crate::global::compressor::CompressionAlgorithm; } diff --git a/vach/src/loader/archive.rs b/vach/src/loader/archive.rs index 30e1f9e4..7374bf05 100644 --- a/vach/src/loader/archive.rs +++ b/vach/src/loader/archive.rs @@ -73,7 +73,7 @@ impl Archive { // Decompress and|or decrypt the data #[inline(never)] - fn process(&self, entry: &RegistryEntry, id: &str, mut raw: Vec) -> InternalResult<(Vec, bool)> { + fn process(&self, entry: &RegistryEntry, mut raw: Vec) -> InternalResult<(Vec, bool)> { /* Literally the hottest function in the block (🕶) */ // buffer_a originally contains the raw data @@ -88,7 +88,7 @@ impl Archive { if let Some(signature) = entry.signature { let raw_size = raw.len(); - let entry_bytes = entry.encode(true)?; + let entry_bytes = entry.to_bytes(true)?; raw.extend_from_slice(&entry_bytes); is_secure = pk.verify_strict(&raw, &signature).is_ok(); @@ -136,7 +136,11 @@ impl Archive { Compressor::new(source.as_slice()).decompress(CompressionAlgorithm::Snappy, &mut target)? } else { return InternalResult::Err(InternalError::OtherError( - format!("Unable to determine the compression algorithm used for entry with ID: {id}").into(), + format!( + "Unable to determine the compression algorithm used for entry: {}", + entry + ) + .into(), )); }; @@ -164,8 +168,6 @@ where /// ```skip /// Archive::with_config(HANDLE, &ArchiveConfig::default())?; /// ``` - /// ### Errors - /// - If the internal call to `Archive::with_config(-)` returns an error #[inline(always)] pub fn new(handle: T) -> InternalResult> { Archive::with_config(handle, &ArchiveConfig::default()) @@ -173,11 +175,6 @@ where /// Given a read handle, this will read and parse the data into an [`Archive`] struct. /// Pass a reference to [ArchiveConfig] and it will be used to validate the source and for further configuration. - /// ### Errors - /// - If parsing fails, an `Err(---)` is returned. - /// - The archive fails to validate - /// - `io` errors - /// - If any `ID`s are not valid UTF-8 pub fn with_config(mut handle: T, config: &ArchiveConfig) -> InternalResult> { // Start reading from the start of the input handle.seek(SeekFrom::Start(0))?; @@ -194,31 +191,20 @@ where entries.insert(entry.id.clone(), entry); } - #[cfg(feature = "crypto")] - { - // Errors where no decryptor has been instantiated will be returned once a fetch is made to an encrypted resource - let decryptor = config + let archive = Archive { + header, + handle: Mutex::new(handle), + entries, + + #[cfg(feature = "crypto")] + key: config.public_key, + #[cfg(feature = "crypto")] + decryptor: config .public_key .as_ref() - .map(|pk| crypto::Encryptor::new(pk, config.magic)); - - Ok(Archive { - header, - handle: Mutex::new(handle), - key: config.public_key, - entries, - decryptor, - }) - } - - #[cfg(not(feature = "crypto"))] - { - Ok(Archive { - header, - handle: Mutex::new(handle), - entries, - }) - } + .map(|pk| crypto::Encryptor::new(pk, config.magic)), + }; + Ok(archive) } /// Fetch a [`RegistryEntry`] from this [`Archive`]. @@ -265,7 +251,7 @@ where // Prepare contextual variables // Decompress and|or decrypt the data - let (buffer, is_secure) = self.process(&entry, id.as_ref(), raw)?; + let (buffer, is_secure) = self.process(&entry, raw)?; Ok(Resource { content_version: entry.content_version, @@ -290,7 +276,7 @@ where // Prepare contextual variables // Decompress and|or decrypt the data - let (buffer, is_secure) = self.process(&entry, id.as_ref(), raw)?; + let (buffer, is_secure) = self.process(&entry, raw)?; Ok(Resource { content_version: entry.content_version, diff --git a/vach/src/tests/mod.rs b/vach/src/tests.rs similarity index 96% rename from vach/src/tests/mod.rs rename to vach/src/tests.rs index 615bbee9..4fe55b74 100644 --- a/vach/src/tests/mod.rs +++ b/vach/src/tests.rs @@ -7,7 +7,7 @@ use crate::prelude::*; // Contains both the public key and secret key in the same file: // secret -> [u8; crate::SECRET_KEY_LENGTH], public -> [u8; crate::PUBLIC_KEY_LENGTH] -const KEYPAIR: &[u8; crate::SECRET_KEY_LENGTH + crate::PUBLIC_KEY_LENGTH] = include_bytes!("../../test_data/pair.pub"); +const KEYPAIR: &[u8; crate::SECRET_KEY_LENGTH + crate::PUBLIC_KEY_LENGTH] = include_bytes!("../test_data/pair.pub"); // The paths to the Archives, to be written|loaded const SIGNED_TARGET: &str = "test_data/signed/target.vach"; @@ -137,12 +137,15 @@ fn builder_with_signature() -> InternalResult { let mut build_config = BuilderConfig::default().callback(&cb); build_config.load_keypair(KEYPAIR.as_slice())?; + builder.add_dir("test_data", None)?; - let template = Leaf::default().sign(true); - builder.add_dir("test_data", Some(&template))?; + // sign and no sign! + builder.add_leaf(Leaf::default().id("not_signed"))?; - // Tests conditional signing - builder.add_leaf(Leaf::default().id("not_signed").sign(false))?; + let signed = Leaf::new(b"Don't forget to recite your beatitudes!" as &[u8]) + .id("signed") + .sign(true); + builder.add_leaf(signed)?; let mut target = File::create(SIGNED_TARGET)?; println!( @@ -169,19 +172,16 @@ fn fetch_with_signature() -> InternalResult { // The adjacent resource was flagged to not be signed let not_signed_resource = archive.fetch_mut("not_signed")?; - assert!(!not_signed_resource.flags.contains(Flags::SIGNED_FLAG)); - assert!(!not_signed_resource.authenticated); - - // The adjacent resource was flagged to not be signed - let not_signed_resource = archive.fetch_mut("not_signed")?; + dbg!(&archive.entries()); assert!(!not_signed_resource.flags.contains(Flags::SIGNED_FLAG)); assert!(!not_signed_resource.authenticated); // Check authenticity of retrieved data let song = song.trim(); - println!("{}", song); assert_eq!(song.len(), 1977); + let resource = archive.fetch_mut("signed")?; + assert!(resource.authenticated); assert!(resource.flags.contains(Flags::SIGNED_FLAG)); diff --git a/vach/src/writer/config.rs b/vach/src/writer/config.rs index 465f5e66..ad04a7a7 100644 --- a/vach/src/writer/config.rs +++ b/vach/src/writer/config.rs @@ -102,8 +102,6 @@ impl<'a> BuilderConfig<'a> { // Keypair helpers /// Parses and stores a keypair from a source. - /// ### Errors - /// If the call to `::utils::read_keypair()` fails to parse the data from the handle #[cfg(feature = "crypto")] pub fn load_keypair(&mut self, handle: T) -> crate::global::error::InternalResult { crate::crypto_utils::read_keypair(handle).map(|kp| self.keypair = Some(kp)) diff --git a/vach/src/writer/mod.rs b/vach/src/writer/mod.rs index 66731ec4..7d191535 100644 --- a/vach/src/writer/mod.rs +++ b/vach/src/writer/mod.rs @@ -48,8 +48,6 @@ impl<'a> Builder<'a> { /// Appends a read handle wrapped in a [`Leaf`] into the processing queue. /// The `data` is wrapped in the default [`Leaf`], without cloning the original data. /// The second argument is the `ID` with which the embedded data will be tagged - /// ### Errors - /// - if a Leaf with the specified ID exists. pub fn add(&mut self, data: D, id: impl AsRef) -> InternalResult { let leaf = Leaf::new(data) .id(id.as_ref().to_string()) @@ -67,9 +65,6 @@ impl<'a> Builder<'a> { /// Loads all files from a directory, parses them into [`Leaf`]s and appends them into the processing queue. /// An optional [`Leaf`] is passed as a template from which the new [`Leaf`]s shall implement, pass `None` to use the [`Builder`] internal default template. /// Appended [`Leaf`]s have an `ID` in the form of of: `directory_name/file_name`. For example: `sounds/footstep.wav1, `sample/script.data` - /// ## Errors - /// - Any of the underlying calls to the filesystem fail. - /// - The internal call to `Builder::add_leaf()` fails. pub fn add_dir(&mut self, path: impl AsRef, template: Option<&Leaf<'a>>) -> InternalResult { use std::fs; @@ -96,10 +91,8 @@ impl<'a> Builder<'a> { Ok(()) } - /// Append a preconstructed [`Leaf`] into the processing queue. - /// [`Leaf`]s added directly do not implement data from the [`Builder`]s internal template. - /// ### Errors - /// - Returns an error if a [`Leaf`] with the specified `ID` exists. + /// Directly add a [`Leaf`] to the [`Builder`] + /// [`Leaf`]s added directly do not inherit data from the [`Builder`]s template. pub fn add_leaf(&mut self, leaf: Leaf<'a>) -> InternalResult { // Make sure no two leaves are written with the same ID if !self.id_set.insert(leaf.id.clone()) { @@ -188,11 +181,6 @@ impl<'a> Builder<'a> { /// This iterates over all [`Leaf`]s in the processing queue, parses them and writes the bytes out into a the target. /// Configure the custom *`MAGIC`*, `Header` flags and a [`Keypair`](crate::crypto::Keypair) using the [`BuilderConfig`] struct. - /// - /// ### Errors - /// - Underlying `io` errors - /// - If the optional compression or compression features aren't enabled - /// - If the requirements of a given stage, compression or encryption, are not met. Like not providing a keypair if a [`Leaf`] is to be encrypted. pub fn dump(self, mut target: W, config: &BuilderConfig) -> InternalResult { let Builder { mut leafs, .. } = self; @@ -279,7 +267,7 @@ impl<'a> Builder<'a> { #[cfg(feature = "crypto")] if result.sign { if let Some(keypair) = &config.keypair { - let entry_bytes = result.entry.encode(true)?; + let entry_bytes = result.entry.to_bytes(true)?; result.data.extend_from_slice(&entry_bytes); // DON"T FORGET TO TRUNCATE IF MODIFICATIONS ARE MADE // Include registry data in the signature @@ -289,7 +277,7 @@ impl<'a> Builder<'a> { } // write to registry buffer, this one might include the Signature - let entry_bytes = result.entry.encode(false)?; + let entry_bytes = result.entry.to_bytes(false)?; registry.write_all(&entry_bytes)?; // Call the progress callback bound within the [`BuilderConfig`] diff --git a/vach/src/writer/prepared.rs b/vach/src/writer/prepared.rs index 3dff8f34..056d09b9 100644 --- a/vach/src/writer/prepared.rs +++ b/vach/src/writer/prepared.rs @@ -1,7 +1,7 @@ -// Unit of data ready to be inserted into a `Write + Clone` target during Building -pub(crate) struct Prepared { - pub(crate) data: Vec, - pub(crate) entry: super::RegistryEntry, - #[cfg(feature = "crypto")] - pub(crate) sign: bool, -} +// Unit of data ready to be inserted into a `Write + Clone` target during Building +pub(crate) struct Prepared { + pub(crate) data: Vec, + pub(crate) entry: super::RegistryEntry, + #[cfg(feature = "crypto")] + pub(crate) sign: bool, +} diff --git a/vach/test_data/signed/target.vach b/vach/test_data/signed/target.vach index 1c5eb60324a296ceb0152758583b808804daf635..15ba76f6fd13b48c8683edcbba98a24682b37025 100644 GIT binary patch delta 408 zcmex!nY-Z>*}2K!h2Dkc=ou%q-F?C`|%O&4Vh8gxZOsFh4a{ zucQKE({~4m3e5!&T4FL6lT1AWgTg~5ut7W7Ayy$9P@JEa4maTD3y4Cfix{{V^72dK zi!;;nQd59p91Ji8>QEJI3=XGOJ)C)9W}wE}wOkx;54a0CESWk-S-o_J;$P0N1w4{+ z^7ZWA27Xzg!UZ$=TPxq~I(v81@9-tw#u4eqJrq=Lvo$YgYG2O8xP3VjQ|NPbm;5~S n5{0z0>mRP76s zWhqH5E{RV`EJ@T)N=?-(PA(#Q~aapI-ItCRKD+Gt(2 zWNMhY+307zf9(Ba-_AB|(`!X@!s076SJ@ZDZ|Me5P!e?PMh z>K)nfK0e!>XZ1y?N+orhlr_`O1?K83idLO|scGXh{r54Gg!U)ybeGSa&)jJ~?@GnP z$yaKtC!Uf429@(8NPO=EM?VA52f51~uLsKV+N|FHJn-O_H}Tu~8FRV~q+P$ez5dxQ zwZlWi=FZi=V`rAlP0tQ_t-K}n7;B(xmiDDxR$X#}VY@1s5FRMb&r64TfPvx9OK8G^ a#t9cgUOrPvd~*w9dkZ7u_7+B_(B}Yu2>0>;