Skip to content

Commit

Permalink
Initial Commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Dav1dde committed Mar 3, 2024
0 parents commit f9baa74
Show file tree
Hide file tree
Showing 8 changed files with 913 additions and 0 deletions.
47 changes: 47 additions & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
on: [workflow_dispatch, push, pull_request]

name: CI

jobs:
test:
name: Test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: stable
override: true
- uses: Swatinem/rust-cache@v1
- uses: actions-rs/cargo@v1
with:
command: test
args: --all-features

fmt:
name: Rustfmt
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: nightly
components: rustfmt
override: true
- run: cargo +nightly fmt --all -- --check

clippy:
name: Clippy
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: stable
components: clippy
override: true
- uses: Swatinem/rust-cache@v1
- run: cargo clippy --all-features -- -D warnings
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/target
Cargo.lock
*.swp
18 changes: 18 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
[package]
name = "enumap"
version = "0.1.0"
authors = ["David Herberth <github@dav1d.de>"]
description = "A hashmap like interface for enums backed by an array"
license = "MIT OR Apache-2.0"
keywords = ["data-structure", "enum", "no_std"]
categories = ["data-structure", "no_std"]
repository = "https://github.com/Dav1dde/enumap"
edition = "2021"


[dependencies]

# docs.rs-specific configuration
[package.metadata.docs.rs]
all-features = true
rustdoc-args = ["--cfg", "docsrs"]
19 changes: 19 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright (c) 2024, David Herberth.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
63 changes: 63 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
EnuMap
=======

[![Crates.io][crates-badge]][crates-url]
[![License][license-badge]][license-url]
[![Build Status][actions-badge]][actions-url]
[![docs.rs][docsrs-badge]][docsrs-url]

[crates-badge]: https://img.shields.io/crates/v/enumap.svg
[crates-url]: https://crates.io/crates/enumap
[license-badge]: https://img.shields.io/crates/l/enumap.svg
[license-url]: https://github.com/Dav1dde/enumap/blob/master/LICENSE
[actions-badge]: https://github.com/Dav1dde/enumap/workflows/CI/badge.svg
[actions-url]: https://github.com/Dav1dde/enumap/actions?query=workflow%3ACI+branch%3Amaster
[docsrs-badge]: https://img.shields.io/docsrs/enumap
[docsrs-url]: https://docs.rs/enumap


HashMap like interface for enumerations backed by an array.

`enumap` is `no_std` compatible, dependency and proc macro free for blazingly fast compilation speeds.


## Usage

This crate is [on crates.io](https://crates.io/crates/enumap) and can be
used by adding it to your dependencies in your project's `Cargo.toml`.

```toml
[dependencies]
enumap = "0.1"
```

## Example

```rust
use enumap::EnumMap;

enumap::enumap! {
/// A beautiful fruit, ready to be sold.
#[derive(Debug)]
enum Fruit {
Orange,
Banana,
Grape,
}
}

// A fruit shop: fruit -> stock.
let mut shop = EnumMap::new();
shop.insert(Fruit::Orange, 100);
shop.insert(Fruit::Banana, 200);

for (fruit, amount) in &shop {
println!("There are {amount} {fruit:?}s in stock!");
}

if !shop.contains_key(Fruit::Grape) {
println!("Sorry no grapes in stock :(");
}
```

Browse the docs for more examples!
91 changes: 91 additions & 0 deletions src/enum_macro.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
/// Lightweight macro to automatically implement [`Enum`](crate::Enum).
///
/// The macro automatically implements [`Enum`](crate::Enum), it works only
/// on data less enums and automatically derives `Copy` and `Clone`.
///
/// # Example:
///
/// ```
/// use enumap::EnumMap;
///
/// enumap::enumap! {
/// /// A beautiful fruit, ready to be sold.
/// #[derive(Debug, PartialEq, Eq)]
/// enum Fruit {
/// Orange,
/// Banana,
/// Grape,
/// }
/// }
///
/// // A fruit shop: fruit -> stock.
/// let mut shop = EnumMap::new();
/// shop.insert(Fruit::Orange, 100);
/// shop.insert(Fruit::Banana, 200);
/// shop.insert(Fruit::Grape, 300);
///
/// assert_eq!(
/// shop.into_iter().collect::<Vec<_>>(),
/// vec![(Fruit::Orange, 100), (Fruit::Banana, 200), (Fruit::Grape, 300)],
/// );
///
/// // Oranges out of stock:
/// shop.remove(Fruit::Orange);
///
/// assert_eq!(
/// shop.into_iter().collect::<Vec<_>>(),
/// vec![(Fruit::Banana, 200), (Fruit::Grape, 300)],
/// );
/// # use enumap::Enum;
/// # assert_eq!(Fruit::to_index(Fruit::Orange), 0);
/// # assert_eq!(Fruit::to_index(Fruit::Banana), 1);
/// # assert_eq!(Fruit::to_index(Fruit::Grape), 2);
/// # assert!(matches!(Fruit::from_index(0), Some(Fruit::Orange)));
/// # assert!(matches!(Fruit::from_index(1), Some(Fruit::Banana)));
/// # assert!(matches!(Fruit::from_index(2), Some(Fruit::Grape)));
/// # assert!(matches!(Fruit::from_index(3), None));
/// ```
#[macro_export]
macro_rules! enumap {
(
$(#[$($attr:tt)*])*
$vis:vis enum $name:ident {
$(
$(#[$($vattr:tt)*])*
$v:ident
),* $(,)?
}
) =>{
$(#[$($attr)*])*
#[derive(Copy, Clone)]
$vis enum $name {
$(
$(#[$($vattr)*])*
$v,
)*
}

impl $crate::Enum<{ 0 $(+ $crate::__replace_expr!($v 1))* }> for $name {
#[allow(unused_variables)]
fn from_index(index: usize) -> Option<Self> {
$(
if index == 0 { return Some(Self::$v); }
let index = index - 1;
)*
None
}

fn to_index(value: Self) -> usize {
value as usize
}
}
};
}

#[doc(hidden)]
#[macro_export]
macro_rules! __replace_expr {
($_t:tt $sub:expr) => {
$sub
};
}
124 changes: 124 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
//! HashMap like interface for enumerations backed by an array.
//!
//! `enumap` is `no_std` compatible and proc macro free for fast compilation speeds.
//!
//! ```
//! use enumap::EnumMap;
//!
//! enumap::enumap! {
//! /// A beautiful fruit, ready to be sold.
//! #[derive(Debug)]
//! enum Fruit {
//! Orange,
//! Banana,
//! Grape,
//! }
//! }
//!
//! // A fruit shop: fruit -> stock.
//! let mut shop = EnumMap::new();
//! shop.insert(Fruit::Orange, 100);
//! shop.insert(Fruit::Banana, 200);
//!
//! for (fruit, amount) in &shop {
//! println!("There are {amount} {fruit:?}s in stock!");
//! }
//!
//! if !shop.contains_key(Fruit::Grape) {
//! println!("Sorry no grapes in stock :(");
//! }
//! ```
//!
//! # Implementing Enum
//!
//! While the crate was built with enums in mind, it is just a generic map
//! implementation backed by an array which only requires a bijective mapping
//! of items to an array index.
//!
//! ```
//! use enumap::{Enum, EnumMap};
//!
//! #[derive(Copy, Clone)]
//! struct ZeroToTen(u8);
//!
//! impl ZeroToTen {
//! fn new(num: u8) -> Option<Self> {
//! matches!(num, 0..=9).then_some(Self(num))
//! }
//! }
//!
//! impl Enum<10> for ZeroToTen {
//! fn from_index(index: usize) -> Option<Self> {
//! index.try_into().ok().and_then(Self::new)
//! }
//!
//! fn to_index(value: Self) -> usize {
//! value.0 as usize
//! }
//! }
//!
//! let zero = ZeroToTen::new(0).unwrap();
//! let five = ZeroToTen::new(5).unwrap();
//! let nine = ZeroToTen::new(9).unwrap();
//!
//! let mut map = EnumMap::from([
//! (zero, "foo"),
//! (nine, "bar"),
//! ]);
//!
//! assert_eq!(map[zero], "foo");
//! assert_eq!(map[nine], "bar");
//! assert_eq!(map.get(five), None);
//! ```
//!
//! # Use Niches
//!
//! The map is backed by an array of options `[Option<V>; N]`,
//! consider using values with a gurantueed niche to optimize the size of the map:
//!
//! ```
//! use enumap::EnumMap;
//! use std::num::NonZeroUsize;
//!
//! enumap::enumap! {
//! #[derive(Debug)]
//! enum Fruit {
//! Orange,
//! Banana
//! }
//! }
//!
//! assert_eq!(std::mem::size_of::<EnumMap<2, Fruit, usize>>(), 32);
//! assert_eq!(std::mem::size_of::<EnumMap<2, Fruit, NonZeroUsize>>(), 16);
//! ```
//!
#![no_std]

mod enum_macro;

pub mod map;

pub use self::map::EnumMap;

/// Enum type, usually implemented using the [`enumap`] macro.
///
/// Any enumeration used by [`EnumMap`] must implement this trait.
///
/// Failures in implementing the trait will not result in undefined behaviour
/// but may result in panics and invalid results.
pub trait Enum<const LENGTH: usize>: Copy + Sized {
/// Length of the enum.
///
/// Equivalent to the const generic length.
const LENGTH: usize = LENGTH;

/// Converts an index to an enum variant.
///
/// Passed `index` must be in range `0..LENGTH`.
fn from_index(index: usize) -> Option<Self>;

/// Converts an enum variant to an index.
///
/// Returned index must be in range `0..LENGTH`.
fn to_index(value: Self) -> usize;
}
Loading

0 comments on commit f9baa74

Please sign in to comment.