# core/sharedbakecache (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/core/sharedbakecache/

Sharing baked images. (vanilla.js core/graphic/sharedbakecache.js, used by ShadowText, ShadowImage and SoftShade)
- The same shape (key) is baked only once and several components draw the same image (Rc). The GPU texture is also one per image, so it is shared too.
- The original counts the components using each key and calls release. In the Rust version, a component holding the Rc is itself the reference count.
  When the key changes and it holds something else, or the component goes away, the Rc is released. One held only by the cache (Rc::strong_count is 1) is one nobody uses.
- Ones nobody uses are not discarded right away but kept. (if the same shape comes back soon, it is not baked again) When adding a new one, if MAXIMUM_IDLE_BAKE_COUNT is exceeded, the least recently used are discarded first.
- Failed bakes (None) are not stored. The engine runs on one thread, so the cache is a global of that one thread.

Example: The same key is baked only once and shares the same image

```rust
use std::rc::Rc;
use vanilla::core::sharedbakecache::{acquire_shared_bake, read_shared_bake_count};

let mut bake_count = 0;
let first_bake = acquire_shared_bake("label|16px|Hello", || {
	bake_count += 1;
	Some(Rc::new(String::from("Hello")))
}).unwrap();
let second_bake = acquire_shared_bake("label|16px|Hello", || {
	bake_count += 1;
	Some(Rc::new(String::from("Hello")))
}).unwrap();
assert_eq!(bake_count, 1);
assert!(Rc::ptr_eq(&first_bake, &second_bake));
assert_eq!(read_shared_bake_count(), (1, 0));
drop(first_bake);
drop(second_bake);
assert_eq!(read_shared_bake_count(), (1, 1));
```

## Functions and constants

- `pub fn acquire_shared_bake<T: 'static>(bake_key: &str, create_bake: impl FnOnce() -> Option<Rc<T>>) -> Option<Rc<T>>` (method, since 0.4.0): Acquires a baked image. (returns the one baked for the key if there is one, otherwise bakes it with create_bake, stores and returns it, the original acquireSharedBake)
  - It is not discarded while the returned Rc is held. The same key must also have the same type (T). (if the type differs, it bakes a new one and replaces it)
  - `bake_key` &str: Key. (text that distinguishes shapes, the same text means the same image)
  - `create_bake` impl FnOnce() -> Option<Rc<T>>: Bake function called only when nothing is stored for the key. (not stored if it returns None)
  - returns Option<Rc<T>>: The stored image or a newly baked image. None if the bake function returns None.
- `pub fn read_shared_bake_count() -> (usize, usize)` (method, since 0.4.0): Number of baked images held now and how many of them nobody uses. (for tests and statistics, the original readSharedBakeCount)
  - returns (usize, usize): (number stored, number of those held only by the cache). (held only by the cache means `Rc::strong_count` is 1)
