Browse Source

added shim primitives

master
Avril 2 years ago
parent
commit
9eada00990
Signed by: flanchan
GPG Key ID: 284488987C31F630
  1. 3
      Cargo.toml
  2. 12
      src/lib.rs
  3. 70
      src/primitive.rs
  4. 15
      src/space.rs

3
Cargo.toml

@ -4,13 +4,12 @@ description = "Small byte-sized generic key-value map type"
keywords = ["map", "table", "small", "key", "value"]
repository = "https://github.com/notflan/smallmap"
homepage= "https://git.flanchan.moe/flanchan/smallmap"
version = "1.2.1"
version = "1.3.0"
authors = ["Avril <flanchan@cumallover.me>"]
edition = "2018"
license = "MIT"
[dependencies]
const_fn = "0.4.4"
serde = {version = "1.0.116", features = ["derive"], optional = true}
[dev-dependencies]

12
src/lib.rs

@ -33,8 +33,6 @@
#![cfg_attr(nightly, feature(never_type))]
#[cfg(nightly)] extern crate test;
#[macro_use] extern crate const_fn;
const MAX: usize = 256;
@ -45,7 +43,10 @@ use iter::*;
pub mod entry;
pub use entry::Entry;
pub mod space;
pub mod primitive;
pub use primitive::Primitive;
mod init;
@ -53,6 +54,13 @@ mod private {
pub trait Sealed{}
}
/// A smallmap set.
///
/// Can be used to quickly insert or remove a key only, with no value; and can be used to see if this key is present.
///
/// Any map type with a zero-sized value is essentially a set.
pub type Set<T> = Map<T,()>;
/// A helper macro for creating `Map` instances with or without pre-set entries.
///
/// # Create empty map

70
src/primitive.rs

@ -1,16 +1,42 @@
//! Contains `Collapse` impls for primitive types through a newtime wrapper.
//!
//! Contains `Collapse` impls for primitive types through a newtime shim.
//!
//! # Why
//! Such wrappers are a workaround for the lack of template specialisation available in Rust so far, as the generic `impl<T: Hash> Collapse<T> for T` still requires computing the hash of the internal types before reducing to the `u8` page index.
//! For primitive types, this is unnessisary and causes a (very slight) performance loss.
//!
//! If/when Rust gets specialisation, this will be unneeded.
use super::*;
use std::num::*;
/// Sealed trait allowing for wrapping primitive types with a more efficient implemntation for the `Collapse` trait.
/// This should not be used for much directly, instead use the newtype shim `Primitive<T>`.
pub trait PrimitiveCollapse: private::Sealed
{
fn collapse(&self) -> u8;
}
/// Shim for primitive types to efficiently implement `Collapse`.
///
/// # Notes
/// This newtype is transparent. It is safe to `mem::transmute`() from `Primitive<T>` to `T` and vice versa.
/// However, if `T` does *not* implement `PrimitiveCollapse`, it is undefined behaviour.
///
/// Also, the `collapse()` output from this structure is not guaranteed to be the same as the `collapse()` output from the inner value, so the following code is very unsafe and such patterns should only be used if the programmer is absolutely sure there will be absolutely no difference between `T::collapse` and `Self::collapse`:
/// ```
/// # use smallmap::{Map, Primitive};
/// # use std::mem;
///
/// let mut map: Map<u8, ()> = Map::new();
/// map.insert(120, ());
///
/// let map: Map<Primitive<u8>, ()> = unsafe { mem::transmute(map) };
/// assert_eq!(map.get(&120.into()).copied(), Some(()));
/// ```
/// This code pretty much only works with `u8`. and `i8`.
///
/// However unsafe, it is possible these values will line up in your use case. In which case, it is an acceptable pattern.
#[derive(Debug, Clone, PartialEq, Eq, Copy, Default, Ord, PartialOrd)]
#[repr(transparent)]
pub struct Primitive<T>(T);
impl<T: PrimitiveCollapse+ Eq> Collapse for Primitive<T>
@ -22,32 +48,62 @@ impl<T: PrimitiveCollapse+ Eq> Collapse for Primitive<T>
impl<T: PrimitiveCollapse+ Eq> Primitive<T>
{
#[const_fn]
#[inline] pub const fn new(value: T) -> Self
/// Wrap this primitive
#[cfg(nightly)] #[inline] pub const fn new(value: T) -> Self
{
Self(value)
}
/// Wrap this primitive
#[cfg(not(nightly))] #[inline] pub fn new(value: T) -> Self
{
Self(value)
}
/// Consume into the inner primitive
#[inline] pub fn into_inner(self) -> T
{
self.0
}
#[const_fn]
/// Get the inner primitive
///
/// # Notes
/// Only useful if the inner type does not implement `Copy`, which is extremely unlickely.
/// You should almost always use `into_inner` instead.
#[inline] pub fn inner(&self) -> &T
{
&self.0
}
/// Get a mutable reference to the inner ptimitive.
#[inline] pub fn inner_mut(&mut self) -> &mut T
{
&mut self.0
}
#[const_fn]
#[inline] pub const fn copy_into_inner(&self) -> T
/// Same as `into_inner`, except only for `Copy` types.
///
/// # Notes
/// The only use of this function is that it is `const fn` on nightly.
/// If you're not using a version of rustc that supports generic `const fn`, this method is identical to `into_inner`.
#[cfg(nightly)] #[inline] pub const fn into_inner_copy(self) -> T
where T: Copy
{
self.0
}
#[cfg(not(nightly))] #[inline(always)] #[deprecated = "This function should only be used on Rust nightly. Please use `into_inner` instead"] pub fn into_inner_copy(self) -> T
where T: Copy
{
self.0
}
}
impl<T> From<T> for Primitive<T>
where T: PrimitiveCollapse + Eq
{
#[inline] fn from(from: T) -> Self
{
Self::new(from)
}
}
macro_rules! prim {
($name:ty) => {
impl private::Sealed for $name{}

15
src/space.rs

@ -0,0 +1,15 @@
//! Space-efficient small maps and sets
//!
//! To make an entirely space efficient `Map` (i.e. size of each page is 256 bytes, there is never more than 1 page), the following must be true:
//!
//! * The key must be 8 bits wide and subject to the *null pointer optimisation*
//! * The value must be a ZST.
//!
//! This leaves pretty much only `NonZeroU8` and `NonZeroI8` as entirely space-efficient key candidates.
//! The restriction on values also means the only entirely space-efficient smallmaps are sets, enable to encode only if a key is present, with no extra information. (See `std::collections::HashSet`).
use super::*;
/// A set of only non-zero bytes.
///
/// This type is entirely space efficient and will only ever allocate `256` bytes of memory.
pub type NonZeroByteSet = Map<std::num::NonZeroU8, ()>;
Loading…
Cancel
Save