Skip to content

no_std support #95

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 1 addition & 6 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,7 @@ language: rust
sudo: false
matrix:
include:
- rust: 1.18.0
before_script:
# lazy_static 1.1 requires Rust 1.21+, so downgrade it.
# (we only use it in benchmarks anyway...)
- cargo generate-lockfile
- cargo update -p lazy_static --precise 1.0.2
- rust: 1.36.0
- rust: stable
env:
- FEATURES='serde-1'
Expand Down
6 changes: 4 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
[package]
name = "indexmap"
version = "1.1.0"
edition = "2018"
authors = [
"bluss",
"Josh Stone <[email protected]>"
Expand Down Expand Up @@ -28,10 +29,11 @@ categories = ["data-structures"]
bench = false

[dependencies]
serde = { version = "1.0", optional = true }
serde = { version = "1.0", optional = true, default-features = false }
hashbrown = "0.6.0"

[dev-dependencies]
itertools = "0.7.0" # 0.8 not compiles on Rust 1.18
itertools = "0.8.0"
rand = "0.4"
quickcheck = { version = "0.6", default-features = false }
fnv = "1.0"
Expand Down
4 changes: 2 additions & 2 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ indexmap
.. |docs| image:: https://docs.rs/indexmap/badge.svg
.. _docs: https://docs.rs/indexmap

.. |rustc| image:: https://img.shields.io/badge/rust-1.18%2B-orange.svg
.. _rustc: https://img.shields.io/badge/rust-1.18%2B-orange.svg
.. |rustc| image:: https://img.shields.io/badge/rust-1.36%2B-orange.svg
.. _rustc: https://img.shields.io/badge/rust-1.36%2B-orange.svg

A safe, pure-Rust hash table which preserves insertion order.

Expand Down
6 changes: 1 addition & 5 deletions benches/bench.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
#![feature(test)]
extern crate test;
extern crate rand;
extern crate fnv;
#[macro_use]
extern crate lazy_static;

Expand All @@ -13,8 +11,6 @@ type FnvBuilder = BuildHasherDefault<FnvHasher>;
use test::Bencher;
use test::black_box;

extern crate indexmap;

use indexmap::IndexMap;

use std::collections::HashMap;
Expand Down Expand Up @@ -580,7 +576,7 @@ fn remove_ordermap_100_000(b: &mut Bencher) {
b.iter(|| {
let mut map = map.clone();
for key in &keys {
map.remove(key).is_some();
let _ = map.remove(key).is_some();
}
assert_eq!(map.len(), 0);
map
Expand Down
4 changes: 0 additions & 4 deletions benches/faststring.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
#![feature(test)]
extern crate test;
extern crate rand;
extern crate lazy_static;

use test::Bencher;

extern crate indexmap;

use indexmap::IndexMap;

use std::collections::HashMap;
Expand Down
2 changes: 1 addition & 1 deletion src/equivalent.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@

use std::borrow::Borrow;
use core::borrow::Borrow;

/// Key equivalence trait.
///
Expand Down
9 changes: 8 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,19 @@
//!
//! ## Rust Version
//!
//! This version of indexmap requires Rust 1.18 or later.
//! This version of indexmap requires Rust 1.36 or later.
//!
//! The indexmap 1.x release series will use a carefully considered version
//! upgrade policy, where in a later 1.x version, we will raise the minimum
//! required Rust version.

#![cfg_attr(not(test), no_std)]

#[cfg(test)]
extern crate core;

extern crate alloc;

#[macro_use]
mod macros;
#[cfg(feature = "serde-1")]
Expand Down
4 changes: 3 additions & 1 deletion src/macros.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@

#[macro_export]
/// Create an `IndexMap` from a list of key-value pairs
///
/// ## Example
///
/// ```
/// # extern crate std;
///
/// #[macro_use] extern crate indexmap;
/// # fn main() {
///
Expand Down Expand Up @@ -43,6 +44,7 @@ macro_rules! indexmap {
/// ## Example
///
/// ```
/// # extern crate std;
/// #[macro_use] extern crate indexmap;
/// # fn main() {
///
Expand Down
69 changes: 37 additions & 32 deletions src/map.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,27 @@
//! `IndexMap` is a hash table where the iteration order of the key-value
//! pairs is independent of the hash values of the keys.

pub use mutable_keys::MutableKeys;

use std::hash::Hash;
use std::hash::BuildHasher;
use std::hash::Hasher;
use std::iter::FromIterator;
use std::collections::hash_map::RandomState;
use std::ops::RangeFull;

use std::cmp::{max, Ordering};
use std::fmt;
use std::mem::{replace};
use std::marker::PhantomData;

use util::{third, ptrdistance, enumerate};
use equivalent::Equivalent;
use {
pub use crate::mutable_keys::MutableKeys;

use core::hash::Hash;
use core::hash::BuildHasher;
use core::hash::Hasher;
use core::iter::FromIterator;
use hashbrown::hash_map::DefaultHashBuilder;
use core::ops::RangeFull;

use core::cmp::{max, Ordering};
use core::fmt;
use core::mem::{replace};
use core::marker::PhantomData;

use alloc::vec::Vec;
use alloc::boxed::Box;
use alloc::vec;

use crate::util::{third, ptrdistance, enumerate};
use crate::equivalent::Equivalent;
use crate::{
Bucket,
HashValue,
};
Expand Down Expand Up @@ -246,6 +250,7 @@ impl<Sz> ShortHashProxy<Sz>
/// # Examples
///
/// ```
/// # extern crate std;
/// use indexmap::IndexMap;
///
/// // count the frequency of each letter in a sentence.
Expand All @@ -260,7 +265,7 @@ impl<Sz> ShortHashProxy<Sz>
/// assert_eq!(letters.get(&'y'), None);
/// ```
#[derive(Clone)]
pub struct IndexMap<K, V, S = RandomState> {
pub struct IndexMap<K, V, S = DefaultHashBuilder> {
core: OrderMapCore<K, V>,
hash_builder: S,
}
Expand Down Expand Up @@ -301,28 +306,28 @@ impl<K, V, S> fmt::Debug for IndexMap<K, V, S>
S: BuildHasher,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(f.debug_map().entries(self.iter()).finish());
f.debug_map().entries(self.iter()).finish()?;
if cfg!(not(feature = "test_debug")) {
return Ok(());
}
try!(writeln!(f, ""));
writeln!(f, "")?;
for (i, index) in enumerate(&*self.core.indices) {
try!(write!(f, "{}: {:?}", i, index));
write!(f, "{}: {:?}", i, index)?;
if let Some(pos) = index.pos() {
let hash = self.core.entries[pos].hash;
let key = &self.core.entries[pos].key;
let desire = desired_pos(self.core.mask, hash);
try!(write!(f, ", desired={}, probe_distance={}, key={:?}",
write!(f, ", desired={}, probe_distance={}, key={:?}",
desire,
probe_distance(self.core.mask, hash, i),
key));
key)?;
}
try!(writeln!(f, ""));
writeln!(f, "")?;
}
try!(writeln!(f, "cap={}, raw_cap={}, entries.cap={}",
writeln!(f, "cap={}, raw_cap={}, entries.cap={}",
self.capacity(),
self.raw_capacity(),
self.core.entries.capacity()));
self.core.entries.capacity())?;
Ok(())
}
}
Expand Down Expand Up @@ -1492,9 +1497,9 @@ fn find_existing_entry_at<Sz>(indices: &[Pos], hash: HashValue,
});
}

use std::slice::Iter as SliceIter;
use std::slice::IterMut as SliceIterMut;
use std::vec::IntoIter as VecIntoIter;
use core::slice::Iter as SliceIter;
use core::slice::IterMut as SliceIterMut;
use alloc::vec::IntoIter as VecIntoIter;

/// An iterator over the keys of a `IndexMap`.
///
Expand Down Expand Up @@ -1730,7 +1735,7 @@ impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for IntoIter<K, V> {
/// [`drain`]: struct.IndexMap.html#method.drain
/// [`IndexMap`]: struct.IndexMap.html
pub struct Drain<'a, K, V> where K: 'a, V: 'a {
pub(crate) iter: ::std::vec::Drain<'a, Bucket<K, V>>
pub(crate) iter: ::alloc::vec::Drain<'a, Bucket<K, V>>
}

impl<'a, K, V> Iterator for Drain<'a, K, V> {
Expand Down Expand Up @@ -1779,7 +1784,7 @@ impl<K, V, S> IntoIterator for IndexMap<K, V, S>
}
}

use std::ops::{Index, IndexMut};
use core::ops::{Index, IndexMut};

impl<'a, K, V, Q: ?Sized, S> Index<&'a Q> for IndexMap<K, V, S>
where Q: Hash + Equivalent<K>,
Expand Down Expand Up @@ -1900,7 +1905,7 @@ impl<K, V, S> Eq for IndexMap<K, V, S>
#[cfg(test)]
mod tests {
use super::*;
use util::enumerate;
use crate::util::enumerate;

#[test]
fn it_works() {
Expand Down
4 changes: 2 additions & 2 deletions src/mutable_keys.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@

use std::hash::Hash;
use std::hash::BuildHasher;
use core::hash::Hash;
use core::hash::BuildHasher;

use super::{IndexMap, Equivalent};

Expand Down
30 changes: 14 additions & 16 deletions src/serde.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@

extern crate serde;
use serde::ser::{Serialize, Serializer, SerializeMap, SerializeSeq};
use serde::de::{Deserialize, Deserializer, Error, IntoDeserializer, MapAccess, SeqAccess, Visitor};
use serde::de::value::{MapDeserializer, SeqDeserializer};

use self::serde::ser::{Serialize, Serializer, SerializeMap, SerializeSeq};
use self::serde::de::{Deserialize, Deserializer, Error, IntoDeserializer, MapAccess, SeqAccess, Visitor};
use self::serde::de::value::{MapDeserializer, SeqDeserializer};
use core::fmt::{self, Formatter};
use core::hash::{BuildHasher, Hash};
use core::marker::PhantomData;

use std::fmt::{self, Formatter};
use std::hash::{BuildHasher, Hash};
use std::marker::PhantomData;

use IndexMap;
use crate::IndexMap;

/// Requires crate feature `"serde-1"`
impl<K, V, S> Serialize for IndexMap<K, V, S>
Expand All @@ -20,9 +18,9 @@ impl<K, V, S> Serialize for IndexMap<K, V, S>
fn serialize<T>(&self, serializer: T) -> Result<T::Ok, T::Error>
where T: Serializer
{
let mut map_serializer = try!(serializer.serialize_map(Some(self.len())));
let mut map_serializer = serializer.serialize_map(Some(self.len()))?;
for (key, value) in self {
try!(map_serializer.serialize_entry(key, value));
map_serializer.serialize_entry(key, value)?;
}
map_serializer.end()
}
Expand All @@ -46,7 +44,7 @@ impl<'de, K, V, S> Visitor<'de> for OrderMapVisitor<K, V, S>
{
let mut values = IndexMap::with_capacity_and_hasher(map.size_hint().unwrap_or(0), S::default());

while let Some((key, value)) = try!(map.next_entry()) {
while let Some((key, value)) = map.next_entry()? {
values.insert(key, value);
}

Expand Down Expand Up @@ -81,7 +79,7 @@ impl<'de, K, V, S, E> IntoDeserializer<'de, E> for IndexMap<K, V, S>
}


use IndexSet;
use crate::IndexSet;

/// Requires crate feature `"serde-1"`
impl<T, S> Serialize for IndexSet<T, S>
Expand All @@ -91,9 +89,9 @@ impl<T, S> Serialize for IndexSet<T, S>
fn serialize<Se>(&self, serializer: Se) -> Result<Se::Ok, Se::Error>
where Se: Serializer
{
let mut set_serializer = try!(serializer.serialize_seq(Some(self.len())));
let mut set_serializer = serializer.serialize_seq(Some(self.len()))?;
for value in self {
try!(set_serializer.serialize_element(value));
set_serializer.serialize_element(value)?;
}
set_serializer.end()
}
Expand All @@ -116,7 +114,7 @@ impl<'de, T, S> Visitor<'de> for OrderSetVisitor<T, S>
{
let mut values = IndexSet::with_capacity_and_hasher(seq.size_hint().unwrap_or(0), S::default());

while let Some(value) = try!(seq.next_element()) {
while let Some(value) = seq.next_element()? {
values.insert(value);
}

Expand Down
Loading