use std::collections::HashMap;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use crate::ImageFormat;
pub const DEFAULT_IMAGE_BYTES_CACHE: usize = 16 * 1024 * 1024;
static NEXT_STORE_ID: AtomicU64 = AtomicU64::new(1);
#[must_use]
pub fn next_store_id() -> u64 {
NEXT_STORE_ID.fetch_add(1, Ordering::Relaxed)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ImageId {
store: u64,
index: u32,
}
impl ImageId {
#[must_use]
pub const fn new(store: u64, index: u32) -> Self {
Self { store, index }
}
#[must_use]
pub const fn store(self) -> u64 {
self.store
}
#[must_use]
pub const fn index(self) -> u32 {
self.index
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ImageKey {
Inline {
addr: usize,
len: usize,
},
Handle(ImageId),
}
pub trait ImageLoader: Send + Sync + fmt::Debug {
fn load(&self, index: u32) -> Option<Arc<[u8]>>;
fn load_with_format(
&self,
index: u32,
fallback: ImageFormat,
) -> Option<(Arc<[u8]>, ImageFormat)> {
self.load(index).map(|bytes| (bytes, fallback))
}
fn load_prefix(&self, index: u32, max_bytes: usize) -> Option<Arc<[u8]>> {
let _ = max_bytes;
self.load(index)
}
}
#[derive(Clone)]
pub struct ImageRef {
id: ImageId,
byte_len: u64,
loader: Arc<dyn ImageLoader>,
}
impl ImageRef {
#[must_use]
pub fn new(id: ImageId, byte_len: u64, loader: Arc<dyn ImageLoader>) -> Self {
Self {
id,
byte_len,
loader,
}
}
#[must_use]
pub const fn id(&self) -> ImageId {
self.id
}
#[must_use]
pub const fn byte_len(&self) -> u64 {
self.byte_len
}
#[must_use]
pub fn load(&self) -> Option<Arc<[u8]>> {
self.loader.load(self.id.index)
}
#[must_use]
pub fn load_with_format(&self, fallback: ImageFormat) -> Option<(Arc<[u8]>, ImageFormat)> {
self.loader.load_with_format(self.id.index, fallback)
}
#[must_use]
pub fn load_prefix(&self, max_bytes: usize) -> Option<Arc<[u8]>> {
self.loader.load_prefix(self.id.index, max_bytes)
}
}
impl fmt::Debug for ImageRef {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ImageRef")
.field("index", &self.id.index)
.field("byte_len", &self.byte_len)
.finish_non_exhaustive()
}
}
impl PartialEq for ImageRef {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
impl Eq for ImageRef {}
impl Hash for ImageRef {
fn hash<H: Hasher>(&self, state: &mut H) {
self.id.hash(state);
}
}
#[derive(Clone, Debug)]
pub enum ImageData {
Inline(Arc<[u8]>),
Lazy(ImageRef),
}
impl ImageData {
#[must_use]
pub fn bytes(&self) -> Option<Arc<[u8]>> {
match self {
Self::Inline(bytes) => Some(Arc::clone(bytes)),
Self::Lazy(handle) => handle.load(),
}
}
#[must_use]
pub fn bytes_with_format(&self, fallback: ImageFormat) -> Option<(Arc<[u8]>, ImageFormat)> {
match self {
Self::Inline(bytes) => Some((Arc::clone(bytes), fallback)),
Self::Lazy(handle) => handle.load_with_format(fallback),
}
}
#[must_use]
pub fn prefix(&self, max_bytes: usize) -> Option<Arc<[u8]>> {
match self {
Self::Inline(bytes) => Some(Arc::clone(bytes)),
Self::Lazy(handle) => handle.load_prefix(max_bytes),
}
}
#[must_use]
pub fn key(&self) -> ImageKey {
match self {
Self::Inline(bytes) => ImageKey::Inline {
addr: bytes.as_ptr().addr(),
len: bytes.len(),
},
Self::Lazy(handle) => ImageKey::Handle(handle.id()),
}
}
#[must_use]
pub fn len(&self) -> usize {
match self {
Self::Inline(bytes) => bytes.len(),
Self::Lazy(handle) => usize::try_from(handle.byte_len()).unwrap_or(usize::MAX),
}
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
#[must_use]
pub const fn is_lazy(&self) -> bool {
matches!(self, Self::Lazy(_))
}
#[must_use]
pub const fn inline_bytes(&self) -> Option<&Arc<[u8]>> {
match self {
Self::Inline(bytes) => Some(bytes),
Self::Lazy(_) => None,
}
}
#[must_use]
pub const fn lazy_ref(&self) -> Option<&ImageRef> {
match self {
Self::Inline(_) => None,
Self::Lazy(handle) => Some(handle),
}
}
}
impl PartialEq for ImageData {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::Inline(left), Self::Inline(right)) => left == right,
(Self::Lazy(left), Self::Lazy(right)) => left == right,
_ => false,
}
}
}
impl Eq for ImageData {}
impl Hash for ImageData {
fn hash<H: Hasher>(&self, state: &mut H) {
std::mem::discriminant(self).hash(state);
match self {
Self::Inline(bytes) => bytes.hash(state),
Self::Lazy(handle) => handle.hash(state),
}
}
}
impl From<Arc<[u8]>> for ImageData {
fn from(bytes: Arc<[u8]>) -> Self {
Self::Inline(bytes)
}
}
impl From<Vec<u8>> for ImageData {
fn from(bytes: Vec<u8>) -> Self {
Self::Inline(Arc::from(bytes))
}
}
impl From<&[u8]> for ImageData {
fn from(bytes: &[u8]) -> Self {
Self::Inline(Arc::from(bytes))
}
}
impl From<Box<[u8]>> for ImageData {
fn from(bytes: Box<[u8]>) -> Self {
Self::Inline(Arc::from(bytes))
}
}
impl From<ImageRef> for ImageData {
fn from(handle: ImageRef) -> Self {
Self::Lazy(handle)
}
}
#[derive(Debug)]
pub struct LruBytesCache {
max_bytes: usize,
inner: Mutex<LruBytesInner>,
}
#[derive(Debug, Default)]
struct LruBytesInner {
entries: HashMap<u32, LruEntry>,
total_bytes: usize,
tick: u64,
}
#[derive(Debug)]
struct LruEntry {
bytes: Arc<[u8]>,
format: ImageFormat,
last_used: u64,
}
impl LruBytesCache {
#[must_use]
pub fn new(max_bytes: usize) -> Self {
Self {
max_bytes,
inner: Mutex::new(LruBytesInner::default()),
}
}
#[must_use]
pub fn get(&self, index: u32) -> Option<(Arc<[u8]>, ImageFormat)> {
let mut inner = self.inner.lock().ok()?;
inner.tick = inner.tick.saturating_add(1);
let tick = inner.tick;
let entry = inner.entries.get_mut(&index)?;
entry.last_used = tick;
Some((Arc::clone(&entry.bytes), entry.format))
}
pub fn insert(&self, index: u32, bytes: Arc<[u8]>, format: ImageFormat) {
let cost = bytes.len();
if self.max_bytes == 0 || cost > self.max_bytes {
return;
}
let Ok(mut inner) = self.inner.lock() else {
return;
};
if let Some(previous) = inner.entries.remove(&index) {
inner.total_bytes = inner.total_bytes.saturating_sub(previous.bytes.len());
}
while inner.total_bytes.saturating_add(cost) > self.max_bytes {
let Some(&oldest_key) = inner
.entries
.iter()
.min_by_key(|(_, entry)| entry.last_used)
.map(|(key, _)| key)
else {
break;
};
if let Some(evicted) = inner.entries.remove(&oldest_key) {
inner.total_bytes = inner.total_bytes.saturating_sub(evicted.bytes.len());
}
}
inner.tick = inner.tick.saturating_add(1);
let tick = inner.tick;
inner.total_bytes = inner.total_bytes.saturating_add(cost);
inner.entries.insert(
index,
LruEntry {
bytes,
format,
last_used: tick,
},
);
}
#[must_use]
pub fn total_bytes(&self) -> usize {
self.inner.lock().map_or(0, |inner| inner.total_bytes)
}
#[must_use]
pub fn len(&self) -> usize {
self.inner.lock().map_or(0, |inner| inner.entries.len())
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn clear(&self) {
if let Ok(mut inner) = self.inner.lock() {
inner.entries.clear();
inner.total_bytes = 0;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn lru_cache_evicts_least_recently_used() {
let cache = LruBytesCache::new(10);
cache.insert(1, Arc::from([1_u8; 4]), ImageFormat::Png);
cache.insert(2, Arc::from([2_u8; 4]), ImageFormat::Jpeg);
assert_eq!(cache.total_bytes(), 8);
assert!(cache.get(1).is_some());
cache.insert(3, Arc::from([3_u8; 4]), ImageFormat::Png);
assert_eq!(
(
cache.get(1).is_some(),
cache.get(2).is_none(),
cache.get(3).is_some()
),
(true, true, true)
);
assert_eq!(cache.total_bytes(), 8);
}
#[derive(Debug)]
struct Empty;
impl ImageLoader for Empty {
fn load(&self, _index: u32) -> Option<Arc<[u8]>> {
None
}
}
#[test]
fn an_image_handles_debug_form_is_the_same_for_every_store() {
let loader: Arc<dyn ImageLoader> = Arc::new(Empty);
let first = ImageRef::new(ImageId::new(next_store_id(), 3), 120, Arc::clone(&loader));
let second = ImageRef::new(ImageId::new(next_store_id(), 3), 120, loader);
assert_ne!(first.id(), second.id());
assert_eq!(format!("{first:?}"), format!("{second:?}"));
assert_eq!(
format!("{first:?}"),
"ImageRef { index: 3, byte_len: 120, .. }"
);
}
#[test]
fn lru_cache_skips_oversized_entries() {
let cache = LruBytesCache::new(10);
cache.insert(1, Arc::from([1_u8; 4]), ImageFormat::Png);
cache.insert(4, Arc::from([4_u8; 16]), ImageFormat::Png);
assert!(cache.get(4).is_none());
assert_eq!(cache.len(), 1);
}
}