Coverage Report

Created: 2026-12-01 06:30

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/read-fonts-0.47.0/src/mem.rs
Line
Count
Source
1
//! Short lived memory.
2
//!
3
//! For work whose size is not known until it runs, and which is finished with
4
//! the memory by the time it returns. Allocating for each such call can cost
5
//! more than the work itself.
6
7
use alloc::{vec, vec::Vec};
8
use bytemuck::{AnyBitPattern, NoUninit};
9
use core::mem::{align_of, size_of};
10
11
/// Calls `f` with a zeroed block of `size` bytes.
12
///
13
/// The block comes from the stack where it is small enough, and from the heap
14
/// otherwise. Sizes are bucketed so that a small request does not pay to zero
15
/// a block sized for the largest one.
16
590k
pub fn with_scratch<R>(size: usize, mut f: impl FnMut(&mut [u8]) -> R) -> R {
17
590k
    let mut result = None;
18
590k
    with_scratch_dyn(size, &mut |block| result = Some(f(block)));
read_fonts::mem::with_scratch::<core::option::Option<read_fonts::model::metrics::glyph::GlyphExtents<font_types::fixed::F48Dot16>>, read_fonts::model::metrics::glyph::varied_control_box::{closure#0}>::{closure#0}
Line
Count
Source
18
584k
    with_scratch_dyn(size, &mut |block| result = Some(f(block)));
Unexecuted instantiation: read_fonts::mem::with_scratch::<core::option::Option<font_types::fixed::F48Dot16>, read_fonts::model::metrics::glyph::glyf_v_origin_from_context::{closure#0}>::{closure#0}
Unexecuted instantiation: read_fonts::mem::with_scratch::<core::result::Result<read_fonts::model::glyph::outline::DrawnMetrics, read_fonts::model::error::Error>, <read_fonts::model::glyph::outline::glyphs::OutlineGlyph>::draw_unscaled_dyn::{closure#0}>::{closure#0}
Unexecuted instantiation: read_fonts::mem::with_scratch::<core::result::Result<read_fonts::model::glyph::outline::DrawnMetrics, read_fonts::model::error::Error>, <read_fonts::model::glyph::outline::glyphs::OutlineGlyph>::draw_unscaled_dyn::{closure#1}>::{closure#0}
Unexecuted instantiation: read_fonts::mem::with_scratch::<core::result::Result<read_fonts::model::glyph::outline::DrawnMetrics, read_fonts::model::error::Error>, <read_fonts::model::glyph::outline::glyphs::OutlineGlyph>::draw_dyn::{closure#3}>::{closure#0}
read_fonts::mem::with_scratch::<core::result::Result<read_fonts::model::glyph::outline::DrawnMetrics, read_fonts::model::error::Error>, <read_fonts::model::glyph::outline::glyphs::OutlineGlyph>::draw_dyn::{closure#1}>::{closure#0}
Line
Count
Source
18
6.25k
    with_scratch_dyn(size, &mut |block| result = Some(f(block)));
19
    // The block is always handed to `f`, so there is always a result.
20
590k
    result.unwrap()
21
590k
}
read_fonts::mem::with_scratch::<core::option::Option<read_fonts::model::metrics::glyph::GlyphExtents<font_types::fixed::F48Dot16>>, read_fonts::model::metrics::glyph::varied_control_box::{closure#0}>
Line
Count
Source
16
584k
pub fn with_scratch<R>(size: usize, mut f: impl FnMut(&mut [u8]) -> R) -> R {
17
584k
    let mut result = None;
18
584k
    with_scratch_dyn(size, &mut |block| result = Some(f(block)));
19
    // The block is always handed to `f`, so there is always a result.
20
584k
    result.unwrap()
21
584k
}
Unexecuted instantiation: read_fonts::mem::with_scratch::<core::option::Option<font_types::fixed::F48Dot16>, read_fonts::model::metrics::glyph::glyf_v_origin_from_context::{closure#0}>
Unexecuted instantiation: read_fonts::mem::with_scratch::<core::result::Result<read_fonts::model::glyph::outline::DrawnMetrics, read_fonts::model::error::Error>, <read_fonts::model::glyph::outline::glyphs::OutlineGlyph>::draw_unscaled_dyn::{closure#0}>
Unexecuted instantiation: read_fonts::mem::with_scratch::<core::result::Result<read_fonts::model::glyph::outline::DrawnMetrics, read_fonts::model::error::Error>, <read_fonts::model::glyph::outline::glyphs::OutlineGlyph>::draw_unscaled_dyn::{closure#1}>
Unexecuted instantiation: read_fonts::mem::with_scratch::<core::result::Result<read_fonts::model::glyph::outline::DrawnMetrics, read_fonts::model::error::Error>, <read_fonts::model::glyph::outline::glyphs::OutlineGlyph>::draw_dyn::{closure#3}>
read_fonts::mem::with_scratch::<core::result::Result<read_fonts::model::glyph::outline::DrawnMetrics, read_fonts::model::error::Error>, <read_fonts::model::glyph::outline::glyphs::OutlineGlyph>::draw_dyn::{closure#1}>
Line
Count
Source
16
6.25k
pub fn with_scratch<R>(size: usize, mut f: impl FnMut(&mut [u8]) -> R) -> R {
17
6.25k
    let mut result = None;
18
6.25k
    with_scratch_dyn(size, &mut |block| result = Some(f(block)));
19
    // The block is always handed to `f`, so there is always a result.
20
6.25k
    result.unwrap()
21
6.25k
}
22
23
/// Calls `f` with a zeroed block of `size` bytes, through a trait object so
24
/// that the buckets below are compiled once rather than once per caller.
25
590k
fn with_scratch_dyn(size: usize, f: &mut dyn FnMut(&mut [u8])) {
26
    // Not inlined, so a caller that lands in another bucket neither reserves
27
    // this one's stack nor zeroes it.
28
    #[inline(never)]
29
583k
    fn on_stack<const SIZE: usize>(size: usize, f: &mut dyn FnMut(&mut [u8])) {
30
583k
        f(&mut [0u8; SIZE][..size])
31
583k
    }
read_fonts::mem::with_scratch_dyn::on_stack::<4096>
Line
Count
Source
29
12.1k
    fn on_stack<const SIZE: usize>(size: usize, f: &mut dyn FnMut(&mut [u8])) {
30
12.1k
        f(&mut [0u8; SIZE][..size])
31
12.1k
    }
read_fonts::mem::with_scratch_dyn::on_stack::<8192>
Line
Count
Source
29
3.93k
    fn on_stack<const SIZE: usize>(size: usize, f: &mut dyn FnMut(&mut [u8])) {
30
3.93k
        f(&mut [0u8; SIZE][..size])
31
3.93k
    }
read_fonts::mem::with_scratch_dyn::on_stack::<512>
Line
Count
Source
29
556k
    fn on_stack<const SIZE: usize>(size: usize, f: &mut dyn FnMut(&mut [u8])) {
30
556k
        f(&mut [0u8; SIZE][..size])
31
556k
    }
read_fonts::mem::with_scratch_dyn::on_stack::<16384>
Line
Count
Source
29
1.63k
    fn on_stack<const SIZE: usize>(size: usize, f: &mut dyn FnMut(&mut [u8])) {
30
1.63k
        f(&mut [0u8; SIZE][..size])
31
1.63k
    }
read_fonts::mem::with_scratch_dyn::on_stack::<1024>
Line
Count
Source
29
4.90k
    fn on_stack<const SIZE: usize>(size: usize, f: &mut dyn FnMut(&mut [u8])) {
30
4.90k
        f(&mut [0u8; SIZE][..size])
31
4.90k
    }
read_fonts::mem::with_scratch_dyn::on_stack::<2048>
Line
Count
Source
29
3.68k
    fn on_stack<const SIZE: usize>(size: usize, f: &mut dyn FnMut(&mut [u8])) {
30
3.68k
        f(&mut [0u8; SIZE][..size])
31
3.68k
    }
32
590k
    if size <= 512 {
33
556k
        on_stack::<512>(size, f)
34
33.6k
    } else if size <= 1024 {
35
4.90k
        on_stack::<1024>(size, f)
36
28.7k
    } else if size <= 2048 {
37
3.68k
        on_stack::<2048>(size, f)
38
25.0k
    } else if size <= 4096 {
39
12.1k
        on_stack::<4096>(size, f)
40
12.8k
    } else if size <= 8192 {
41
3.93k
        on_stack::<8192>(size, f)
42
8.92k
    } else if size <= 16384 {
43
1.63k
        on_stack::<16384>(size, f)
44
    } else {
45
7.29k
        let mut block: Vec<u8> = vec![0; size];
46
7.29k
        f(&mut block)
47
    }
48
590k
}
49
50
/// Takes a `len` element slice of `T` off the front of `bytes`, aligning
51
/// first, and returns it along with what is left.
52
///
53
/// For carving one block into the several typed slices a caller needs, so that
54
/// the whole of it is one allocation rather than one each.
55
///
56
/// Returns `None` when the block is of insufficient size.
57
4.13M
pub fn take_slice<T>(bytes: &mut [u8], len: usize) -> Option<(&mut [T], &mut [u8])>
58
4.13M
where
59
4.13M
    T: AnyBitPattern + NoUninit,
60
{
61
4.13M
    if len == 0 {
62
2.25M
        return Some((Default::default(), bytes));
63
1.87M
    }
64
1.87M
    let padding = (bytes.as_ptr() as usize).wrapping_neg() & (align_of::<T>() - 1);
65
1.87M
    let bytes = bytes.get_mut(padding..)?;
66
    // A count that cannot be expressed in bytes is one no block can hold.
67
1.87M
    let byte_len = len.checked_mul(size_of::<T>())?;
68
1.87M
    if byte_len > bytes.len() {
69
0
        return None;
70
1.87M
    }
71
1.87M
    let (mine, rest) = bytes.split_at_mut(byte_len);
72
    // Bytemuck checks size and alignment; both hold by construction.
73
1.87M
    let mine = bytemuck::try_cast_slice_mut(mine).ok()?;
74
1.87M
    Some((mine, rest))
75
4.13M
}
Unexecuted instantiation: read_fonts::mem::take_slice::<font_types::point::Point<font_types::fixed::Fixed>>
Unexecuted instantiation: read_fonts::mem::take_slice::<font_types::point::Point<font_types::fixed::F26Dot6>>
read_fonts::mem::take_slice::<font_types::point::Point<f32>>
Line
Count
Source
57
2.36M
pub fn take_slice<T>(bytes: &mut [u8], len: usize) -> Option<(&mut [T], &mut [u8])>
58
2.36M
where
59
2.36M
    T: AnyBitPattern + NoUninit,
60
{
61
2.36M
    if len == 0 {
62
1.16M
        return Some((Default::default(), bytes));
63
1.19M
    }
64
1.19M
    let padding = (bytes.as_ptr() as usize).wrapping_neg() & (align_of::<T>() - 1);
65
1.19M
    let bytes = bytes.get_mut(padding..)?;
66
    // A count that cannot be expressed in bytes is one no block can hold.
67
1.19M
    let byte_len = len.checked_mul(size_of::<T>())?;
68
1.19M
    if byte_len > bytes.len() {
69
0
        return None;
70
1.19M
    }
71
1.19M
    let (mine, rest) = bytes.split_at_mut(byte_len);
72
    // Bytemuck checks size and alignment; both hold by construction.
73
1.19M
    let mine = bytemuck::try_cast_slice_mut(mine).ok()?;
74
1.19M
    Some((mine, rest))
75
2.36M
}
read_fonts::mem::take_slice::<font_types::point::Point<i32>>
Line
Count
Source
57
590k
pub fn take_slice<T>(bytes: &mut [u8], len: usize) -> Option<(&mut [T], &mut [u8])>
58
590k
where
59
590k
    T: AnyBitPattern + NoUninit,
60
{
61
590k
    if len == 0 {
62
590k
        return Some((Default::default(), bytes));
63
0
    }
64
0
    let padding = (bytes.as_ptr() as usize).wrapping_neg() & (align_of::<T>() - 1);
65
0
    let bytes = bytes.get_mut(padding..)?;
66
    // A count that cannot be expressed in bytes is one no block can hold.
67
0
    let byte_len = len.checked_mul(size_of::<T>())?;
68
0
    if byte_len > bytes.len() {
69
0
        return None;
70
0
    }
71
0
    let (mine, rest) = bytes.split_at_mut(byte_len);
72
    // Bytemuck checks size and alignment; both hold by construction.
73
0
    let mine = bytemuck::try_cast_slice_mut(mine).ok()?;
74
0
    Some((mine, rest))
75
590k
}
Unexecuted instantiation: read_fonts::mem::take_slice::<font_types::fixed::F2Dot14>
read_fonts::mem::take_slice::<read_fonts::tables::glyf::PointFlags>
Line
Count
Source
57
590k
pub fn take_slice<T>(bytes: &mut [u8], len: usize) -> Option<(&mut [T], &mut [u8])>
58
590k
where
59
590k
    T: AnyBitPattern + NoUninit,
60
{
61
590k
    if len == 0 {
62
0
        return Some((Default::default(), bytes));
63
590k
    }
64
590k
    let padding = (bytes.as_ptr() as usize).wrapping_neg() & (align_of::<T>() - 1);
65
590k
    let bytes = bytes.get_mut(padding..)?;
66
    // A count that cannot be expressed in bytes is one no block can hold.
67
590k
    let byte_len = len.checked_mul(size_of::<T>())?;
68
590k
    if byte_len > bytes.len() {
69
0
        return None;
70
590k
    }
71
590k
    let (mine, rest) = bytes.split_at_mut(byte_len);
72
    // Bytemuck checks size and alignment; both hold by construction.
73
590k
    let mine = bytemuck::try_cast_slice_mut(mine).ok()?;
74
590k
    Some((mine, rest))
75
590k
}
Unexecuted instantiation: read_fonts::mem::take_slice::<f64>
Unexecuted instantiation: read_fonts::mem::take_slice::<f32>
read_fonts::mem::take_slice::<u16>
Line
Count
Source
57
590k
pub fn take_slice<T>(bytes: &mut [u8], len: usize) -> Option<(&mut [T], &mut [u8])>
58
590k
where
59
590k
    T: AnyBitPattern + NoUninit,
60
{
61
590k
    if len == 0 {
62
501k
        return Some((Default::default(), bytes));
63
89.0k
    }
64
89.0k
    let padding = (bytes.as_ptr() as usize).wrapping_neg() & (align_of::<T>() - 1);
65
89.0k
    let bytes = bytes.get_mut(padding..)?;
66
    // A count that cannot be expressed in bytes is one no block can hold.
67
89.0k
    let byte_len = len.checked_mul(size_of::<T>())?;
68
89.0k
    if byte_len > bytes.len() {
69
0
        return None;
70
89.0k
    }
71
89.0k
    let (mine, rest) = bytes.split_at_mut(byte_len);
72
    // Bytemuck checks size and alignment; both hold by construction.
73
89.0k
    let mine = bytemuck::try_cast_slice_mut(mine).ok()?;
74
89.0k
    Some((mine, rest))
75
590k
}
76
77
#[cfg(test)]
78
mod tests {
79
    use super::*;
80
81
    #[test]
82
    fn every_bucket_hands_back_the_size_asked_for() {
83
        // A block from a larger bucket is trimmed to the request, so a caller
84
        // carving it into typed slices reads none of the slack.
85
        for size in [0, 1, 512, 513, 4096, 16384, 16385, 40000] {
86
            assert_eq!(with_scratch(size, |block| block.len()), size);
87
        }
88
    }
89
90
    #[test]
91
    fn a_block_arrives_zeroed() {
92
        // A caller may write every field before reading it, but carving a
93
        // block into typed slices reads it as those types first.
94
        for size in [8, 700, 20000] {
95
            assert!(with_scratch(size, |block| block
96
                .iter()
97
                .all(|byte| *byte == 0)));
98
        }
99
    }
100
101
    #[test]
102
    fn a_block_is_carved_into_aligned_slices() {
103
        with_scratch(64, |block| {
104
            let (first, rest) = take_slice::<u32>(block, 3).unwrap();
105
            assert_eq!(first.len(), 3);
106
            assert_eq!(first.as_ptr() as usize % align_of::<u32>(), 0);
107
            let (second, rest) = take_slice::<u16>(rest, 5).unwrap();
108
            assert_eq!(second.len(), 5);
109
            assert_eq!(second.as_ptr() as usize % align_of::<u16>(), 0);
110
            // Three `u32` and five `u16` leave 42 of the 64 bytes, less
111
            // whatever aligning the second slice cost.
112
            assert!(rest.len() <= 42, "{} left", rest.len());
113
            first[0] = 7;
114
            second[4] = 9;
115
        });
116
    }
117
118
    #[test]
119
    fn an_empty_slice_takes_nothing() {
120
        // A caller whose slice is unused still asks for it, so asking for
121
        // none of something is an answer rather than a failure.
122
        let mut block = [0u8; 4];
123
        let (taken, rest) = take_slice::<u64>(&mut block, 0).unwrap();
124
        assert!(taken.is_empty());
125
        assert_eq!(rest.len(), 4);
126
    }
127
128
    /// A block whose first byte is deliberately not aligned for `i32`.
129
    fn unaligned(block: &mut [u8]) -> &mut [u8] {
130
        let base = block.as_ptr() as usize;
131
        let offset = usize::from(base % align_of::<i32>() == 0);
132
        let block = &mut block[offset..];
133
        assert_ne!(block.as_ptr() as usize % align_of::<i32>(), 0);
134
        block
135
    }
136
137
    #[test]
138
    fn an_unaligned_block_is_aligned_before_anything_is_taken() {
139
        let mut block = [0u8; 40];
140
        let (taken, _) = take_slice::<i32>(unaligned(&mut block), 8).unwrap();
141
        assert_eq!(taken.as_ptr() as usize % align_of::<i32>(), 0);
142
    }
143
144
    #[test]
145
    fn aligning_comes_out_of_the_block() {
146
        // 40 bytes hold ten `i32`, but not once some of them have gone to
147
        // aligning the first.
148
        let mut block = [0u8; 40];
149
        assert!(take_slice::<i32>(unaligned(&mut block), 10).is_none());
150
    }
151
152
    #[test]
153
    fn a_block_too_small_for_what_is_asked_refuses() {
154
        let mut block = [0u8; 8];
155
        assert!(take_slice::<u32>(&mut block, 3).is_none());
156
        // What one slice takes is gone for the next, padding included, so a
157
        // block holding two of something holds neither twice.
158
        let (first, rest) = take_slice::<u32>(&mut block, 1).unwrap();
159
        assert_eq!(first.len(), 1);
160
        assert!(take_slice::<u32>(rest, 2).is_none());
161
        // Nor can it hold a count that is not a size at all.
162
        assert!(take_slice::<u32>(&mut block, usize::MAX).is_none());
163
    }
164
}