Giter Club home page Giter Club logo

recycle_vec's Introduction

recycle_vec

Note: There used to be an RFC for making this functionality a part of the standard library. However, it was closed because 1) an additional API as little as this doesn't need a full RFC anymore 2) but the capabilities of the language around checking invariants statically aren't there yet, so the API would be suboptimal and therefore it's best to wait for the const generics and static checking stuff to catch up.

This crate provides a recycle extension method for Vec. It's intended to change the type of the Vec while "recycling" the underlying allocation. This is a trick that is useful especially when storing data with short lifetimes in Vec:

    let mut objects: Vec<Object<'static>> = Vec::new();

    while let Some(byte_chunk) = stream.next() { // byte_chunk only lives this scope
        let mut objects_temp: Vec<Object<'_>> = objects.recycle();

        // Zero-copy parsing; Object has references to chunk
        deserialize(byte_chunk, &mut objects_temp)?;
        process(&objects_temp)?;

        objects = objects_temp.recycle();
    } // byte_chunk lifetime ends

Notes about safety

This crate uses internally unsafe to achieve it's functionality. However, it provides a safe interface. To achieve safety, it does the following precautions:

  1. It truncates the Vec to zero length, dropping all the values. This ensures that no values of arbitrary types are transmuted accidentally.
  2. It checks that the sizes and alignments of the source and target types match. This ensures that the underlying block of memory backing Vec is compatible layout-wise. The sizes and alignments are checked statically, so if the compile will fail in case of a mismatch.
  3. It creates a new Vec value using from_raw_parts instead of transmuting, an operation whose soundness would be questionable.

recycle_vec's People

Contributors

golddranks avatar ten0 avatar

Stargazers

Felipe S. S. Schneider avatar  avatar

Watchers

James Cloos avatar  avatar  avatar

recycle_vec's Issues

Compile time asserts

When const_panic first stabilized, it didn't seem to be applicable for checking properties of generics, since const items inside functions can't be tied to the generics. However, an associated const on a struct seems to do the trick:

use std::mem::{align_of, size_of};

struct AssertSameLayout<A, B>(std::marker::PhantomData<(A, B)>);
impl<A, B> AssertSameLayout<A, B> {
    const OK: () = assert!(
        size_of::<A>() == size_of::<B>() && align_of::<A>() == align_of::<B>(),
        "types must have identical size and alignment"
    );
}

// used as
() = AssertSameLayout::<A, B>::OK;

Playground

Idea stolen from here.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.