Skip to content

Commit b9fe606

Browse files
authored
Merge pull request #7 from Sajjon/error_types
Error types
2 parents 3a21080 + 8c88b38 commit b9fe606

File tree

8 files changed

+104
-80
lines changed

8 files changed

+104
-80
lines changed

Cargo.lock

Lines changed: 1 addition & 11 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "identified_vec"
3-
version = "0.1.3"
3+
version = "0.1.4"
44
edition = "2021"
55
authors = ["Alexander Cyon <[email protected]>"]
66
description = "Like HashSet but retaining INSERTION order and without `Hash` requirement on the Element type."
@@ -15,7 +15,6 @@ serde = ["dep:serde"]
1515
id_prim = []
1616

1717
[dependencies]
18-
anyerror = "0.1.12"
1918
serde = { version = "1.0.193", optional = true }
2019
thiserror = "1.0.50"
2120

src/identifiable_trait.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,18 @@
11
use std::fmt::Debug;
22
use std::hash::Hash;
33

4+
/// The `Identifiable` trait allows you to use the
5+
/// `IdentifiedVecOf<User> instead of the more verbose
6+
/// `IdentifiedVec<SomeUserID, User>` but also allows you to
7+
/// skip the `id_of_element: fn(&Element) -> ID` closure when
8+
/// initializing a new identified vec.
49
pub trait Identifiable {
10+
/// The type that your `Element` will use as its globally unique and stable ID,
11+
/// must impl `Hash` since it is used as a key in `IdentifiedVecOf`'s internal
12+
/// `HashMap`. Must impl `Clone` since we need to be able to clone it as a key
513
type ID: Eq + Hash + Clone + Debug;
14+
15+
/// Return `Element`'s globally unique and stable ID, used to uniquely identify
16+
/// the `Element` in the `IdentifiedVecOf` collection of elements.
617
fn id(&self) -> Self::ID;
718
}

src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,8 @@
124124
//! ```
125125
//! extern crate identified_vec;
126126
//! use identified_vec::{IdentifiedVec, IdentifiedVecOf, Identifiable};
127+
//!
128+
//! // closure which plucks out an ID from an element.
127129
//! let numbers = IdentifiedVec::<u32, u32>::new_identifying_element(|e| *e);
128130
//! ```
129131

src/serde_error.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
#[cfg(feature = "serde")]
2-
#[derive(thiserror::Error, Debug, Clone)]
2+
#[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)]
33
pub enum IdentifiedVecOfSerdeFailure {
44
#[error("Duplicate element at offset {0}")]
55
DuplicateElementsAtIndex(usize),

src/vec.rs

Lines changed: 28 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,6 @@ use std::collections::HashMap;
22
use std::fmt::{Debug, Display};
33
use std::hash::{Hash, Hasher};
44

5-
use anyerror::AnyError;
6-
75
/// Representation of a choice in a conflict resolution
86
/// where two elements with the same ID exists, if `ChooseFirst`,
97
/// is specified the first/current/existing value will be used, but
@@ -236,11 +234,11 @@ where
236234
/// implements high-quality hashing.
237235
#[cfg(not(tarpaulin_include))] // false negative
238236
#[inline]
239-
pub fn new_from_iter_try_uniquing_ids_with<I>(
237+
pub fn try_from_iter_select_unique_ids_with<E, I>(
240238
elements: I,
241239
id_of_element: fn(&Element) -> ID,
242-
combine: fn((usize, &Element, &Element)) -> Result<ConflictResolutionChoice, AnyError>,
243-
) -> Result<Self, AnyError>
240+
combine: fn((usize, &Element, &Element)) -> Result<ConflictResolutionChoice, E>,
241+
) -> Result<Self, E>
244242
where
245243
I: IntoIterator<Item = Element>,
246244
{
@@ -294,7 +292,7 @@ where
294292
/// implements high-quality hashing.
295293
#[cfg(not(tarpaulin_include))] // false negative
296294
#[inline]
297-
pub fn new_from_iter_uniquing_ids_with<I>(
295+
pub fn from_iter_select_unique_ids_with<I>(
298296
elements: I,
299297
id_of_element: fn(&Element) -> ID,
300298
combine: fn((usize, &Element, &Element)) -> ConflictResolutionChoice,
@@ -406,16 +404,16 @@ where
406404
self.elements.get_mut(id)
407405
}
408406

409-
/// A read-only collection view for the elements contained in this array, as a `Vec<Elements>`.
407+
/// A read-only collection of references to the elements contained in this array, as a `Vec<&Elements>`.
408+
///
409+
/// N.B. that this method is not constant time.
410+
///
411+
/// If `Element` implements `Clone` you can use `self.items()` which returns a `Vec<Element>`, of cloned elements.
410412
///
411413
/// - Complexity: O(n)
412414
#[inline]
413415
pub fn elements(&self) -> Vec<&Element> {
414-
let mut elements_ordered = Vec::<&Element>::new();
415-
for id in &self.order {
416-
elements_ordered.push(self.elements.get(id).expect("element"));
417-
}
418-
elements_ordered
416+
self.iter().collect()
419417
}
420418

421419
/// Returns `true` if the `identified_vec` contains the `element.`
@@ -443,6 +441,24 @@ where
443441
}
444442
}
445443

444+
impl<ID, Element> IdentifiedVec<ID, Element>
445+
where
446+
Element: Clone,
447+
ID: Eq + Hash + Clone + Debug,
448+
{
449+
/// A read-only collection of clones of the elements contained in this array, as a `Vec<Elements>`.
450+
///
451+
/// N.B. that this method is not constant time.
452+
///
453+
/// Use `self.elements()` if you are looking for a collection of references.
454+
///
455+
/// - Complexity: O(n)
456+
#[inline]
457+
pub fn items(&self) -> Vec<Element> {
458+
self.iter().map(|e| e.clone()).collect()
459+
}
460+
}
461+
446462
/// An iterator over the items of an `IdentifiedVec`.
447463
pub struct IdentifiedVecIterator<'a, ID, Element>
448464
where

src/vec_of.rs

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1-
use anyerror::AnyError;
21
use std::collections::HashMap;
2+
3+
#[cfg(feature = "serde")]
34
use std::fmt::Debug;
45

56
#[cfg(feature = "serde")]
@@ -15,6 +16,15 @@ use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
1516
///////////////////////
1617
/// IdentifiedVecOf ///
1718
///////////////////////
19+
20+
/// A type alias for `IdentifiedVec<Element::ID, Element>`, this is the
21+
/// preferred and most powerful collection type of this crate, requires
22+
/// that your `Element`s impl the `Identifiable` trait. Using this collection
23+
/// allows you to skip passing the `id_of_element: fn(&Element) -> ID` closure
24+
/// which you otherwise need to pass when initializing an `IdentifiedVec`. Using
25+
/// `IdentifiedVecOf` together with feature "serde" also gives serde
26+
/// serialization/deserialization as if it were a `Vec<Element>`, given that
27+
/// `Element` implements serde serialization/deserialization of course.
1828
pub type IdentifiedVecOf<Element> = IdentifiedVec<<Element as Identifiable>::ID, Element>;
1929

2030
//////////////////////////////////////////////
@@ -73,14 +83,14 @@ where
7383
/// - Complexity: Expected O(*n*) on average, where *n* is the count of elements, if `ID`
7484
/// implements high-quality hashing.
7585
#[inline]
76-
pub fn new_from_iter_try_uniquing_with<I>(
86+
pub fn try_from_iter_select_unique_with<E, I>(
7787
elements: I,
78-
combine: fn((usize, &Element, &Element)) -> Result<ConflictResolutionChoice, AnyError>,
79-
) -> Result<Self, AnyError>
88+
combine: fn((usize, &Element, &Element)) -> Result<ConflictResolutionChoice, E>,
89+
) -> Result<Self, E>
8090
where
8191
I: IntoIterator<Item = Element>,
8292
{
83-
Self::new_from_iter_try_uniquing_ids_with(elements, |e| e.id(), combine)
93+
Self::try_from_iter_select_unique_ids_with(elements, |e| e.id(), combine)
8494
}
8595

8696
/// Creates a new `identified_vec` from the elements in the given sequence, using a combining closure to
@@ -99,14 +109,14 @@ where
99109
/// - Complexity: Expected O(*n*) on average, where *n* is the count of elements, if `ID`
100110
/// implements high-quality hashing.
101111
#[inline]
102-
pub fn new_from_iter_uniquing_with<I>(
112+
pub fn from_iter_select_unique_with<I>(
103113
elements: I,
104114
combine: fn((usize, &Element, &Element)) -> ConflictResolutionChoice,
105115
) -> Self
106116
where
107117
I: IntoIterator<Item = Element>,
108118
{
109-
Self::new_from_iter_uniquing_ids_with(elements, |e| e.id(), combine)
119+
Self::from_iter_select_unique_ids_with(elements, |e| e.id(), combine)
110120
}
111121
}
112122

@@ -136,10 +146,8 @@ where
136146
deserializer: D,
137147
) -> Result<IdentifiedVecOf<Element>, D::Error> {
138148
let elements = Vec::<Element>::deserialize(deserializer)?;
139-
IdentifiedVecOf::<Element>::new_from_iter_try_uniquing_with(elements, |(idx, _, _)| {
140-
Err(AnyError::new(
141-
&IdentifiedVecOfSerdeFailure::DuplicateElementsAtIndex(idx),
142-
))
149+
IdentifiedVecOf::<Element>::try_from_iter_select_unique_with(elements, |(idx, _, _)| {
150+
Err(IdentifiedVecOfSerdeFailure::DuplicateElementsAtIndex(idx))
143151
})
144152
.map_err(de::Error::custom)
145153
}

0 commit comments

Comments
 (0)