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

Extend (slightly) entry index interface [ECR-1832] #781

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Expand Up @@ -85,6 +85,8 @@ The project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html)
- `exonum::crypto::x25519` module to convert from Ed25519 keys to X25519 keys
has been introduced. (#722)

- `storage::Entry` has been extended with `take` and `swap` methods. (#781)

### Bug fixes

#### exonum
Expand Down
52 changes: 52 additions & 0 deletions exonum/src/storage/entry.rs
Expand Up @@ -172,4 +172,56 @@ where
pub fn remove(&mut self) {
self.base.remove(&())
}

/// Takes the value out of the entry, leaving a None in its place.
///
/// # Examples
///
/// ```
/// use exonum::storage::{MemoryDB, Database, Entry};
///
/// let db = MemoryDB::new();
/// let name = "name";
/// let mut fork = db.fork();
/// let mut index = Entry::new(name, &mut fork);
///
/// index.set(10);
/// assert_eq!(Some(10), index.get());
///
/// let value = index.take();
/// assert_eq!(Some(10), value);
/// assert_eq!(None, index.get());
/// ```
pub fn take(&mut self) -> Option<V> {
let value = self.get();
if value.is_some() {
self.remove();
}
value
}

/// Replaces the value in the entry with the given one, returning the previously stored value.
///
/// # Examples
///
/// ```
/// use exonum::storage::{MemoryDB, Database, Entry};
///
/// let db = MemoryDB::new();
/// let name = "name";
/// let mut fork = db.fork();
/// let mut index = Entry::new(name, &mut fork);
///
/// index.set(10);
/// assert_eq!(Some(10), index.get());
///
/// let value = index.swap(20);
/// assert_eq!(Some(10), value);
/// assert_eq!(Some(20), index.get());
/// ```
pub fn swap(&mut self, value: V) -> Option<V> {
let previous = self.get();
self.set(value);
previous
}
}