Git Product home page Git Product logo

pinus's Introduction

pinus

Lib.rs Crates.io Docs.rs

Rust 1.55 CI Crates.io - License

GitHub open issues open pull requests good first issues

crev reviews

A prickly BTreeMap.

  • You can insert through shared references and values are pin-projected.
  • You can remove keys and drop entries through exclusive references.
  • You can remove values through exclusive references until the PineMap is pinned.

This container API is fine ☕🐕, but it's still fully usable without directly referencing that crate.

This crate goes together well with fruit-salad 🥗

Help wanted!

I need only a fairly barebones implementation and not necessarily optimized version of this data structure for my own project(s), but am committed to maintaining it into shape if there's interest.

Follow the "good first issues" badge above for starting points!

Note that the crate uses unsafe code very frequently, so you should be at least somewhat comfortable with ensuring soundness manually. Code reviews are also highly appreciated, both within and outside of this regard.

Installation

Please use cargo-edit to always add the latest version of this library:

cargo add pinus

Examples

Homogeneous Map

use pinus::{prelude::*, sync::PineMap};
use std::{convert::Infallible, pin::Pin};
use this_is_fine::prelude::*;

// `PineMap` is interior-mutable, so either is useful:
let map = PineMap::new();
let mut mut_map = PineMap::new();


// Get parallel shared references by inserting like this:
let a: &String = map.insert("Hello!", "Hello!".to_string())
  .unwrap(/* Your data back if the entry already existed. */);
let b: &String = map.insert_with("Hello again!", |k| k.to_string())
  .map_err(|(key, _factory)| key).unwrap();
let c: &String = map.try_insert_with::<_, Infallible>("Hello once again!", |k| Ok(k.to_string()))
  .unwrap(/* Error from factory. */)
  .map_err(|(key, _factory)| key).unwrap();

let a2: &String = map.get("Hello!").unwrap();

let _ = (a, a2, b, c);


// Get exclusive references like this (also with or without factory):
let mut_a: &mut String = mut_map.insert_with_mut("Hi!", |k| k.to_string())
  .map_err(|(key, _factory)| key).unwrap();

let mut_a2: &mut String = mut_map.get_mut("Hi!").unwrap();

// The `…_mut` methods are actually faster, but their results can't be held onto at once:
// let _ = (mut_a, mut_a2); // "error[E0499]: cannot borrow `mut_map` as mutable more than once at a time"


// Remove entries like this:
mut_map.clear();
let _: Option<(&str, String)> = mut_map.remove_pair("A");
let _: Option<String> = mut_map.remove_value("B");
let _: Option<&str> = mut_map.remove_key("C");
let _: bool = mut_map.drop_entry("D");


/////


// Now on to part 2, value pinning:
let mut map: Pin<_> = map.pin();
let mut mut_map: Pin<_> = mut_map.pin();


// Shared references to values are now pinned:
let a: Pin<&String> = map.insert("Hello!!", "Hello!!".to_string())
  .unwrap();
let b: Pin<&String> = map.insert_with("Hello again!!", |k| k.to_string())
  .ok().unwrap();
let c: Pin<&String> = map.try_insert_with::<_, Infallible>("Hello once again!!", |k| Ok(k.to_string()))
  .unwrap().ok().unwrap();

let a2: Pin<&String> = map.get("Hello!").unwrap();

let _ = (a, a2, b, c);


// Exclusive references to values are also pinned:
let mut mut_a: Pin<&mut String> = mut_map.insert_with_mut("Hi!", |k| k.to_string())
  .map_err(|(key, _factory)| key).unwrap();

let mut mut_a2: Pin<&mut String> = mut_map.get_mut("Hi!").unwrap();

// The `…_mut` methods are actually faster, but their results can't be held onto at once:
// let _ = (mut_a, mut_a2); // "error[E0499]: cannot borrow `mut_map` as mutable more than once at a time"

// Only keys can be removed now, but values must be dropped in place:
mut_map.clear();
let _: Option<&str> = mut_map.remove_key("C");
let _: bool = mut_map.drop_entry("D");

Heterogeneous Map

use pinus::{prelude::*, sync::PressedPineMap};
use std::{
  any::Any,
  borrow::{Borrow, BorrowMut},
  convert::Infallible,
  pin::Pin,
};
use this_is_fine::prelude::*;

let map = PressedPineMap::<_, dyn Any>::new();

// `dyn Any` is `!Sized`,
// so it's necessary to use the loosely-typed emplacement methods:
let _: &dyn Any = map
  .emplace_with(1, |_key, slot| slot.write(()))
  .ok(/* or key and factory */).unwrap();
let _: &dyn Any = map
  .try_emplace_with::<_, Infallible>(2, |_key, slot| Ok(slot.write(())))
  .unwrap(/* or factory error */)
  .ok(/* or key and factory */).unwrap();

// There's also a by-value method,
// but it has slightly steeper requirements:
#[derive(Debug)]
struct MyAny;
impl std::borrow::Borrow<dyn Any> for MyAny { //…
#   fn borrow(&self) -> &dyn Any { self }
# }
impl std::borrow::BorrowMut<dyn Any> for MyAny { //…
#   fn borrow_mut(&mut self) -> &mut dyn Any { self }
# }

let _: &dyn Any = map
  .emplace(3, MyAny)
  .unwrap(/* or key and value */);

// As usual the map's values can be pinned:
let map: Pin<PressedPineMap<_, _>> = map.pin();

// And then further value references are pinned:
let _: Pin<&dyn Any> = map.emplace(4, MyAny).unwrap();

// To immediately get an unpinned reference, just use `.as_unpinned()`:
let _: &dyn Any = map.as_unpinned().emplace(5, MyAny).unwrap();

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

See CONTRIBUTING for more information.

Versioning

pinus strictly follows Semantic Versioning 2.0.0 with the following exceptions:

  • The minor version will not reset to 0 on major version changes (except for v1).
    Consider it the global feature level.
  • The patch version will not reset to 0 on major or minor version changes (except for v0.1 and v1).
    Consider it the global patch level.

This includes the Rust version requirement specified above.
Earlier Rust versions may be compatible, but this can change with minor or patch releases.

Which versions are affected by features and patches can be determined from the respective headings in CHANGELOG.md.

Note that dependencies of this crate may have a more lenient MSRV policy! Please use cargo +nightly update -Z minimal-versions in your automation if you don't generate Cargo.lock manually (or as necessary) and require support for a compiler older than current stable.

pinus's People

Contributors

dependabot[bot] avatar tamschi avatar

Watchers

 avatar  avatar  avatar

Forkers

scribe

pinus's Issues

`!Sync` implementation

Is your feature request related to a problem? Please describe.

Right now, only a thread-safe implementation of the data structures exists.
It would make sense for this crate to also provide a thread-unsafe version that can function without synchronisation primitives.

Describe the solution you'd like

The code in https://github.com/Tamschi/pinus/blob/develop/src/sync.rs should be copied to another module (unsync.rs?), attached to lib.rs and adjusted to contain no locking primitives and such. It should otherwise function identically.

Describe alternatives you've considered

Once GATs land, it will be possible to abstract over thread-safety instead. However, this is still some ways off.

Additional context

None.

Please check for soundness issues!

This crate hasn't been "peer-reviewed" yet. Since it's full of unsafe, I'd appreciate additional opinions even more than usual.
(I can add // SAFETY comments to unsafe blocks if that would be helpful.)

I'd also really appreciate some advice on testing the crate more thoroughly for soundness issues.

`Clone` implementations

Is your feature request related to a problem? Please describe.

It should be possible to clone the collections (into their unpinned forms) whenever both keys and values can also be cloned.

Describe the solution you'd like

This Clone implementation should be recursive into those of the keys and values.

The internal Bump can't be cloned directly (and such a feature is impossible there, due to pointer comparison issues), so all entries must be cloned into the new allocation one-by-one.
It should be possible to optimise the initial allocation size somewhat, though.

Describe alternatives you've considered

None.

Additional context

This may partially conflict with leaking values into the collection.
However, cloning seems more important.

Please check for pinning and unwind safety issues!

I'm quite sure that pinning is handled correctly during normal operation, but haven't looked into whether the behaviour is sound iff a Drop::drop panic happens.

I should most likely aggressively try to clean out the rest of the values iff a panic occurs during .drop() or .clear(), maybe resume unwinding with a compound panic where applicable… and the allocation can be freed there too, since an instance is considered dropped even if it panics like that.

(Better) Panic (and Err) Handlers

Right now, some memory is wasted when a panic occurs while trying to insert a value, at least in some case. A panic handler could undo the last allocation and then resume unwinding.

The same goes for plain errors, which aren't handled in all cases I think.

`.remove…unchecked`, `.drop_entry_unchecked` and `.clear_unchecked` methods

Tree entries could still be unsafely removed through shared references by taking out a write lock, but I personally don't need that functionality (so far).

It's in theory also possible to avoid poisoning the collection if a panic occurs during Drop::drop, for keys and for values that aren't pinned or are Unpin. (Reusing the memory of a pinned !Unpin that wasn't dropped seems like a bad idea, but I haven't read up on that in particular.)

`Debug` implementations

Is your feature request related to a problem? Please describe.

This is a common trait that should be available here, but I forgot.

Describe the solution you'd like

A normal Debug implementation, similar to matching standard library types.

Describe alternatives you've considered

None.

Additional context

This is a requirement for adding the same feature to rhizome.

Entry access

Is your feature request related to a problem? Please describe.

It may eventually become necessary to manipulate entries through a low-level interface that avoid repeat look-ups when replacing values and should allow one to "leak" an entry's value into the collection, freeing the key without dropping the value. (Tentative API: OccupiedEntry::split(self) -> (VacantEntry::<'tag>, ValueHandle<V>), ValueHandle::<'tag>::seep(self) -> &mut V, with lifetime extensions to be done by the caller outside of using the reference in a new value for the same entry.)

Describe the solution you'd like

This should be a fairly thorough in-place entry manipulation API, similarly to what other map container types offer.

Describe alternatives you've considered

It would be possible to "seep" values without going to the entry API,
but this would expose that fairly tricky low-level API too easily in my opinion.

Additional context

This could be useful for debugging Asteracea apps, since the DI chain could be shimmed fully transparently this way. That API probably shouldn't be exposed outside of debug tooling, though.

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.