diff options
author | Eelco Dolstra <edolstra@gmail.com> | 2022-01-25 13:57:22 +0100 |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-01-25 13:57:22 +0100 |
commit | 5fa624f59af67a1b6b6c7bfd8f00a47520b34cce (patch) | |
tree | 851882363cd2b55c4e98cae947a4d2cf0e9b4f30 /nix-rust/src | |
parent | a04a66c19659a092821877ff41a8380118ff7376 (diff) | |
parent | fcf3528ad1ad3fc0eeac9a1241b7edfebf67eb3d (diff) |
Merge pull request #5987 from edolstra/rust-cleanup
Remove unused Rust stuff
Diffstat (limited to 'nix-rust/src')
-rw-r--r-- | nix-rust/src/c.rs | 77 | ||||
-rw-r--r-- | nix-rust/src/error.rs | 118 | ||||
-rw-r--r-- | nix-rust/src/lib.rs | 10 | ||||
-rw-r--r-- | nix-rust/src/nar.rs | 126 | ||||
-rw-r--r-- | nix-rust/src/store/binary_cache_store.rs | 48 | ||||
-rw-r--r-- | nix-rust/src/store/mod.rs | 17 | ||||
-rw-r--r-- | nix-rust/src/store/path.rs | 224 | ||||
-rw-r--r-- | nix-rust/src/store/path_info.rs | 70 | ||||
-rw-r--r-- | nix-rust/src/store/store.rs | 53 | ||||
-rw-r--r-- | nix-rust/src/util/base32.rs | 160 | ||||
-rw-r--r-- | nix-rust/src/util/mod.rs | 1 |
11 files changed, 0 insertions, 904 deletions
diff --git a/nix-rust/src/c.rs b/nix-rust/src/c.rs deleted file mode 100644 index c1358545f..000000000 --- a/nix-rust/src/c.rs +++ /dev/null @@ -1,77 +0,0 @@ -use super::{error, store::path, store::StorePath, util}; - -#[no_mangle] -pub unsafe extern "C" fn ffi_String_new(s: &str, out: *mut String) { - // FIXME: check whether 's' is valid UTF-8? - out.write(s.to_string()) -} - -#[no_mangle] -pub unsafe extern "C" fn ffi_String_drop(self_: *mut String) { - std::ptr::drop_in_place(self_); -} - -#[no_mangle] -pub extern "C" fn ffi_StorePath_new( - path: &str, - store_dir: &str, -) -> Result<StorePath, error::CppException> { - StorePath::new(std::path::Path::new(path), std::path::Path::new(store_dir)) - .map_err(|err| err.into()) -} - -#[no_mangle] -pub extern "C" fn ffi_StorePath_new2( - hash: &[u8; crate::store::path::STORE_PATH_HASH_BYTES], - name: &str, -) -> Result<StorePath, error::CppException> { - StorePath::from_parts(*hash, name).map_err(|err| err.into()) -} - -#[no_mangle] -pub extern "C" fn ffi_StorePath_fromBaseName( - base_name: &str, -) -> Result<StorePath, error::CppException> { - StorePath::new_from_base_name(base_name).map_err(|err| err.into()) -} - -#[no_mangle] -pub unsafe extern "C" fn ffi_StorePath_drop(self_: *mut StorePath) { - std::ptr::drop_in_place(self_); -} - -#[no_mangle] -pub extern "C" fn ffi_StorePath_to_string(self_: &StorePath) -> Vec<u8> { - let mut buf = vec![0; path::STORE_PATH_HASH_CHARS + 1 + self_.name.name().len()]; - util::base32::encode_into(self_.hash.hash(), &mut buf[0..path::STORE_PATH_HASH_CHARS]); - buf[path::STORE_PATH_HASH_CHARS] = b'-'; - buf[path::STORE_PATH_HASH_CHARS + 1..].clone_from_slice(self_.name.name().as_bytes()); - buf -} - -#[no_mangle] -pub extern "C" fn ffi_StorePath_less_than(a: &StorePath, b: &StorePath) -> bool { - a < b -} - -#[no_mangle] -pub extern "C" fn ffi_StorePath_eq(a: &StorePath, b: &StorePath) -> bool { - a == b -} - -#[no_mangle] -pub extern "C" fn ffi_StorePath_clone(self_: &StorePath) -> StorePath { - self_.clone() -} - -#[no_mangle] -pub extern "C" fn ffi_StorePath_name(self_: &StorePath) -> &str { - self_.name.name() -} - -#[no_mangle] -pub extern "C" fn ffi_StorePath_hash_data( - self_: &StorePath, -) -> &[u8; crate::store::path::STORE_PATH_HASH_BYTES] { - self_.hash.hash() -} diff --git a/nix-rust/src/error.rs b/nix-rust/src/error.rs deleted file mode 100644 index bb0c9a933..000000000 --- a/nix-rust/src/error.rs +++ /dev/null @@ -1,118 +0,0 @@ -use std::fmt; - -#[derive(Debug)] -pub enum Error { - InvalidPath(crate::store::StorePath), - BadStorePath(std::path::PathBuf), - NotInStore(std::path::PathBuf), - BadNarInfo, - BadBase32, - StorePathNameEmpty, - StorePathNameTooLong, - BadStorePathName, - NarSizeFieldTooBig, - BadNarString, - BadNarPadding, - BadNarVersionMagic, - MissingNarOpenTag, - MissingNarCloseTag, - MissingNarField, - BadNarField(String), - BadExecutableField, - IOError(std::io::Error), - #[cfg(unused)] - HttpError(hyper::error::Error), - Misc(String), - #[cfg(not(test))] - Foreign(CppException), - BadTarFileMemberName(String), -} - -impl From<std::io::Error> for Error { - fn from(err: std::io::Error) -> Self { - Error::IOError(err) - } -} - -#[cfg(unused)] -impl From<hyper::error::Error> for Error { - fn from(err: hyper::error::Error) -> Self { - Error::HttpError(err) - } -} - -impl fmt::Display for Error { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Error::InvalidPath(_) => write!(f, "invalid path"), - Error::BadNarInfo => write!(f, ".narinfo file is corrupt"), - Error::BadStorePath(path) => write!(f, "path '{}' is not a store path", path.display()), - Error::NotInStore(path) => { - write!(f, "path '{}' is not in the Nix store", path.display()) - } - Error::BadBase32 => write!(f, "invalid base32 string"), - Error::StorePathNameEmpty => write!(f, "store path name is empty"), - Error::StorePathNameTooLong => { - write!(f, "store path name is longer than 211 characters") - } - Error::BadStorePathName => write!(f, "store path name contains forbidden character"), - Error::NarSizeFieldTooBig => write!(f, "size field in NAR is too big"), - Error::BadNarString => write!(f, "NAR string is not valid UTF-8"), - Error::BadNarPadding => write!(f, "NAR padding is not zero"), - Error::BadNarVersionMagic => write!(f, "unsupported NAR version"), - Error::MissingNarOpenTag => write!(f, "NAR open tag is missing"), - Error::MissingNarCloseTag => write!(f, "NAR close tag is missing"), - Error::MissingNarField => write!(f, "expected NAR field is missing"), - Error::BadNarField(s) => write!(f, "unrecognized NAR field '{}'", s), - Error::BadExecutableField => write!(f, "bad 'executable' field in NAR"), - Error::IOError(err) => write!(f, "I/O error: {}", err), - #[cfg(unused)] - Error::HttpError(err) => write!(f, "HTTP error: {}", err), - #[cfg(not(test))] - Error::Foreign(_) => write!(f, "<C++ exception>"), // FIXME - Error::Misc(s) => write!(f, "{}", s), - Error::BadTarFileMemberName(s) => { - write!(f, "tar archive contains illegal file name '{}'", s) - } - } - } -} - -#[cfg(not(test))] -impl From<Error> for CppException { - fn from(err: Error) -> Self { - match err { - Error::Foreign(ex) => ex, - _ => CppException::new(&err.to_string()), - } - } -} - -#[cfg(not(test))] -#[repr(C)] -#[derive(Debug)] -pub struct CppException(*const libc::c_void); // == std::exception_ptr* - -#[cfg(not(test))] -impl CppException { - fn new(s: &str) -> Self { - Self(unsafe { make_error(s) }) - } -} - -#[cfg(not(test))] -impl Drop for CppException { - fn drop(&mut self) { - unsafe { - destroy_error(self.0); - } - } -} - -#[cfg(not(test))] -extern "C" { - #[allow(improper_ctypes)] // YOLO - fn make_error(s: &str) -> *const libc::c_void; - - fn destroy_error(exc: *const libc::c_void); -} diff --git a/nix-rust/src/lib.rs b/nix-rust/src/lib.rs deleted file mode 100644 index 101de106f..000000000 --- a/nix-rust/src/lib.rs +++ /dev/null @@ -1,10 +0,0 @@ -#[allow(improper_ctypes_definitions)] -#[cfg(not(test))] -mod c; -mod error; -#[cfg(unused)] -mod nar; -mod store; -mod util; - -pub use error::Error; diff --git a/nix-rust/src/nar.rs b/nix-rust/src/nar.rs deleted file mode 100644 index cb520935e..000000000 --- a/nix-rust/src/nar.rs +++ /dev/null @@ -1,126 +0,0 @@ -use crate::Error; -use byteorder::{LittleEndian, ReadBytesExt}; -use std::convert::TryFrom; -use std::io::Read; - -pub fn parse<R: Read>(input: &mut R) -> Result<(), Error> { - if String::read(input)? != NAR_VERSION_MAGIC { - return Err(Error::BadNarVersionMagic); - } - - parse_file(input) -} - -const NAR_VERSION_MAGIC: &str = "nix-archive-1"; - -fn parse_file<R: Read>(input: &mut R) -> Result<(), Error> { - if String::read(input)? != "(" { - return Err(Error::MissingNarOpenTag); - } - - if String::read(input)? != "type" { - return Err(Error::MissingNarField); - } - - match String::read(input)?.as_ref() { - "regular" => { - let mut _executable = false; - let mut tag = String::read(input)?; - if tag == "executable" { - _executable = true; - if String::read(input)? != "" { - return Err(Error::BadExecutableField); - } - tag = String::read(input)?; - } - if tag != "contents" { - return Err(Error::MissingNarField); - } - let _contents = Vec::<u8>::read(input)?; - if String::read(input)? != ")" { - return Err(Error::MissingNarCloseTag); - } - } - "directory" => loop { - match String::read(input)?.as_ref() { - "entry" => { - if String::read(input)? != "(" { - return Err(Error::MissingNarOpenTag); - } - if String::read(input)? != "name" { - return Err(Error::MissingNarField); - } - let _name = String::read(input)?; - if String::read(input)? != "node" { - return Err(Error::MissingNarField); - } - parse_file(input)?; - let tag = String::read(input)?; - if tag != ")" { - return Err(Error::MissingNarCloseTag); - } - } - ")" => break, - s => return Err(Error::BadNarField(s.into())), - } - }, - "symlink" => { - if String::read(input)? != "target" { - return Err(Error::MissingNarField); - } - let _target = String::read(input)?; - if String::read(input)? != ")" { - return Err(Error::MissingNarCloseTag); - } - } - s => return Err(Error::BadNarField(s.into())), - } - - Ok(()) -} - -trait Deserialize: Sized { - fn read<R: Read>(input: &mut R) -> Result<Self, Error>; -} - -impl Deserialize for String { - fn read<R: Read>(input: &mut R) -> Result<Self, Error> { - let buf = Deserialize::read(input)?; - Ok(String::from_utf8(buf).map_err(|_| Error::BadNarString)?) - } -} - -impl Deserialize for Vec<u8> { - fn read<R: Read>(input: &mut R) -> Result<Self, Error> { - let n: usize = Deserialize::read(input)?; - let mut buf = vec![0; n]; - input.read_exact(&mut buf)?; - skip_padding(input, n)?; - Ok(buf) - } -} - -fn skip_padding<R: Read>(input: &mut R, len: usize) -> Result<(), Error> { - if len % 8 != 0 { - let mut buf = [0; 8]; - let buf = &mut buf[0..8 - (len % 8)]; - input.read_exact(buf)?; - if !buf.iter().all(|b| *b == 0) { - return Err(Error::BadNarPadding); - } - } - Ok(()) -} - -impl Deserialize for u64 { - fn read<R: Read>(input: &mut R) -> Result<Self, Error> { - Ok(input.read_u64::<LittleEndian>()?) - } -} - -impl Deserialize for usize { - fn read<R: Read>(input: &mut R) -> Result<Self, Error> { - let n: u64 = Deserialize::read(input)?; - Ok(usize::try_from(n).map_err(|_| Error::NarSizeFieldTooBig)?) - } -} diff --git a/nix-rust/src/store/binary_cache_store.rs b/nix-rust/src/store/binary_cache_store.rs deleted file mode 100644 index 9e1e88b7c..000000000 --- a/nix-rust/src/store/binary_cache_store.rs +++ /dev/null @@ -1,48 +0,0 @@ -use super::{PathInfo, Store, StorePath}; -use crate::Error; -use hyper::client::Client; - -pub struct BinaryCacheStore { - base_uri: String, - client: Client<hyper::client::HttpConnector, hyper::Body>, -} - -impl BinaryCacheStore { - pub fn new(base_uri: String) -> Self { - Self { - base_uri, - client: Client::new(), - } - } -} - -impl Store for BinaryCacheStore { - fn query_path_info( - &self, - path: &StorePath, - ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<PathInfo, Error>> + Send>> { - let uri = format!("{}/{}.narinfo", self.base_uri.clone(), path.hash); - let path = path.clone(); - let client = self.client.clone(); - let store_dir = self.store_dir().to_string(); - - Box::pin(async move { - let response = client.get(uri.parse::<hyper::Uri>().unwrap()).await?; - - if response.status() == hyper::StatusCode::NOT_FOUND - || response.status() == hyper::StatusCode::FORBIDDEN - { - return Err(Error::InvalidPath(path)); - } - - let mut body = response.into_body(); - - let mut bytes = Vec::new(); - while let Some(next) = body.next().await { - bytes.extend(next?); - } - - PathInfo::parse_nar_info(std::str::from_utf8(&bytes).unwrap(), &store_dir) - }) - } -} diff --git a/nix-rust/src/store/mod.rs b/nix-rust/src/store/mod.rs deleted file mode 100644 index da972482c..000000000 --- a/nix-rust/src/store/mod.rs +++ /dev/null @@ -1,17 +0,0 @@ -pub mod path; - -#[cfg(unused)] -mod binary_cache_store; -#[cfg(unused)] -mod path_info; -#[cfg(unused)] -mod store; - -pub use path::{StorePath, StorePathHash, StorePathName}; - -#[cfg(unused)] -pub use binary_cache_store::BinaryCacheStore; -#[cfg(unused)] -pub use path_info::PathInfo; -#[cfg(unused)] -pub use store::Store; diff --git a/nix-rust/src/store/path.rs b/nix-rust/src/store/path.rs deleted file mode 100644 index 99f7a1f18..000000000 --- a/nix-rust/src/store/path.rs +++ /dev/null @@ -1,224 +0,0 @@ -use crate::error::Error; -use crate::util::base32; -use std::fmt; -use std::path::Path; - -#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug)] -pub struct StorePath { - pub hash: StorePathHash, - pub name: StorePathName, -} - -pub const STORE_PATH_HASH_BYTES: usize = 20; -pub const STORE_PATH_HASH_CHARS: usize = 32; - -impl StorePath { - pub fn new(path: &Path, store_dir: &Path) -> Result<Self, Error> { - if path.parent() != Some(store_dir) { - return Err(Error::NotInStore(path.into())); - } - Self::new_from_base_name( - path.file_name() - .ok_or_else(|| Error::BadStorePath(path.into()))? - .to_str() - .ok_or_else(|| Error::BadStorePath(path.into()))?, - ) - } - - pub fn from_parts(hash: [u8; STORE_PATH_HASH_BYTES], name: &str) -> Result<Self, Error> { - Ok(StorePath { - hash: StorePathHash(hash), - name: StorePathName::new(name)?, - }) - } - - pub fn new_from_base_name(base_name: &str) -> Result<Self, Error> { - if base_name.len() < STORE_PATH_HASH_CHARS + 1 - || base_name.as_bytes()[STORE_PATH_HASH_CHARS] != b'-' - { - return Err(Error::BadStorePath(base_name.into())); - } - - Ok(StorePath { - hash: StorePathHash::new(&base_name[0..STORE_PATH_HASH_CHARS])?, - name: StorePathName::new(&base_name[STORE_PATH_HASH_CHARS + 1..])?, - }) - } -} - -impl fmt::Display for StorePath { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}-{}", self.hash, self.name) - } -} - -#[derive(Clone, PartialEq, Eq, Debug)] -pub struct StorePathHash([u8; STORE_PATH_HASH_BYTES]); - -impl StorePathHash { - pub fn new(s: &str) -> Result<Self, Error> { - assert_eq!(s.len(), STORE_PATH_HASH_CHARS); - let v = base32::decode(s)?; - assert_eq!(v.len(), STORE_PATH_HASH_BYTES); - let mut bytes: [u8; 20] = Default::default(); - bytes.copy_from_slice(&v[0..STORE_PATH_HASH_BYTES]); - Ok(Self(bytes)) - } - - pub fn hash(&self) -> &[u8; STORE_PATH_HASH_BYTES] { - &self.0 - } -} - -impl fmt::Display for StorePathHash { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let mut buf = vec![0; STORE_PATH_HASH_CHARS]; - base32::encode_into(&self.0, &mut buf); - f.write_str(std::str::from_utf8(&buf).unwrap()) - } -} - -impl Ord for StorePathHash { - fn cmp(&self, other: &Self) -> std::cmp::Ordering { - // Historically we've sorted store paths by their base32 - // serialization, but our base32 encodes bytes in reverse - // order. So compare them in reverse order as well. - self.0.iter().rev().cmp(other.0.iter().rev()) - } -} - -impl PartialOrd for StorePathHash { - fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { - Some(self.cmp(other)) - } -} - -#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug)] -pub struct StorePathName(String); - -impl StorePathName { - pub fn new(s: &str) -> Result<Self, Error> { - if s.is_empty() { - return Err(Error::StorePathNameEmpty); - } - - if s.len() > 211 { - return Err(Error::StorePathNameTooLong); - } - - let is_good_path_name = s.chars().all(|c| { - c.is_ascii_alphabetic() - || c.is_ascii_digit() - || c == '+' - || c == '-' - || c == '.' - || c == '_' - || c == '?' - || c == '=' - }); - if s.starts_with('.') || !is_good_path_name { - return Err(Error::BadStorePathName); - } - - Ok(Self(s.to_string())) - } - - pub fn name(&self) -> &str { - &self.0 - } -} - -impl fmt::Display for StorePathName { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str(&self.0) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use assert_matches::assert_matches; - - #[test] - fn test_parse() { - let s = "7h7qgvs4kgzsn8a6rb273saxyqh4jxlz-konsole-18.12.3"; - let p = StorePath::new_from_base_name(&s).unwrap(); - assert_eq!(p.name.0, "konsole-18.12.3"); - assert_eq!( - p.hash.0, - [ - 0x9f, 0x76, 0x49, 0x20, 0xf6, 0x5d, 0xe9, 0x71, 0xc4, 0xca, 0x46, 0x21, 0xab, 0xff, - 0x9b, 0x44, 0xef, 0x87, 0x0f, 0x3c - ] - ); - } - - #[test] - fn test_no_name() { - let s = "7h7qgvs4kgzsn8a6rb273saxyqh4jxlz-"; - assert_matches!( - StorePath::new_from_base_name(&s), - Err(Error::StorePathNameEmpty) - ); - } - - #[test] - fn test_no_dash() { - let s = "7h7qgvs4kgzsn8a6rb273saxyqh4jxlz"; - assert_matches!( - StorePath::new_from_base_name(&s), - Err(Error::BadStorePath(_)) - ); - } - - #[test] - fn test_short_hash() { - let s = "7h7qgvs4kgzsn8a6rb273saxyqh4jxl-konsole-18.12.3"; - assert_matches!( - StorePath::new_from_base_name(&s), - Err(Error::BadStorePath(_)) - ); - } - - #[test] - fn test_invalid_hash() { - let s = "7h7qgvs4kgzsn8e6rb273saxyqh4jxlz-konsole-18.12.3"; - assert_matches!(StorePath::new_from_base_name(&s), Err(Error::BadBase32)); - } - - #[test] - fn test_long_name() { - let s = "7h7qgvs4kgzsn8a6rb273saxyqh4jxlz-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; - assert_matches!(StorePath::new_from_base_name(&s), Ok(_)); - } - - #[test] - fn test_too_long_name() { - let s = "7h7qgvs4kgzsn8a6rb273saxyqh4jxlz-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; - assert_matches!( - StorePath::new_from_base_name(&s), - Err(Error::StorePathNameTooLong) - ); - } - - #[test] - fn test_bad_name() { - let s = "7h7qgvs4kgzsn8a6rb273saxyqh4jxlz-foo bar"; - assert_matches!( - StorePath::new_from_base_name(&s), - Err(Error::BadStorePathName) - ); - - let s = "7h7qgvs4kgzsn8a6rb273saxyqh4jxlz-kónsole"; - assert_matches!( - StorePath::new_from_base_name(&s), - Err(Error::BadStorePathName) - ); - } - - #[test] - fn test_roundtrip() { - let s = "7h7qgvs4kgzsn8a6rb273saxyqh4jxlz-konsole-18.12.3"; - assert_eq!(StorePath::new_from_base_name(&s).unwrap().to_string(), s); - } -} diff --git a/nix-rust/src/store/path_info.rs b/nix-rust/src/store/path_info.rs deleted file mode 100644 index c2903ed29..000000000 --- a/nix-rust/src/store/path_info.rs +++ /dev/null @@ -1,70 +0,0 @@ -use crate::store::StorePath; -use crate::Error; -use std::collections::BTreeSet; - -#[derive(Clone, Debug)] -pub struct PathInfo { - pub path: StorePath, - pub references: BTreeSet<StorePath>, - pub nar_size: u64, - pub deriver: Option<StorePath>, - - // Additional binary cache info. - pub url: Option<String>, - pub compression: Option<String>, - pub file_size: Option<u64>, -} - -impl PathInfo { - pub fn parse_nar_info(nar_info: &str, store_dir: &str) -> Result<Self, Error> { - let mut path = None; - let mut references = BTreeSet::new(); - let mut nar_size = None; - let mut deriver = None; - let mut url = None; - let mut compression = None; - let mut file_size = None; - - for line in nar_info.lines() { - let colon = line.find(':').ok_or(Error::BadNarInfo)?; - - let (name, value) = line.split_at(colon); - - if !value.starts_with(": ") { - return Err(Error::BadNarInfo); - } - - let value = &value[2..]; - - if name == "StorePath" { - path = Some(StorePath::new(std::path::Path::new(value), store_dir)?); - } else if name == "NarSize" { - nar_size = Some(u64::from_str_radix(value, 10).map_err(|_| Error::BadNarInfo)?); - } else if name == "References" { - if !value.is_empty() { - for r in value.split(' ') { - references.insert(StorePath::new_from_base_name(r)?); - } - } - } else if name == "Deriver" { - deriver = Some(StorePath::new_from_base_name(value)?); - } else if name == "URL" { - url = Some(value.into()); - } else if name == "Compression" { - compression = Some(value.into()); - } else if name == "FileSize" { - file_size = Some(u64::from_str_radix(value, 10).map_err(|_| Error::BadNarInfo)?); - } - } - - Ok(PathInfo { - path: path.ok_or(Error::BadNarInfo)?, - references, - nar_size: nar_size.ok_or(Error::BadNarInfo)?, - deriver, - url: Some(url.ok_or(Error::BadNarInfo)?), - compression, - file_size, - }) - } -} diff --git a/nix-rust/src/store/store.rs b/nix-rust/src/store/store.rs deleted file mode 100644 index c33dc4a90..000000000 --- a/nix-rust/src/store/store.rs +++ /dev/null @@ -1,53 +0,0 @@ -use super::{PathInfo, StorePath}; -use crate::Error; -use std::collections::{BTreeMap, BTreeSet}; -use std::path::Path; - -pub trait Store: Send + Sync { - fn store_dir(&self) -> &str { - "/nix/store" - } - - fn query_path_info( - &self, - store_path: &StorePath, - ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<PathInfo, Error>> + Send>>; -} - -impl dyn Store { - pub fn parse_store_path(&self, path: &Path) -> Result<StorePath, Error> { - StorePath::new(path, self.store_dir()) - } - - pub async fn compute_path_closure( - &self, - roots: BTreeSet<StorePath>, - ) -> Result<BTreeMap<StorePath, PathInfo>, Error> { - let mut done = BTreeSet::new(); - let mut result = BTreeMap::new(); - let mut pending = vec![]; - - for root in roots { - pending.push(self.query_path_info(&root)); - done.insert(root); - } - - while !pending.is_empty() { - let (info, _, remaining) = futures::future::select_all(pending).await; - pending = remaining; - - let info = info?; - - for path in &info.references { - if !done.contains(path) { - pending.push(self.query_path_info(&path)); - done.insert(path.clone()); - } - } - - result.insert(info.path.clone(), info); - } - - Ok(result) - } -} diff --git a/nix-rust/src/util/base32.rs b/nix-rust/src/util/base32.rs deleted file mode 100644 index 7e71dc920..000000000 --- a/nix-rust/src/util/base32.rs +++ /dev/null @@ -1,160 +0,0 @@ -use crate::error::Error; -use lazy_static::lazy_static; - -pub fn encoded_len(input_len: usize) -> usize { - if input_len == 0 { - 0 - } else { - (input_len * 8 - 1) / 5 + 1 - } -} - -pub fn decoded_len(input_len: usize) -> usize { - input_len * 5 / 8 -} - -static BASE32_CHARS: &[u8; 32] = &b"0123456789abcdfghijklmnpqrsvwxyz"; - -lazy_static! { - static ref BASE32_CHARS_REVERSE: Box<[u8; 256]> = { - let mut xs = [0xffu8; 256]; - for (n, c) in BASE32_CHARS.iter().enumerate() { - xs[*c as usize] = n as u8; - } - Box::new(xs) - }; -} - -pub fn encode(input: &[u8]) -> String { - let mut buf = vec![0; encoded_len(input.len())]; - encode_into(input, &mut buf); - std::str::from_utf8(&buf).unwrap().to_string() -} - -pub fn encode_into(input: &[u8], output: &mut [u8]) { - let len = encoded_len(input.len()); - assert_eq!(len, output.len()); - - let mut nr_bits_left: usize = 0; - let mut bits_left: u16 = 0; - let mut pos = len; - - for b in input { - bits_left |= (*b as u16) << nr_bits_left; - nr_bits_left += 8; - while nr_bits_left > 5 { - output[pos - 1] = BASE32_CHARS[(bits_left & 0x1f) as usize]; - pos -= 1; - bits_left >>= 5; - nr_bits_left -= 5; - } - } - - if nr_bits_left > 0 { - output[pos - 1] = BASE32_CHARS[(bits_left & 0x1f) as usize]; - pos -= 1; - } - - assert_eq!(pos, 0); -} - -pub fn decode(input: &str) -> Result<Vec<u8>, crate::Error> { - let mut res = Vec::with_capacity(decoded_len(input.len())); - - let mut nr_bits_left: usize = 0; - let mut bits_left: u16 = 0; - - for c in input.chars().rev() { - let b = BASE32_CHARS_REVERSE[c as usize]; - if b == 0xff { - return Err(Error::BadBase32); - } - bits_left |= (b as u16) << nr_bits_left; - nr_bits_left += 5; - if nr_bits_left >= 8 { - res.push((bits_left & 0xff) as u8); - bits_left >>= 8; - nr_bits_left -= 8; - } - } - - if nr_bits_left > 0 && bits_left != 0 { - return Err(Error::BadBase32); - } - - Ok(res) -} - -#[cfg(test)] -mod tests { - use super::*; - use assert_matches::assert_matches; - use hex; - use proptest::proptest; - - #[test] - fn test_encode() { - assert_eq!(encode(&[]), ""); - - assert_eq!( - encode(&hex::decode("0839703786356bca59b0f4a32987eb2e6de43ae8").unwrap()), - "x0xf8v9fxf3jk8zln1cwlsrmhqvp0f88" - ); - - assert_eq!( - encode( - &hex::decode("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad") - .unwrap() - ), - "1b8m03r63zqhnjf7l5wnldhh7c134ap5vpj0850ymkq1iyzicy5s" - ); - - assert_eq!( - encode( - &hex::decode("ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f") - .unwrap() - ), - "2gs8k559z4rlahfx0y688s49m2vvszylcikrfinm30ly9rak69236nkam5ydvly1ai7xac99vxfc4ii84hawjbk876blyk1jfhkbbyx" - ); - } - - #[test] - fn test_decode() { - assert_eq!(hex::encode(decode("").unwrap()), ""); - - assert_eq!( - hex::encode(decode("x0xf8v9fxf3jk8zln1cwlsrmhqvp0f88").unwrap()), - "0839703786356bca59b0f4a32987eb2e6de43ae8" - ); - - assert_eq!( - hex::encode(decode("1b8m03r63zqhnjf7l5wnldhh7c134ap5vpj0850ymkq1iyzicy5s").unwrap()), - "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" - ); - - assert_eq!( - hex::encode(decode("2gs8k559z4rlahfx0y688s49m2vvszylcikrfinm30ly9rak69236nkam5ydvly1ai7xac99vxfc4ii84hawjbk876blyk1jfhkbbyx").unwrap()), - "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f" - ); - - assert_matches!( - decode("xoxf8v9fxf3jk8zln1cwlsrmhqvp0f88"), - Err(Error::BadBase32) - ); - assert_matches!( - decode("2b8m03r63zqhnjf7l5wnldhh7c134ap5vpj0850ymkq1iyzicy5s"), - Err(Error::BadBase32) - ); - assert_matches!(decode("2"), Err(Error::BadBase32)); - assert_matches!(decode("2gs"), Err(Error::BadBase32)); - assert_matches!(decode("2gs8"), Err(Error::BadBase32)); - } - - proptest! { - - #[test] - fn roundtrip(s: Vec<u8>) { - assert_eq!(s, decode(&encode(&s)).unwrap()); - } - } -} diff --git a/nix-rust/src/util/mod.rs b/nix-rust/src/util/mod.rs deleted file mode 100644 index eaad9d406..000000000 --- a/nix-rust/src/util/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod base32; |