Skip to content

Commit

Permalink
#69 MaybeUninit for each array item
Browse files Browse the repository at this point in the history
  • Loading branch information
yegor256 committed Apr 25, 2023
1 parent cea2092 commit 0c81995
Show file tree
Hide file tree
Showing 8 changed files with 89 additions and 30 deletions.
1 change: 1 addition & 0 deletions .github/workflows/cargo.yml
Expand Up @@ -18,6 +18,7 @@ jobs:
with:
toolchain: stable
- run: cargo --color=never test --all-features -vv -- --nocapture
- run: cargo --color=never test --release --all-features -vv -- --nocapture
- run: cargo --color=never fmt --check
- run: cargo --color=never doc --no-deps
- run: cargo --color=never clippy -- --no-deps
1 change: 1 addition & 0 deletions .rultor.yml
Expand Up @@ -16,6 +16,7 @@ release:
sed -i -e "s/^version = \"0.0.0\"/version = \"${tag}\"/" Cargo.toml
sed -i -e "s/0.0.0/${tag}/" src/lib.rs
cargo --color=never test --all-features -vv -- --nocapture
cargo --color=never test --release --all-features -vv -- --nocapture
cargo --color=never fmt --check
cargo --color=never clippy -- --no-deps
git commit -am "${tag}"
Expand Down
5 changes: 1 addition & 4 deletions README.md
Expand Up @@ -65,8 +65,6 @@ the numbers over 1.0 indicate performance gain,
while the numbers below 1.0 demonstrate performance loss.

<!-- benchmark -->
| | 2 | 4 | 8 | 16 | 32 | 64 | 128 |
| --- | --: | --: | --: | --: | --: | --: | --: |
| `hashbrown::HashMap` | 18.04 | 3.79 | 2.34 | 1.44 | 0.67 | 0.30 | 0.17 |
| `indexmap::IndexMap` | 14.77 | 6.44 | 4.30 | 2.42 | 1.44 | 0.63 | 0.35 |
| `linear_map::LinearMap` | 2.50 | 0.76 | 0.65 | 0.60 | 0.63 | 0.65 | 0.63 |
Expand All @@ -79,10 +77,9 @@ while the numbers below 1.0 demonstrate performance loss.
| `std::collections::HashMap` | 46.50 | 6.26 | 3.98 | 2.38 | 1.35 | 0.62 | 0.36 |
| `tinymap::array_map::ArrayMap` | 1.21 | 2.26 | 2.23 | 2.26 | 2.64 | 2.37 | 2.52 |

The experiment was performed on 24-04-2023.
The experiment was performed on 25-04-2023.
There were 1000000 repetition cycles.
The entire benchmark took 385s.

<!-- benchmark -->

As you see, the highest performance gain was achieved for the maps that were smaller than ten keys.
Expand Down
43 changes: 43 additions & 0 deletions src/clone.rs
@@ -0,0 +1,43 @@
// Copyright (c) 2023 Yegor Bugayenko
//
// 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 NON-INFRINGEMENT. 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.

use crate::Map;

impl<K: Clone + PartialEq, V: Clone, const N: usize> Clone for Map<K, V, N> {
fn clone(&self) -> Self {
let mut m: Self = Self::new();
for (k, v) in self.iter() {
m.insert(k.clone(), v.clone());
}
m
}
}

#[cfg(test)]
use anyhow::Result;

#[test]
#[ignore]
fn map_can_be_cloned() -> Result<()> {
let mut m: Map<u8, u8, 16> = Map::new();
m.insert(0, 42);
assert_eq!(42, *m.clone().get(&0).unwrap());
Ok(())
}
10 changes: 8 additions & 2 deletions src/ctors.rs
Expand Up @@ -21,7 +21,7 @@
use crate::{Map, Pair};
use std::mem::MaybeUninit;

impl<K: PartialEq, V: Clone, const N: usize> Map<K, V, N> {
impl<K: Clone + PartialEq, V: Clone, const N: usize> Map<K, V, N> {
/// Make it.
#[inline]
#[must_use]
Expand All @@ -30,7 +30,7 @@ impl<K: PartialEq, V: Clone, const N: usize> Map<K, V, N> {
unsafe {
Self {
next: 0,
pairs: MaybeUninit::<[Pair<K, V>; N]>::uninit().assume_init(),
pairs: MaybeUninit::<[MaybeUninit<Pair<K, V>>; N]>::uninit().assume_init(),
}
}
}
Expand All @@ -45,3 +45,9 @@ fn makes_new_map() -> Result<()> {
assert_eq!(0, m.len());
Ok(())
}

#[test]
fn drops_correctly() -> Result<()> {
let _m: Map<Vec<u8>, u8, 8> = Map::new();
Ok(())
}
9 changes: 5 additions & 4 deletions src/iterators.rs
Expand Up @@ -27,7 +27,8 @@ impl<'a, K: Clone, V: Clone, const N: usize> Iterator for Iter<'a, K, V, N> {
#[must_use]
fn next(&mut self) -> Option<Self::Item> {
while self.pos < self.next {
if let Present(p) = &self.pairs[self.pos] {
let p = unsafe { self.pairs[self.pos].assume_init_ref() };
if let Present(p) = p {
self.pos += 1;
return Some((&p.0, &p.1));
}
Expand All @@ -44,10 +45,10 @@ impl<'a, K: Clone, V: Clone, const N: usize> Iterator for IntoIter<'a, K, V, N>
#[must_use]
fn next(&mut self) -> Option<Self::Item> {
while self.pos < self.next {
if self.pairs[self.pos].is_some() {
let pair = self.pairs[self.pos].clone().unwrap();
let p = unsafe { self.pairs[self.pos].assume_init_ref() };
if p.is_some() {
self.pos += 1;
return Some(pair);
return Some(p.clone().unwrap());
}
self.pos += 1;
}
Expand Down
13 changes: 7 additions & 6 deletions src/lib.rs
Expand Up @@ -45,6 +45,7 @@
#![allow(clippy::multiple_inherent_impl)]
#![allow(clippy::multiple_crate_versions)]

mod clone;
mod ctors;
mod debug;
mod eq;
Expand All @@ -57,7 +58,7 @@ mod pair;
mod serialization;

/// A pair in the Map.
#[derive(Clone, Default, Copy, Eq, PartialEq)]
#[derive(Clone, Default, Eq, PartialEq)]
enum Pair<K, V> {
Present((K, V)),
#[default]
Expand All @@ -72,28 +73,28 @@ enum Pair<K, V> {
/// because it doesn't use heap. When a [`Map`] is being created, it allocates the necessary
/// space on stack. That's why the maximum size of the map must be provided in
/// compile time.
#[derive(Clone, Copy)]
pub struct Map<K: PartialEq, V: Clone, const N: usize> {
pub struct Map<K: Clone + PartialEq, V: Clone, const N: usize> {
next: usize,
pairs: [Pair<K, V>; N],
pairs: [MaybeUninit<Pair<K, V>>; N],
}

/// Iterator over the [`Map`].
pub struct Iter<'a, K, V, const N: usize> {
next: usize,
pos: usize,
pairs: &'a [Pair<K, V>; N],
pairs: &'a [MaybeUninit<Pair<K, V>>; N],
}

/// Into-iterator over the [`Map`].
pub struct IntoIter<'a, K, V, const N: usize> {
next: usize,
pos: usize,
pairs: &'a [Pair<K, V>; N],
pairs: &'a [MaybeUninit<Pair<K, V>>; N],
}

#[cfg(test)]
use simple_logger::SimpleLogger;
use std::mem::MaybeUninit;

#[cfg(test)]
use log::LevelFilter;
Expand Down
37 changes: 23 additions & 14 deletions src/map.rs
Expand Up @@ -21,8 +21,9 @@
use crate::Pair::{Absent, Present};
use crate::{IntoIter, Iter, Map};
use std::borrow::Borrow;
use std::mem::MaybeUninit;

impl<K: PartialEq, V: Clone, const N: usize> Default for Map<K, V, N> {
impl<K: Clone + PartialEq, V: Clone, const N: usize> Default for Map<K, V, N> {
fn default() -> Self {
Self::new()
}
Expand Down Expand Up @@ -64,7 +65,8 @@ impl<K: PartialEq + Clone, V: Clone, const N: usize> Map<K, V, N> {
pub fn len(&self) -> usize {
let mut busy = 0;
for i in 0..self.next {
if self.pairs[i].is_some() {
let p = unsafe { self.pairs[i].assume_init_ref() };
if p.is_some() {
busy += 1;
}
}
Expand All @@ -75,7 +77,8 @@ impl<K: PartialEq + Clone, V: Clone, const N: usize> Map<K, V, N> {
#[inline]
pub fn contains_key(&self, k: &K) -> bool {
for i in 0..self.next {
if let Present((bk, _bv)) = &self.pairs[i] {
let p = unsafe { self.pairs[i].assume_init_ref() };
if let Present((bk, _bv)) = &p {
if bk == k {
return true;
}
Expand All @@ -88,9 +91,10 @@ impl<K: PartialEq + Clone, V: Clone, const N: usize> Map<K, V, N> {
#[inline]
pub fn remove(&mut self, k: &K) {
for i in 0..self.next {
if let Present((bk, _bv)) = &self.pairs[i] {
let p = unsafe { self.pairs[i].assume_init_ref() };
if let Present((bk, _bv)) = &p {
if bk == k {
self.pairs[i] = Absent;
self.pairs[i] = MaybeUninit::new(Absent);
break;
}
}
Expand All @@ -106,13 +110,14 @@ impl<K: PartialEq + Clone, V: Clone, const N: usize> Map<K, V, N> {
pub fn insert(&mut self, k: K, v: V) {
self.remove(&k);
for i in 0..self.next {
if !self.pairs[i].is_some() {
self.pairs[i] = Present((k, v));
let p = unsafe { self.pairs[i].assume_init_ref() };
if !p.is_some() {
self.pairs[i] = MaybeUninit::new(Present((k, v)));
return;
}
}
if self.next < N {
self.pairs[self.next] = Present((k, v));
self.pairs[self.next] = MaybeUninit::new(Present((k, v)));
self.next += 1;
return;
}
Expand All @@ -127,7 +132,8 @@ impl<K: PartialEq + Clone, V: Clone, const N: usize> Map<K, V, N> {
K: Borrow<Q>,
{
for i in 0..self.next {
if let Present(p) = &self.pairs[i] {
let p = unsafe { self.pairs[i].assume_init_ref() };
if let Present(p) = &p {
if p.0.borrow() == k {
return Some(&p.1);
}
Expand All @@ -148,9 +154,11 @@ impl<K: PartialEq + Clone, V: Clone, const N: usize> Map<K, V, N> {
K: Borrow<Q>,
{
for i in 0..self.next {
if let Present(p) = &mut self.pairs[i] {
if p.0.borrow() == k {
return Some(&mut self.pairs[i].as_mut().unwrap().1);
let p = unsafe { self.pairs[i].assume_init_ref() };
if let Present(p1) = &p {
if p1.0.borrow() == k {
let p2 = unsafe { self.pairs[i].assume_init_mut() };
return Some(&mut p2.as_mut().unwrap().1);
}
}
}
Expand All @@ -167,9 +175,10 @@ impl<K: PartialEq + Clone, V: Clone, const N: usize> Map<K, V, N> {
#[inline]
pub fn retain<F: Fn(&K, &V) -> bool>(&mut self, f: F) {
for i in 0..self.next {
if let Present((k, v)) = &self.pairs[i] {
let p = unsafe { self.pairs[i].assume_init_ref() };
if let Present((k, v)) = &p {
if !f(k, v) {
self.pairs[i] = Absent;
self.pairs[i] = MaybeUninit::new(Absent);
}
}
}
Expand Down

0 comments on commit 0c81995

Please sign in to comment.