-
Notifications
You must be signed in to change notification settings - Fork 191
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Feature request: zero-copy constructor? #221
Comments
Seems that's something the library can't do at the moment. What about implementing it? I can open a PR. In theory not that hard. If data is little-ended and it is aligned with |
It's not possible to borrow from an existing buffer because there's no lifetime parameter in the type (like
If we instead consumed a
Performance is a goal, but that doesn't mean it must come at all costs. |
Hi, @cuviper Hm.. Are you saying it's not possible? What about borrowing data from I didn't think a lot about alternatives. Please treat them as a product of brainstorm activity rather than well thought out plan. Nevertheless, a theoretical solution definitely exists. |
It's fundamental to Rust that a type can't borrow data without expressing that borrowed lifetime. We could add something like
I'm not sure what you're suggesting here -- could you sketch out that API? |
I was looking for an API like this today. What I had in mind was something like this where T can be anything that can be borrowed as a slice of digits: use std::borrow::BorrowMut;
struct BigUint<T> {
data: T,
}
impl <T: BorrowMut<[u64]>> BigUint<T> {
pub fn new(data: T) -> Self {
Self { data }
}
/// Returns the number of least-significant bits that are zero,
/// or `None` if the entire number is zero.
pub fn trailing_zeros(&self) -> Option<u64> {
let data = self.data.borrow();
let i = data.iter().position(|&digit| digit != 0)?;
let zeros: u64 = data[i].trailing_zeros().into();
Some((i as u64) * 64 + zeros)
}
}
fn main() {
let mut digits: Vec<u64> = vec![0, 1, 0];
// First operate on a mut ref
let bigint = BigUint::new(&mut *digits);
println!("{:?}", bigint.trailing_zeros());
// Then consume the whole thing
let bigint = BigUint::new(digits);
println!("{:?}", bigint.trailing_zeros());
} |
By the way let vec1 = vec![ 0; 15 ];
println!( "{:p}", &vec1[ .. ] );
let mut buff = Cursor::new( vec1 );
let vec2 = &buff.into_inner();
println!( "{:p}", &vec2[ .. ] ); That code does not allocate unnecessary memory. |
Might be useful: |
Hi. I have input data in a raw buffer. I am doing this:
I would like to achieve zero-copy solution. Is that possible/planned with the wonderful library?
The text was updated successfully, but these errors were encountered: