f-office-paint 0.2.1

Display list: the contract between layout and output.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
//! Handle-based lazy image storage and bounded LRU caching for encoded image bytes.

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;

/// Default byte budget for a bounded encoded-image LRU cache (`16 MiB`).
pub const DEFAULT_IMAGE_BYTES_CACHE: usize = 16 * 1024 * 1024;

/// Monotonic generator for distinct [`ImageId`] store identifiers.
static NEXT_STORE_ID: AtomicU64 = AtomicU64::new(1);

/// Allocates a process-unique store identifier for a new [`ImageLoader`] instance.
#[must_use]
pub fn next_store_id() -> u64 {
    NEXT_STORE_ID.fetch_add(1, Ordering::Relaxed)
}

/// Stable identity of an image managed by an [`ImageLoader`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ImageId {
    store: u64,
    index: u32,
}

impl ImageId {
    /// Creates an image identifier for `index` within `store`.
    #[must_use]
    pub const fn new(store: u64, index: u32) -> Self {
        Self { store, index }
    }

    /// Returns the loader's store identifier.
    #[must_use]
    pub const fn store(self) -> u64 {
        self.store
    }

    /// Returns the image's index within its loader.
    #[must_use]
    pub const fn index(self) -> u32 {
        self.index
    }
}

/// Key uniquely identifying an image's encoded source for raster and PDF caches.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ImageKey {
    /// Pointer address and length of an inline `Arc<[u8]>` buffer.
    Inline {
        /// Memory address of the shared slice.
        addr: usize,
        /// Byte length of the shared slice.
        len: usize,
    },
    /// Stable identity of a lazily loaded [`ImageRef`].
    Handle(ImageId),
}

/// Lazy source of encoded image bytes, backed by an archive, rewrite pipeline, or cache.
pub trait ImageLoader: Send + Sync + fmt::Debug {
    /// Loads the complete encoded bytes of image `index`, or `None` if unavailable.
    fn load(&self, index: u32) -> Option<Arc<[u8]>>;

    /// Loads the encoded bytes together with their effective [`ImageFormat`].
    ///
    /// Loaders that lazily transcode images (for example opaque PNGs converted to JPEG) override
    /// this method so consumers observe the resulting format without eagerly transcoding at open
    /// time.
    fn load_with_format(
        &self,
        index: u32,
        fallback: ImageFormat,
    ) -> Option<(Arc<[u8]>, ImageFormat)> {
        self.load(index).map(|bytes| (bytes, fallback))
    }

    /// Loads up to `max_bytes` leading bytes for header inspection without inflating the full
    /// asset when supported by the backing store.
    fn load_prefix(&self, index: u32, max_bytes: usize) -> Option<Arc<[u8]>> {
        let _ = max_bytes;
        self.load(index)
    }
}

/// Lightweight handle to lazily loaded image bytes backed by an [`ImageLoader`].
///
/// Cloning an `ImageRef` copies only its [`ImageId`], declared length, and `Arc` loader handle
/// without retaining any decoded or decompressed image bytes.
#[derive(Clone)]
pub struct ImageRef {
    id: ImageId,
    byte_len: u64,
    loader: Arc<dyn ImageLoader>,
}

impl ImageRef {
    /// Creates a lazy image handle for `id` with declared length `byte_len` backed by `loader`.
    #[must_use]
    pub fn new(id: ImageId, byte_len: u64, loader: Arc<dyn ImageLoader>) -> Self {
        Self {
            id,
            byte_len,
            loader,
        }
    }

    /// Returns the handle's stable identity.
    #[must_use]
    pub const fn id(&self) -> ImageId {
        self.id
    }

    /// Returns the declared encoded byte length of the image.
    #[must_use]
    pub const fn byte_len(&self) -> u64 {
        self.byte_len
    }

    /// Loads the complete encoded bytes from the backing loader.
    #[must_use]
    pub fn load(&self) -> Option<Arc<[u8]>> {
        self.loader.load(self.id.index)
    }

    /// Loads the complete encoded bytes and effective format from the backing loader.
    #[must_use]
    pub fn load_with_format(&self, fallback: ImageFormat) -> Option<(Arc<[u8]>, ImageFormat)> {
        self.loader.load_with_format(self.id.index, fallback)
    }

    /// Loads up to `max_bytes` leading bytes for header inspection.
    #[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("id", &self.id)
            .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);
    }
}

/// Encoded image payload stored on an [`crate::Image`]: either inline shared bytes or a lazy
/// [`ImageRef`] handle.
#[derive(Clone, Debug)]
pub enum ImageData {
    /// Inline shared bytes already resident in memory (for example synthetic effect bitmaps).
    Inline(Arc<[u8]>),
    /// Lightweight handle loaded lazily on demand from an [`ImageLoader`].
    Lazy(ImageRef),
}

impl ImageData {
    /// Returns the complete encoded bytes, loading them lazily when backed by an [`ImageRef`].
    #[must_use]
    pub fn bytes(&self) -> Option<Arc<[u8]>> {
        match self {
            Self::Inline(bytes) => Some(Arc::clone(bytes)),
            Self::Lazy(handle) => handle.load(),
        }
    }

    /// Returns the complete encoded bytes and their effective format, loading lazily when backed
    /// by an [`ImageRef`].
    #[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),
        }
    }

    /// Returns up to `max_bytes` leading bytes for header inspection without necessarily inflating
    /// the full asset.
    #[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),
        }
    }

    /// Returns a cache key uniquely identifying this image source.
    #[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()),
        }
    }

    /// Returns the encoded byte length (from the slice or declared archive metadata).
    #[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),
        }
    }

    /// Returns `true` when the declared encoded byte length is zero.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns `true` when this payload is backed by a lazy [`ImageRef`].
    #[must_use]
    pub const fn is_lazy(&self) -> bool {
        matches!(self, Self::Lazy(_))
    }

    /// Returns the inline byte buffer when resident in memory, or `None` for a lazy handle.
    #[must_use]
    pub const fn inline_bytes(&self) -> Option<&Arc<[u8]>> {
        match self {
            Self::Inline(bytes) => Some(bytes),
            Self::Lazy(_) => None,
        }
    }

    /// Returns the lazy handle when backed by an [`ImageRef`], or `None` for inline bytes.
    #[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)
    }
}

/// Bounded LRU cache of encoded image bytes keyed by loader index (`u32`).
///
/// Entries larger than the configured byte budget are skipped rather than evicting the rest of
/// the cache.
#[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 {
    /// Creates a new bounded LRU cache holding at most `max_bytes` of encoded image data.
    #[must_use]
    pub fn new(max_bytes: usize) -> Self {
        Self {
            max_bytes,
            inner: Mutex::new(LruBytesInner::default()),
        }
    }

    /// Returns the cached bytes and format for `index`, refreshing its recency timestamp.
    #[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))
    }

    /// Inserts `bytes` and `format` for `index`, evicting least-recently-used entries until the
    /// total cached bytes stay within the budget.
    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,
            },
        );
    }

    /// Returns the total bytes currently retained in the cache.
    #[must_use]
    pub fn total_bytes(&self) -> usize {
        self.inner.lock().map_or(0, |inner| inner.total_bytes)
    }

    /// Returns the number of cached entries.
    #[must_use]
    pub fn len(&self) -> usize {
        self.inner.lock().map_or(0, |inner| inner.entries.len())
    }

    /// Returns `true` when no entries are cached.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Removes all cached entries.
    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);
    }

    #[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);
    }
}