Speed up StorePath::to_string()

1.81% -> 0.56%
This commit is contained in:
Eelco Dolstra 2019-12-10 20:48:36 +01:00
parent f64b58b45e
commit f800d450b7
3 changed files with 24 additions and 8 deletions

View file

@ -1,6 +1,7 @@
use super::{ use super::{
error, error,
foreign::{self, CBox}, foreign::{self, CBox},
store::path,
store::StorePath, store::StorePath,
util, util,
}; };
@ -53,8 +54,12 @@ pub unsafe extern "C" fn ffi_StorePath_drop(self_: *mut StorePath) {
} }
#[no_mangle] #[no_mangle]
pub extern "C" fn ffi_StorePath_to_string(self_: &StorePath) -> String { pub extern "C" fn ffi_StorePath_to_string(self_: &StorePath) -> Vec<u8> {
format!("{}", self_) 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] #[no_mangle]

View file

@ -70,7 +70,9 @@ impl StorePathHash {
impl fmt::Display for StorePathHash { impl fmt::Display for StorePathHash {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&base32::encode(&self.0)) 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())
} }
} }

View file

@ -25,27 +25,36 @@ lazy_static! {
} }
pub fn encode(input: &[u8]) -> String { pub fn encode(input: &[u8]) -> String {
let mut res = String::new(); let mut buf = vec![0; encoded_len(input.len())];
res.reserve(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 nr_bits_left: usize = 0;
let mut bits_left: u16 = 0; let mut bits_left: u16 = 0;
let mut pos = len;
for b in input { for b in input {
bits_left |= (*b as u16) << nr_bits_left; bits_left |= (*b as u16) << nr_bits_left;
nr_bits_left += 8; nr_bits_left += 8;
while nr_bits_left > 5 { while nr_bits_left > 5 {
res.push(BASE32_CHARS[(bits_left & 0x1f) as usize] as char); output[pos - 1] = BASE32_CHARS[(bits_left & 0x1f) as usize];
pos -= 1;
bits_left >>= 5; bits_left >>= 5;
nr_bits_left -= 5; nr_bits_left -= 5;
} }
} }
if nr_bits_left > 0 { if nr_bits_left > 0 {
res.push(BASE32_CHARS[(bits_left & 0x1f) as usize] as char); output[pos - 1] = BASE32_CHARS[(bits_left & 0x1f) as usize];
pos -= 1;
} }
res.chars().rev().collect() assert_eq!(pos, 0);
} }
pub fn decode(input: &str) -> Result<Vec<u8>, crate::Error> { pub fn decode(input: &str) -> Result<Vec<u8>, crate::Error> {