Skip to content

Commit

Permalink
Extend (slightly) entry index interface [ECR-1832] (#781)
Browse files Browse the repository at this point in the history
  • Loading branch information
stanislav-tkach committed Jul 9, 2018
1 parent 5e75d9c commit 41abf44
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Expand Up @@ -94,6 +94,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
}
}

0 comments on commit 41abf44

Please sign in to comment.