Skip to main content

MemoryStore

Struct MemoryStore 

Source
pub struct MemoryStore { /* private fields */ }
Expand description

A store that keeps everything in memory.

For tests and for bringing a board up before its flash driver works. It is not a leaf node’s storage: it satisfies the durability contract only in the sense that there is nothing to lose power.

Implementations§

Source§

impl MemoryStore

Source

pub fn new() -> Self

Creates an empty store.

Examples found in repository?
examples/wasi_host_shim.rs (line 123)
112fn run() -> Result<(), String> {
113    let args: Vec<String> = std::env::args().skip(1).collect();
114    let [app_id, peer, now] = args.as_slice() else {
115        return Err(USAGE.to_string());
116    };
117    let now_unix_secs: u64 = now
118        .parse()
119        .map_err(|_| format!("now_unix_secs must be a whole number of seconds, got {now:?}"))?;
120
121    // `shared_store` rather than `Arc::new`: it is the one constructor that
122    // builds on every target the crate supports, so it is the route to copy.
123    let store = shared_store(MemoryStore::new());
124
125    // Provisioning draws from the getrandom backend the target selects. On
126    // WASI that is the runtime's `random_get`; see the header.
127    let mut device =
128        LeafDevice::open(store, app_id).map_err(|error| format!("opening the device: {error}"))?;
129    eprintln!("address {}", device.address());
130
131    let stdout = io::stdout();
132    let mut out = stdout.lock();
133
134    // Pairing starts with the device's key package. The time is supplied, not
135    // read: with `now_unix_secs` the package's validity window is real, and
136    // without it the library would stamp 1970.
137    let advertisement = device
138        .key_package_frame(peer, now_unix_secs)
139        .map_err(|error| format!("minting the key package: {error}"))?;
140    emit(&mut out, &advertisement)?;
141
142    // Steady state: frames arrive, the device verifies each, opens it if it is
143    // sealed, persists, and only then hands back what it owes in reply.
144    for (index, line) in io::stdin().lock().lines().enumerate() {
145        let line = line.map_err(|error| format!("reading standard input: {error}"))?;
146        if line.trim().is_empty() {
147            continue;
148        }
149        let inbound = Message::from_json(&line)
150            .map_err(|error| format!("line {}: not a frame: {error}", index + 1))?;
151        match device.handle(&inbound, now_unix_secs) {
152            Ok(handled) => {
153                for event in &handled.events {
154                    eprintln!("event {event:?}");
155                }
156                for frame in &handled.outbound {
157                    emit(&mut out, frame)?;
158                }
159            }
160            Err(error) => eprintln!("line {}: refused: {error}", index + 1),
161        }
162    }
163
164    // Answering. The persist is inside `seal`, before it returns anything, so
165    // there is no ordering here to get wrong. Without the phone's Welcome
166    // there is no session, and the crate says so rather than sealing into a
167    // group that does not exist.
168    match device.seal(peer, GREETING, now_unix_secs) {
169        Ok(frame) => emit(&mut out, &frame),
170        Err(LeafError::NoSession(_)) => {
171            eprintln!(
172                "no session with {peer}: nothing sealed. A session exists only after the \
173                 phone's Welcome, and no frame on standard input carried one."
174            );
175            Ok(())
176        }
177        Err(error) => Err(format!("sealing to {peer}: {error}")),
178    }
179}
Source

pub fn len(&self) -> usize

Number of entries held, for tests that assert what was written.

Source

pub fn is_empty(&self) -> bool

Whether the store holds nothing.

Trait Implementations§

Source§

impl Debug for MemoryStore

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for MemoryStore

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl LeafStore for MemoryStore

Source§

fn store( &self, key_type: &str, key_id: &str, data: &[u8], ) -> Result<(), StoreError>

Writes data, replacing any previous value for this key. Read more
Source§

fn load( &self, key_type: &str, key_id: &str, ) -> Result<Option<Vec<u8>>, StoreError>

Reads a value, or None if this key was never written.
Source§

fn delete(&self, key_type: &str, key_id: &str) -> Result<(), StoreError>

Removes a value. Removing a key that is not there is not an error. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more