#interior-mutability #mutability #cell #write-once

mutate_once

Interior mutability, write-once and borrowable as plain &T

2 releases

0.1.1 Dec 12, 2019
0.1.0 Jul 25, 2019

#193 in Caching

Download history 42699/week @ 2024-03-14 35365/week @ 2024-03-21 40049/week @ 2024-03-28 35018/week @ 2024-04-04 35187/week @ 2024-04-11 36139/week @ 2024-04-18 30066/week @ 2024-04-25 27771/week @ 2024-05-02 27279/week @ 2024-05-09 29753/week @ 2024-05-16 25479/week @ 2024-05-23 71040/week @ 2024-05-30 94885/week @ 2024-06-06 77377/week @ 2024-06-13 117847/week @ 2024-06-20 106341/week @ 2024-06-27

414,656 downloads per month
Used in 93 crates (via kamadak-exif)

BSD-2-Clause

13KB
176 lines

Interior mutability, write-once and borrowable as plain &T

This library provides interior mutability that can be borrowed as plain immutable references &T in exchange for the write-once, read-many restriction.

Unlike std::cell::Cell or std::cell::RefCell, a plain immutable reference &T can be taken from MutOnce<T>. Once an immutable reference is taken, the value can never be mutated (even after all references are dropped).

The use cases include caching getter and delayed evaluation.

Usage

Run "cargo doc" in the source directory to generate the API reference. It is also available online at https://docs.rs/mutate_once.

An example follows:

  struct Container {
      expensive: MutOnce<String>,
  }
  impl Container {
      fn expensive(&self) -> &str {
          if !self.expensive.is_fixed() {
              let mut ref_mut = self.expensive.get_mut();
              *ref_mut += "expensive";
              // Drop `ref_mut` before calling `get_ref`.
          }
          // A plain reference can be returned to the caller
          // unlike `Cell` or `RefCell`.
          self.expensive.get_ref()
      }
  }
  let container = Container { expensive: MutOnce::new(String::new()) };
  assert_eq!(container.expensive(), "expensive");

No runtime deps