Crates.io | collect_into_rc_slice |
lib.rs | collect_into_rc_slice |
version | 1.0.0 |
source | src |
created_at | 2023-08-02 18:10:16.03791 |
updated_at | 2023-08-02 18:10:16.03791 |
description | A crate that let's you collect an `Iterator |
homepage | |
repository | https://github.com/Markos-Th09/collect_into_rc_slice |
max_upload_size | |
id | 932966 |
size | 24,550 |
A crate that let's you collect an Iterator<Item=T>
into an Rc<[T]>
or Arc<[T]>
without needing to make 2 heap allocations.
Please DO NOT use this if you already have a Vec<T>
, sString
or &[T]
that contains the exact block memory you are trying convert to Rc<[T]>
.
It wouldn't do anything better than the std
implementation. It always better to use .into()
in this case.
For example
use std::rc::Rc;
let v = vec![1,2,3];
let rc: Rc<[i32]> = v.into(); // Just use .into()
You just learned about how cool using Rc<[T]>
can be and you have an Iterator<Item=char>
and you want to collect it to Rc<str>
One could naively do it as:
use std::rc::Rc;
let iter = "Hello, world!".chars();
let rc: Rc<str> = iter.collect::<String>().into();
Which makes 2 seperate heap allocations, one for String
and another one for Rc
It is very possible to do this with only 1 heap allocation, however it requires the usage of unsafe code, and good knowledge of the internal data structure of the smart pointers
With this crate you can avoid another heap allocation:
use collect_into_rc_slice::*;
use std::rc::Rc;
let iter = "Hello, world!".chars(); // Some iterator
let rc: Rc<str> = iter.collect_into_rc_str();
This crate utilizes unsafe code to create a safe abstraction. To ensure that it is safe, it is tested, and uses miri to identify possible undefined behavior