Created
October 18, 2024 18:16
-
-
Save ItsDoot/878ee32834b2951e96af19b557797bae to your computer and use it in GitHub Desktop.
Similar in essence to Cow but stores only values and also stores the original
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// A container that stores both the original and current value of a variable | |
/// with type `T`. | |
pub struct Editable<T> { | |
/// The original value of the editable. | |
original: T, | |
/// The current value of the editable, if any. | |
current: Option<T>, | |
} | |
impl<T> Editable<T> { | |
/// Creates a new editable with the given original value. | |
pub fn new(original: T) -> Self { | |
Self { | |
original, | |
current: None, | |
} | |
} | |
/// Returns a read-only reference to the original value of the editable. | |
pub fn original(&self) -> &T { | |
&self.original | |
} | |
/// Returns a read-only reference to the current value of the editable, if any. | |
pub fn current(&self) -> Option<&T> { | |
self.current.as_ref() | |
} | |
/// Returns a mutable reference to the current value of the editable, if any. | |
pub fn current_mut(&mut self) -> Option<&mut T> { | |
self.current.as_mut() | |
} | |
/// Returns a read-only reference to either the current value of the | |
/// editable, or the original value if not yet edited. | |
pub fn value(&self) -> &T { | |
self.current.as_ref().unwrap_or(&self.original) | |
} | |
/// Returns a mutable reference to the current value of the editable, | |
/// initializing it with a clone of the original value if not yet edited. | |
pub fn value_mut(&mut self) -> &mut T | |
where | |
T: Clone, | |
{ | |
self.current.get_or_insert_with(|| self.original.clone()) | |
} | |
/// Sets the current value of the editable. | |
pub fn set_value(&mut self, value: T) { | |
self.current = Some(value); | |
} | |
} | |
impl<T> Deref for Editable<T> { | |
type Target = T; | |
fn deref(&self) -> &Self::Target { | |
self.value() | |
} | |
} | |
impl<T: Clone> DerefMut for Editable<T> { | |
fn deref_mut(&mut self) -> &mut Self::Target { | |
self.value_mut() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment