MemoryStorage

Struct MemoryStorage 

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

A simple in-memory storage implementation for testing and single-instance applications.

This implementation uses a HashMap wrapped in Arc<RwLock<>> for thread-safe access. It doesn’t persist data across restarts and doesn’t implement automatic expiration (expired entries are only removed during cleanup operations).

§Features

  • Zero dependencies: No external storage dependencies required
  • Thread-safe: Uses tokio’s RwLock for concurrent access
  • Fast operations: All operations are in-memory and very fast
  • Context isolation: Supports nonce namespacing via contexts
  • No persistence: Data is lost when the application restarts
  • Pre-allocated capacity: Optional capacity hint for better performance
  • Batch operations: Support for bulk operations

§Use Cases

  • Development and testing environments
  • Single-instance applications with short-lived nonces
  • Applications that don’t require persistence across restarts
  • Proof-of-concept implementations

§Example

use nonce_auth::storage::{MemoryStorage, NonceStorage};
use std::time::Duration;

let storage = MemoryStorage::new();

// Store a nonce
storage.set("test-nonce", None, Duration::from_secs(300)).await?;

// Check if it exists
let exists = storage.exists("test-nonce", None).await?;
assert!(exists);

// Get the entry
let entry = storage.get("test-nonce", None).await?;
assert!(entry.is_some());

Implementations§

Source§

impl MemoryStorage

Source

pub fn new() -> Self

Creates a new in-memory storage instance.

§Example
use nonce_auth::storage::MemoryStorage;

let storage = MemoryStorage::new();
Source

pub fn with_capacity(capacity: usize) -> Self

Creates a new in-memory storage instance with pre-allocated capacity.

This can improve performance when you know approximately how many nonces you’ll be storing, as it avoids HashMap reallocations.

§Arguments
  • capacity - Initial capacity hint for the internal HashMap
§Example
use nonce_auth::storage::MemoryStorage;

// Pre-allocate for ~1000 nonces
let storage = MemoryStorage::with_capacity(1000);
Source§

impl MemoryStorage

Batch operations support for better performance

Source

pub async fn batch_set( &self, nonces: Vec<(&str, Option<&str>)>, _ttl: Duration, ) -> Result<usize, NonceError>

Insert multiple nonces in a batch operation.

This method acquires the write lock once and performs all insertions, which can be more efficient than individual set operations.

§Arguments
  • nonces - Vector of (nonce, context) tuples to insert
  • _ttl - Time-to-live (not used in memory storage but kept for consistency)
§Returns

Number of successfully inserted nonces (duplicates are skipped)

§Example
use nonce_auth::storage::MemoryStorage;
use std::time::Duration;

let storage = MemoryStorage::new();
let nonces = vec![
    ("nonce1", None),
    ("nonce2", Some("ctx1")),
    ("nonce3", Some("ctx2")),
];

let inserted = storage.batch_set(nonces, Duration::from_secs(300)).await?;
assert_eq!(inserted, 3);
Source

pub async fn batch_exists( &self, nonces: Vec<(&str, Option<&str>)>, ) -> Result<Vec<bool>, NonceError>

Check existence of multiple nonces in a batch operation.

This method acquires the read lock once and checks all nonces, which can be more efficient than individual exists operations.

§Arguments
  • nonces - Vector of (nonce, context) tuples to check
§Returns

Vector of boolean values indicating existence for each nonce

§Example
use nonce_auth::storage::MemoryStorage;

let storage = MemoryStorage::new();
let check_nonces = vec![
    ("nonce1", None),
    ("nonce2", Some("ctx1")),
];

let results = storage.batch_exists(check_nonces).await?;
Source

pub async fn batch_get( &self, nonces: Vec<(&str, Option<&str>)>, ) -> Result<Vec<Option<NonceEntry>>, NonceError>

Get multiple nonces in a batch operation.

This method acquires the read lock once and retrieves all nonces, which can be more efficient than individual get operations.

§Arguments
  • nonces - Vector of (nonce, context) tuples to retrieve
§Returns

Vector of optional NonceEntry values

§Example
use nonce_auth::storage::MemoryStorage;

let storage = MemoryStorage::new();
let get_nonces = vec![
    ("nonce1", None),
    ("nonce2", Some("ctx1")),
];

let results = storage.batch_get(get_nonces).await?;

Trait Implementations§

Source§

impl Debug for MemoryStorage

Source§

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

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

impl Default for MemoryStorage

Source§

fn default() -> Self

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

impl NonceStorage for MemoryStorage

Source§

fn get<'life0, 'life1, 'life2, 'async_trait>( &'life0 self, nonce: &'life1 str, context: Option<&'life2 str>, ) -> Pin<Box<dyn Future<Output = Result<Option<NonceEntry>, NonceError>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait,

Retrieves a nonce entry if it exists. Read more
Source§

fn set<'life0, 'life1, 'life2, 'async_trait>( &'life0 self, nonce: &'life1 str, context: Option<&'life2 str>, _ttl: Duration, ) -> Pin<Box<dyn Future<Output = Result<(), NonceError>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait,

Stores a new nonce with expiration time. Read more
Source§

fn exists<'life0, 'life1, 'life2, 'async_trait>( &'life0 self, nonce: &'life1 str, context: Option<&'life2 str>, ) -> Pin<Box<dyn Future<Output = Result<bool, NonceError>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait,

Checks if a nonce exists without retrieving it. Read more
Source§

fn cleanup_expired<'life0, 'async_trait>( &'life0 self, cutoff_time: i64, ) -> Pin<Box<dyn Future<Output = Result<usize, NonceError>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Removes all expired nonces from storage. Read more
Source§

fn get_stats<'life0, 'async_trait>( &'life0 self, ) -> Pin<Box<dyn Future<Output = Result<StorageStats, NonceError>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Returns statistics about the storage backend. Read more
Source§

fn init<'life0, 'async_trait>( &'life0 self, ) -> Pin<Box<dyn Future<Output = Result<(), NonceError>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Optional method for storage backend initialization. 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, 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> 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 = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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.