Skip to main content

vello_encoding/
resolve.rs

1// Copyright 2022 the Vello Authors
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4use bytemuck::{Pod, Zeroable};
5use peniko::{Extend, ImageData};
6use std::ops::Range;
7use std::sync::Arc;
8
9use super::{DrawTag, Encoding, PathTag, StreamOffsets, Style, Transform};
10
11use crate::glyph_cache::GlyphCache;
12use crate::image_cache::{ImageCache, Images};
13use crate::ramp_cache::{RampCache, Ramps};
14
15/// Layout of a packed encoding.
16#[derive(Clone, Copy, Debug, Default, Zeroable, Pod)]
17#[repr(C)]
18pub struct Layout {
19    /// Number of draw objects.
20    pub n_draw_objects: u32,
21    /// Number of paths.
22    pub n_paths: u32,
23    /// Number of clips.
24    pub n_clips: u32,
25    /// Start of binning data.
26    pub bin_data_start: u32,
27    /// Start of path tag stream.
28    pub path_tag_base: u32,
29    /// Start of path data stream.
30    pub path_data_base: u32,
31    /// Start of draw tag stream.
32    pub draw_tag_base: u32,
33    /// Start of draw data stream.
34    pub draw_data_base: u32,
35    /// Start of transform stream.
36    pub transform_base: u32,
37    /// Start of style stream.
38    pub style_base: u32,
39}
40
41impl Layout {
42    /// Creates a zeroed layout.
43    pub fn new() -> Self {
44        Self::default()
45    }
46
47    /// Returns the path tag stream.
48    pub fn path_tags<'a>(&self, data: &'a [u8]) -> &'a [PathTag] {
49        let start = self.path_tag_base as usize * 4;
50        let end = self.path_data_base as usize * 4;
51        bytemuck::cast_slice(&data[start..end])
52    }
53
54    pub fn path_tags_size(&self) -> u32 {
55        let start = self.path_tag_base * 4;
56        let end = self.path_data_base * 4;
57        end - start
58    }
59
60    /// Returns the path tag stream in chunks of 4.
61    pub fn path_tags_chunked<'a>(&self, data: &'a [u8]) -> &'a [u32] {
62        let start = self.path_tag_base as usize * 4;
63        let end = self.path_data_base as usize * 4;
64        bytemuck::cast_slice(&data[start..end])
65    }
66
67    /// Returns the path data stream.
68    pub fn path_data<'a>(&self, data: &'a [u8]) -> &'a [u8] {
69        let start = self.path_data_base as usize * 4;
70        let end = self.draw_tag_base as usize * 4;
71        bytemuck::cast_slice(&data[start..end])
72    }
73
74    /// Returns the draw tag stream.
75    pub fn draw_tags<'a>(&self, data: &'a [u8]) -> &'a [DrawTag] {
76        let start = self.draw_tag_base as usize * 4;
77        let end = self.draw_data_base as usize * 4;
78        bytemuck::cast_slice(&data[start..end])
79    }
80
81    /// Returns the draw data stream.
82    pub fn draw_data<'a>(&self, data: &'a [u8]) -> &'a [u32] {
83        let start = self.draw_data_base as usize * 4;
84        let end = self.transform_base as usize * 4;
85        bytemuck::cast_slice(&data[start..end])
86    }
87
88    /// Returns the transform stream.
89    pub fn transforms<'a>(&self, data: &'a [u8]) -> &'a [Transform] {
90        let start = self.transform_base as usize * 4;
91        let end = self.style_base as usize * 4;
92        bytemuck::cast_slice(&data[start..end])
93    }
94
95    /// Returns the style stream.
96    pub fn styles<'a>(&self, data: &'a [u8]) -> &'a [Style] {
97        let start = self.style_base as usize * 4;
98        bytemuck::cast_slice(&data[start..])
99    }
100}
101
102/// Resolves and packs an encoding that contains only paths with solid color
103/// fills.
104///
105/// Panics if the encoding contains any late bound resources (gradients, images
106/// or glyph runs).
107pub fn resolve_solid_paths_only(encoding: &Encoding, packed: &mut Vec<u8>) -> Layout {
108    assert!(
109        encoding.resources.patches.is_empty(),
110        "this resolve function doesn't support late bound resources"
111    );
112    let data = packed;
113    data.clear();
114    let mut layout = Layout {
115        n_paths: encoding.n_paths,
116        n_clips: encoding.n_clips,
117        ..Layout::default()
118    };
119    let SceneBufferSizes {
120        buffer_size,
121        path_tag_padded,
122    } = SceneBufferSizes::new(encoding, &StreamOffsets::default());
123    data.reserve(buffer_size);
124    // Path tag stream
125    layout.path_tag_base = size_to_words(data.len());
126    data.extend_from_slice(bytemuck::cast_slice(&encoding.path_tags));
127    for _ in 0..encoding.n_open_clips {
128        data.extend_from_slice(bytemuck::bytes_of(&PathTag::PATH));
129    }
130    data.resize(path_tag_padded, 0);
131    // Path data stream
132    layout.path_data_base = size_to_words(data.len());
133    data.extend_from_slice(bytemuck::cast_slice(&encoding.path_data));
134    // Draw tag stream
135    layout.draw_tag_base = size_to_words(data.len());
136    // Bin data follows draw info
137    layout.bin_data_start = encoding.draw_tags.iter().map(|tag| tag.info_size()).sum();
138    data.extend_from_slice(bytemuck::cast_slice(&encoding.draw_tags));
139    for _ in 0..encoding.n_open_clips {
140        data.extend_from_slice(bytemuck::bytes_of(&DrawTag::END_CLIP));
141    }
142    // Draw data stream
143    layout.draw_data_base = size_to_words(data.len());
144    data.extend_from_slice(bytemuck::cast_slice(&encoding.draw_data));
145    // Transform stream
146    layout.transform_base = size_to_words(data.len());
147    data.extend_from_slice(bytemuck::cast_slice(&encoding.transforms));
148    // Style stream
149    layout.style_base = size_to_words(data.len());
150    data.extend_from_slice(bytemuck::cast_slice(&encoding.styles));
151    layout.n_draw_objects = layout.n_paths;
152    assert_eq!(buffer_size, data.len());
153    layout
154}
155
156/// Resolver for late bound resources.
157#[derive(Default)]
158pub struct Resolver {
159    glyph_cache: GlyphCache,
160    glyphs: Vec<Arc<Encoding>>,
161    ramp_cache: RampCache,
162    image_cache: ImageCache,
163    pending_images: Vec<PendingImage>,
164    patches: Vec<ResolvedPatch>,
165}
166
167impl Resolver {
168    /// Limit the image atlas to `max_size` pixels per side; images that do
169    /// not fit after eviction are omitted and reported.
170    pub fn set_image_atlas_max(&mut self, max_size: u32) {
171        self.image_cache
172            .set_max_size(i32::try_from(max_size).unwrap_or(i32::MAX));
173    }
174
175    /// Images went for good: let a sparse atlas shrink within the next few
176    /// resolves instead of after many.
177    pub fn shrink_image_atlas_soon(&mut self) {
178        self.image_cache.shrink_soon();
179    }
180
181    /// What the image atlas cache holds now.
182    pub fn image_cache_stats(&self) -> crate::ImageCacheStats {
183        self.image_cache.stats()
184    }
185
186    /// Creates a new resource cache.
187    pub fn new() -> Self {
188        Self::default()
189    }
190
191    /// Marks the atlas entry for `image` as dirty.
192    ///
193    /// If `image` is already resident in the atlas and appears in a later resolve pass,
194    /// that pass will include it in the returned image uploads.
195    pub fn mark_image_dirty(&mut self, image: &ImageData) {
196        self.image_cache.mark_dirty(image);
197    }
198
199    /// Resolves late bound resources and packs an encoding. Returns the packed
200    /// layout and computed ramp data.
201    pub fn resolve<'a>(
202        &'a mut self,
203        encoding: &Encoding,
204        packed: &mut Vec<u8>,
205    ) -> (Layout, Ramps<'a>, Images<'a>) {
206        let resources = &encoding.resources;
207        if resources.patches.is_empty() {
208            let layout = resolve_solid_paths_only(encoding, packed);
209            return (layout, Ramps::default(), Images::default());
210        }
211        let patch_sizes = self.resolve_patches(encoding);
212        self.resolve_pending_images();
213        self.image_cache.finish_resolve();
214        let data = packed;
215        data.clear();
216        let mut layout = Layout {
217            n_paths: encoding.n_paths,
218            n_clips: encoding.n_clips,
219            ..Layout::default()
220        };
221        let SceneBufferSizes {
222            buffer_size,
223            path_tag_padded,
224        } = SceneBufferSizes::new(encoding, &patch_sizes);
225        data.reserve(buffer_size);
226        // Path tag stream
227        layout.path_tag_base = size_to_words(data.len());
228        {
229            let mut pos = 0;
230            let stream = &encoding.path_tags;
231            for patch in &self.patches {
232                if let ResolvedPatch::GlyphRun { index, glyphs, .. } = patch {
233                    layout.n_paths += 1;
234                    let stream_offset = resources.glyph_runs[*index].stream_offsets.path_tags;
235                    if pos < stream_offset {
236                        data.extend_from_slice(bytemuck::cast_slice(&stream[pos..stream_offset]));
237                        pos = stream_offset;
238                    }
239                    for glyph in &self.glyphs[glyphs.clone()] {
240                        data.extend_from_slice(bytemuck::bytes_of(&PathTag::TRANSFORM));
241                        data.extend_from_slice(bytemuck::cast_slice(&glyph.path_tags));
242                    }
243                    data.extend_from_slice(bytemuck::bytes_of(&PathTag::TRANSFORM));
244                    data.extend_from_slice(bytemuck::bytes_of(&PathTag::PATH));
245                }
246            }
247            if pos < stream.len() {
248                data.extend_from_slice(bytemuck::cast_slice(&stream[pos..]));
249            }
250            for _ in 0..encoding.n_open_clips {
251                data.extend_from_slice(bytemuck::bytes_of(&PathTag::PATH));
252            }
253            data.resize(path_tag_padded, 0);
254        }
255        // Path data stream
256        layout.path_data_base = size_to_words(data.len());
257        {
258            let mut pos = 0;
259            let stream = &encoding.path_data;
260            for patch in &self.patches {
261                if let ResolvedPatch::GlyphRun { index, glyphs, .. } = patch {
262                    let stream_offset = encoding.resources.glyph_runs[*index]
263                        .stream_offsets
264                        .path_data;
265                    if pos < stream_offset {
266                        data.extend_from_slice(bytemuck::cast_slice(&stream[pos..stream_offset]));
267                        pos = stream_offset;
268                    }
269                    for glyph in &self.glyphs[glyphs.clone()] {
270                        data.extend_from_slice(bytemuck::cast_slice(&glyph.path_data));
271                    }
272                }
273            }
274            if pos < stream.len() {
275                data.extend_from_slice(bytemuck::cast_slice(&stream[pos..]));
276            }
277        }
278        // Draw tag stream
279        layout.draw_tag_base = size_to_words(data.len());
280        // Bin data follows draw info
281        layout.bin_data_start = encoding.draw_tags.iter().map(|tag| tag.info_size()).sum();
282        {
283            data.extend_from_slice(bytemuck::cast_slice(&encoding.draw_tags));
284            for _ in 0..encoding.n_open_clips {
285                data.extend_from_slice(bytemuck::bytes_of(&DrawTag::END_CLIP));
286            }
287        }
288        // Draw data stream
289        layout.draw_data_base = size_to_words(data.len());
290        {
291            let mut pos = 0;
292            let stream = &encoding.draw_data;
293            for patch in &self.patches {
294                match patch {
295                    ResolvedPatch::Ramp {
296                        draw_data_offset,
297                        ramp_id,
298                        extend,
299                    } => {
300                        if pos < *draw_data_offset {
301                            data.extend_from_slice(bytemuck::cast_slice(
302                                &encoding.draw_data[pos..*draw_data_offset],
303                            ));
304                        }
305                        let index_mode = (ramp_id << 2) | *extend as u32;
306                        data.extend_from_slice(bytemuck::bytes_of(&index_mode));
307                        pos = *draw_data_offset + 1;
308                    }
309                    ResolvedPatch::GlyphRun { .. } => {}
310                    ResolvedPatch::Image {
311                        index,
312                        draw_data_offset,
313                    } => {
314                        if pos < *draw_data_offset {
315                            data.extend_from_slice(bytemuck::cast_slice(
316                                &encoding.draw_data[pos..*draw_data_offset],
317                            ));
318                        }
319                        if let Some((x, y)) = self.pending_images[*index].xy {
320                            let xy = (x << 16) | y;
321                            data.extend_from_slice(bytemuck::bytes_of(&xy));
322                            pos = *draw_data_offset + 1;
323                        } else {
324                            // If we get here, we failed to allocate a slot for this image in the atlas.
325                            // In this case, let's zero out the dimensions so we don't attempt to render
326                            // anything.
327                            // TODO: a better strategy: texture array? downsample large images?
328                            data.extend_from_slice(&[0_u8; 8]);
329                            pos = *draw_data_offset + 2;
330                        }
331                    }
332                }
333            }
334            if pos < stream.len() {
335                data.extend_from_slice(bytemuck::cast_slice(&stream[pos..]));
336            }
337        }
338        // Transform stream
339        layout.transform_base = size_to_words(data.len());
340        {
341            let mut pos = 0;
342            let stream = &encoding.transforms;
343            for patch in &self.patches {
344                if let ResolvedPatch::GlyphRun {
345                    index,
346                    glyphs: _,
347                    paint_transform,
348                    transform,
349                    scale,
350                    hint,
351                } = patch
352                {
353                    let run = &resources.glyph_runs[*index];
354                    let stream_offset = run.stream_offsets.transforms;
355                    if pos < stream_offset {
356                        data.extend_from_slice(bytemuck::cast_slice(&stream[pos..stream_offset]));
357                        pos = stream_offset;
358                    }
359                    if let Some(glyph_transform) = run.glyph_transform {
360                        for glyph in &resources.glyphs[run.glyphs.clone()] {
361                            let mut xform = *transform
362                                * Transform {
363                                    matrix: [1.0, 0.0, 0.0, -1.0],
364                                    translation: [glyph.x * scale, glyph.y * scale],
365                                }
366                                * glyph_transform;
367                            if *hint {
368                                xform.translation[1] = xform.translation[1].round();
369                            }
370                            data.extend_from_slice(bytemuck::bytes_of(&xform));
371                        }
372                    } else {
373                        for glyph in &resources.glyphs[run.glyphs.clone()] {
374                            let mut xform = *transform
375                                * Transform {
376                                    matrix: [1.0, 0.0, 0.0, -1.0],
377                                    translation: [glyph.x * scale, glyph.y * scale],
378                                };
379                            if *hint {
380                                xform.translation[1] = xform.translation[1].round();
381                            }
382                            data.extend_from_slice(bytemuck::bytes_of(&xform));
383                        }
384                    }
385                    data.extend_from_slice(bytemuck::bytes_of(paint_transform));
386                }
387            }
388            if pos < stream.len() {
389                data.extend_from_slice(bytemuck::cast_slice(&stream[pos..]));
390            }
391        }
392        // Style stream
393        layout.style_base = size_to_words(data.len());
394        {
395            let mut pos = 0;
396            let stream = &encoding.styles;
397            for patch in &self.patches {
398                if let ResolvedPatch::GlyphRun { index, glyphs, .. } = patch {
399                    let stream_offset = resources.glyph_runs[*index].stream_offsets.styles;
400                    if pos < stream_offset {
401                        data.extend_from_slice(bytemuck::cast_slice(&stream[pos..stream_offset]));
402                        pos = stream_offset;
403                    }
404                    for glyph in &self.glyphs[glyphs.clone()] {
405                        data.extend_from_slice(bytemuck::cast_slice(&glyph.styles));
406                    }
407                }
408            }
409            if pos < stream.len() {
410                data.extend_from_slice(bytemuck::cast_slice(&stream[pos..]));
411            }
412        }
413        self.glyphs.clear();
414        layout.n_draw_objects = layout.n_paths;
415        assert_eq!(buffer_size, data.len());
416        (layout, self.ramp_cache.ramps(), self.image_cache.images())
417    }
418
419    fn resolve_patches(&mut self, encoding: &Encoding) -> StreamOffsets {
420        self.ramp_cache.maintain();
421        self.glyphs.clear();
422        self.glyph_cache.maintain();
423        self.image_cache.begin_resolve();
424        self.pending_images.clear();
425        self.patches.clear();
426        let mut sizes = StreamOffsets::default();
427        let resources = &encoding.resources;
428        for patch in &resources.patches {
429            match patch {
430                Patch::Ramp {
431                    draw_data_offset,
432                    stops,
433                    extend,
434                } => {
435                    let ramp_id = self.ramp_cache.add(&resources.color_stops[stops.clone()]);
436                    self.patches.push(ResolvedPatch::Ramp {
437                        draw_data_offset: *draw_data_offset + sizes.draw_data,
438                        ramp_id,
439                        extend: *extend,
440                    });
441                }
442                Patch::GlyphRun { index } => {
443                    let mut run_sizes = StreamOffsets::default();
444                    let run = &resources.glyph_runs[*index];
445                    let glyphs = &resources.glyphs[run.glyphs.clone()];
446                    let coords = &resources.normalized_coords[run.normalized_coords.clone()];
447                    let paint_transform =
448                        run.transform * run.brush_transform.unwrap_or(Transform::IDENTITY);
449                    let mut hint = run.hint;
450                    let mut font_size = run.font_size;
451                    let mut transform = run.transform;
452                    let mut scale = 1.0;
453                    if hint {
454                        // If hinting was requested and our transform matrix is just a uniform
455                        // scale, then adjust our font size and cancel out the matrix. Otherwise,
456                        // disable hinting entirely.
457                        if transform.matrix[0] == transform.matrix[3]
458                            && transform.matrix[1] == 0.0
459                            && transform.matrix[2] == 0.0
460                        {
461                            scale = transform.matrix[0];
462                            font_size *= scale;
463                            transform.matrix = [1.0, 0.0, 0.0, 1.0];
464                        } else {
465                            hint = false;
466                        }
467                    }
468                    let Some(mut session) = self.glyph_cache.session(
469                        &run.font,
470                        bytemuck::cast_slice(coords),
471                        font_size,
472                        run.font_embolden,
473                        hint,
474                        &run.style,
475                    ) else {
476                        continue;
477                    };
478                    let glyph_start = self.glyphs.len();
479                    for glyph in glyphs {
480                        let (encoding, stream_sizes) =
481                            session.get_or_insert(glyph.id).unwrap_or_else(|| {
482                                // HACK: We pretend that the encoding was empty.
483                                // In theory, we should be able to skip this glyph, but there is also
484                                // a corresponding entry in `resources`, which means that we would
485                                // need to make the patching process skip this glyph.
486                                (Arc::new(Encoding::new()), StreamOffsets::default())
487                            });
488                        run_sizes.add(&stream_sizes);
489                        self.glyphs.push(encoding);
490                    }
491                    let glyph_end = self.glyphs.len();
492                    run_sizes.path_tags += glyphs.len() + 2;
493                    run_sizes.transforms += glyphs.len() + 1;
494                    sizes.add(&run_sizes);
495                    self.patches.push(ResolvedPatch::GlyphRun {
496                        index: *index,
497                        glyphs: glyph_start..glyph_end,
498                        paint_transform,
499                        transform,
500                        scale,
501                        hint,
502                    });
503                }
504                Patch::Image {
505                    draw_data_offset,
506                    image,
507                } => {
508                    let index = self.pending_images.len();
509                    self.pending_images.push(PendingImage {
510                        image: image.clone(),
511                        xy: None,
512                    });
513                    self.patches.push(ResolvedPatch::Image {
514                        index,
515                        draw_data_offset: *draw_data_offset + sizes.draw_data,
516                    });
517                }
518            }
519        }
520        sizes
521    }
522
523    fn resolve_pending_images(&mut self) {
524        'outer: loop {
525            self.image_cache.restart_resolve_pass();
526            // Loop over the images, attempting to allocate them all into the atlas.
527            for pending_image in &mut self.pending_images {
528                pending_image.xy = loop {
529                    if let Some(xy) = self.image_cache.get_or_insert(&pending_image.image) {
530                        break Some(xy);
531                    }
532                    if self.image_cache.can_fit_image(&pending_image.image)
533                        && self.image_cache.evict_stale_entries()
534                    {
535                        continue;
536                    }
537                    // We failed to allocate. Try to bump the atlas size.
538                    if self.image_cache.bump_size() {
539                        // We were able to increase the atlas size. Restart the outer loop.
540                        continue 'outer;
541                    } else if self.image_cache.can_fit_image(&pending_image.image)
542                        && self.image_cache.evict_superseded() != 0
543                    {
544                        // The atlas is at its maximum: what no pass drew this time makes room.
545                        continue;
546                    } else {
547                        // If the atlas is already maximum size, there's nothing we can do. Set
548                        // the xy field to None so this image isn't rendered and then carry on--
549                        // other images might still fit. Record the omission so the renderer can
550                        // report why the image is missing.
551                        self.image_cache.record_omission();
552                        break None;
553                    }
554                };
555            }
556            // If we made it here, we've either successfully allocated all images or we reached
557            // the maximum atlas size.
558            break;
559        }
560    }
561}
562
563/// Patch for a late bound resource.
564#[derive(Clone)]
565pub enum Patch {
566    /// Gradient ramp resource.
567    Ramp {
568        /// Byte offset to the ramp id in the draw data stream.
569        draw_data_offset: usize,
570        /// Range of the gradient stops in the resource set.
571        stops: Range<usize>,
572        /// Extend mode for the gradient.
573        extend: Extend,
574    },
575    /// Glyph run resource.
576    GlyphRun {
577        /// Index in the glyph run buffer.
578        index: usize,
579    },
580    /// Image resource.
581    Image {
582        /// Offset to the atlas coordinates in the draw data stream.
583        draw_data_offset: usize,
584        /// Underlying image data.
585        image: ImageData,
586    },
587}
588
589/// Image to be allocated in the atlas.
590#[derive(Clone, Debug)]
591struct PendingImage {
592    image: ImageData,
593    xy: Option<(u32, u32)>,
594}
595
596#[derive(Clone, Debug)]
597enum ResolvedPatch {
598    Ramp {
599        /// Offset to the ramp id in draw data stream.
600        draw_data_offset: usize,
601        /// Resolved ramp index.
602        ramp_id: u32,
603        /// Extend mode for the gradient.
604        extend: Extend,
605    },
606    GlyphRun {
607        /// Index of the original glyph run in the encoding.
608        index: usize,
609        /// Range into the glyphs encoding range buffer.
610        glyphs: Range<usize>,
611        /// Transform used for the run brush.
612        paint_transform: Transform,
613        /// Global transform.
614        transform: Transform,
615        /// Additional scale factor to apply to translation.
616        scale: f32,
617        /// Whether the glyph was hinted.
618        ///
619        /// This determines whether the y-coordinate of the final position
620        /// needs to be rounded.
621        hint: bool,
622    },
623    Image {
624        /// Index of pending image element.
625        index: usize,
626        /// Offset to the atlas location in the draw data stream.
627        draw_data_offset: usize,
628    },
629}
630
631struct SceneBufferSizes {
632    /// Full size of the scene buffer in bytes.
633    buffer_size: usize,
634    /// Padded length of the path tag stream in bytes.
635    path_tag_padded: usize,
636}
637
638impl SceneBufferSizes {
639    /// Computes common scene buffer sizes for the given encoding and patch
640    /// stream sizes.
641    fn new(encoding: &Encoding, patch_sizes: &StreamOffsets) -> Self {
642        let n_path_tags =
643            encoding.path_tags.len() + patch_sizes.path_tags + encoding.n_open_clips as usize;
644        let path_tag_padded = align_up(n_path_tags, 4 * crate::config::PATH_REDUCE_WG);
645        let buffer_size = path_tag_padded
646            + slice_size_in_bytes(&encoding.path_data, patch_sizes.path_data)
647            + slice_size_in_bytes(
648                &encoding.draw_tags,
649                patch_sizes.draw_tags + encoding.n_open_clips as usize,
650            )
651            + slice_size_in_bytes(&encoding.draw_data, patch_sizes.draw_data)
652            + slice_size_in_bytes(&encoding.transforms, patch_sizes.transforms)
653            + slice_size_in_bytes(&encoding.styles, patch_sizes.styles);
654        Self {
655            buffer_size,
656            path_tag_padded,
657        }
658    }
659}
660
661fn slice_size_in_bytes<T: Sized>(slice: &[T], extra: usize) -> usize {
662    (slice.len() + extra) * size_of::<T>()
663}
664
665fn size_to_words(byte_size: usize) -> u32 {
666    (byte_size / size_of::<u32>()) as u32
667}
668
669fn align_up(len: usize, alignment: u32) -> usize {
670    len + (len.wrapping_neg() & (alignment as usize - 1))
671}