Skip to content
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

Arena::alloc_with_id #10

Merged
merged 4 commits into from
Jan 30, 2019
Merged
Show file tree
Hide file tree
Changes from 2 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
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,13 @@
# 3.0.0

Released 2019-01-29.

* Replaced the `Arena::next_id` method with the less bug prone
`Arena::alloc_with_id` method. See
[#9](https://github.com/fitzgen/id-arena/issues/9).

--------------------------------------------------------------------------------

# 2.1.0

Released 2019-01-25.
Expand Down
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ license = "MIT/Apache-2.0"
name = "id-arena"
readme = "README.md"
repository = "https://github.com/fitzgen/id-arena"
version = "2.1.0"
version = "3.0.0"

[package.metadata.docs.rs]
features = ['rayon']
Expand Down
21 changes: 12 additions & 9 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -364,8 +364,7 @@ where
id
}

/// Get the id that will be used for the next item allocated into this
/// arena.
/// Allocate an item with the id that it will be assigned.
///
/// This is useful for structures that want to store their id as their own
/// member.
Expand All @@ -379,14 +378,18 @@ where
///
/// let mut arena = Arena::<Cat>::new();
///
/// let id = arena.next_id();
/// assert!(arena.get(id).is_none());
///
/// let id2 = arena.alloc(Cat { id });
/// assert_eq!(id, id2);
/// assert!(arena.get(id).is_some());
/// let kitty = arena.alloc_with_id(|id| Cat { id });
/// assert_eq!(arena[kitty].id, kitty);
/// ```
pub fn next_id(&self) -> A::Id {
#[inline]
pub fn alloc_with_id(&mut self, f: impl FnOnce(A::Id) -> T) -> A::Id {
let id = self.next_id();
let val = f(id);
self.alloc(val)
}

#[inline]
fn next_id(&self) -> A::Id {
let arena_id = self.arena_id;
let idx = self.items.len();
A::new_id(arena_id, idx)
Expand Down