collect_into_rc_slice

Crates.iocollect_into_rc_slice
lib.rscollect_into_rc_slice
version1.0.0
sourcesrc
created_at2023-08-02 18:10:16.03791
updated_at2023-08-02 18:10:16.03791
descriptionA crate that let's you collect an `Iterator` into an `Rc<[T]>` or `Arc<[T]>` without needing to make 2 heap allocations.
homepage
repositoryhttps://github.com/Markos-Th09/collect_into_rc_slice
max_upload_size
id932966
size24,550
(Markos-Th09)

documentation

README

collect_into_rc_slice

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.

Important Note

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()

The Problem

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

Solution

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();

Safety

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

Commit count: 6

cargo fmt