From 83e3af9df6e83696e60483c0c363fe677f8cdcd7 Mon Sep 17 00:00:00 2001 From: Behdad Esfahbod Date: Sat, 3 Oct 2026 16:57:24 -0600 Subject: [PATCH 01/15] [rust] Update to new rust stack API --- src/rust/Cargo.toml | 8 ++-- src/rust/font.rs | 4 +- src/rust/shape.rs | 108 ++++++++++++++++++++++---------------------- 3 files changed, 61 insertions(+), 59 deletions(-) diff --git a/src/rust/Cargo.toml b/src/rust/Cargo.toml index 3b78f303a..a01965483 100644 --- a/src/rust/Cargo.toml +++ b/src/rust/Cargo.toml @@ -4,10 +4,10 @@ edition = "2021" rust-version = "1.87.0" [dependencies] -harfrust = { version = "0.13.3", features = ["experimental_font_api"], optional = true } -# harfrust = { git = "https://github.com/harfbuzz/harfrust", optional = true } -read-fonts = "0.43.*" -skrifa = { version = "0.46.*", optional = true } +# harfrust = { version = "0.13.3", optional = true } +harfrust = { git = "https://github.com/harfbuzz/harfrust", optional = true } +read-fonts = "0.45.*" +skrifa = { version = "0.48.*", optional = true } smallvec = "1.*" [lib] diff --git a/src/rust/font.rs b/src/rust/font.rs index 3aa3f1007..5e336439b 100644 --- a/src/rust/font.rs +++ b/src/rust/font.rs @@ -338,7 +338,7 @@ extern "C" fn _hb_fontations_get_glyph_v_advances( let coords = data.location.coords(); if !coords.is_empty() { advance += vert_vars - .advance_height_delta(glyph_id, coords) + .advance_delta(glyph_id, coords) .unwrap_or_default() .to_f32(); } @@ -391,7 +391,7 @@ extern "C" fn _hb_fontations_get_glyph_v_origin( let coords = data.location.coords(); if !coords.is_empty() { y_origin += vert_vars - .v_org_delta(glyph_id, coords) + .v_origin_y_delta(glyph_id, coords) .unwrap_or_default() .to_f32(); } diff --git a/src/rust/shape.rs b/src/rust/shape.rs index fa81c25c2..f31594377 100644 --- a/src/rust/shape.rs +++ b/src/rust/shape.rs @@ -10,12 +10,10 @@ use std::ptr::null_mut; use std::sync::Arc; use harfrust::{ - font::{ - AdvanceWidthBatch, BuiltinFontFuncs, Font, FontBlob, FontFuncs, FontInstance, - FontTableFunction, NominalGlyphBatch, - }, - GlyphExtents, GlyphFlags as HRGlyphFlags, GlyphId, GlyphInfo as HRGlyphInfo, - GlyphPosition as HRGlyphPosition, NormalizedCoord, ShapeOptions, Tag, + font::{Blob, Font, NormalizedCoord, TableFunction}, + Advances, FontFuncs, GlyphExtents, GlyphFlags as HRGlyphFlags, GlyphId, + GlyphInfo as HRGlyphInfo, GlyphPosition as HRGlyphPosition, NominalGlyphs, ShapeOptions, + ShaperFont, Tag, }; use smallvec::SmallVec; @@ -103,7 +101,7 @@ pub unsafe extern "C" fn _hb_harfrust_shaper_face_data_create_rs( ) -> *mut c_void { let face_index = hb_face_get_index(face); let hb_face = HbFace::new(face); - let table_fn = FontTableFunction::new(Arc::new(move |tag| { + let table_fn = TableFunction::new(Arc::new(move |tag| { let blob = hb_face.reference_table(tag); if blob.is_null() { return None; @@ -114,12 +112,12 @@ pub unsafe extern "C" fn _hb_harfrust_shaper_face_data_create_rs( } return None; } - Some(FontBlob::Shared(Arc::new(HbBlob(blob)))) + Some(Blob::Shared(Arc::new(HbBlob(blob)))) })); let font = match Font::new(table_fn, face_index) { - Ok(font) => font, - Err(_) => return null_mut(), + Some(font) => font, + None => return null_mut(), }; let hr_face_data = Box::new(HBHarfRustFaceData { font }); @@ -134,7 +132,7 @@ pub unsafe extern "C" fn _hb_harfrust_shaper_face_data_destroy_rs(data: *mut c_v } pub struct HBHarfRustFontData { - instance: FontInstance, + instance: Font, x_scale: i32, y_scale: i32, ptem: Option, @@ -145,7 +143,7 @@ struct HBHarfBuzzFontFuncs { } impl FontFuncs for HBHarfBuzzFontFuncs { - fn nominal_glyph(&mut self, _: &BuiltinFontFuncs, c: u32) -> Option { + fn nominal_glyph(&self, _: &ShaperFont, c: u32) -> Option { let mut glyph = 0; if unsafe { hb_font_get_nominal_glyph(self.font, c, &mut glyph) } != 0 { Some(GlyphId::new(glyph)) @@ -154,7 +152,7 @@ impl FontFuncs for HBHarfBuzzFontFuncs { } } - fn variant_glyph(&mut self, _: &BuiltinFontFuncs, c: u32, vs: u32) -> Option { + fn variation_glyph(&self, _: &ShaperFont, c: u32, vs: u32) -> Option { let mut glyph = 0; if unsafe { hb_font_get_variation_glyph(self.font, c, vs, &mut glyph) } != 0 { Some(GlyphId::new(glyph)) @@ -163,11 +161,11 @@ impl FontFuncs for HBHarfBuzzFontFuncs { } } - fn advance_width(&mut self, _: &BuiltinFontFuncs, glyph: GlyphId) -> i32 { + fn glyph_h_advance(&self, _: &ShaperFont, glyph: GlyphId) -> i32 { unsafe { hb_font_get_glyph_h_advance(self.font, glyph.to_u32()) } } - fn populate_advance_widths(&mut self, _: &BuiltinFontFuncs, batch: AdvanceWidthBatch<'_>) { + fn glyph_h_advances(&self, _: &ShaperFont, batch: Advances<'_>) { let raw = batch.into_raw(); unsafe { hb_font_get_glyph_h_advances( @@ -181,11 +179,7 @@ impl FontFuncs for HBHarfBuzzFontFuncs { } } - fn populate_nominal_glyphs( - &mut self, - _: &BuiltinFontFuncs, - batch: NominalGlyphBatch<'_>, - ) -> usize { + fn nominal_glyphs(&self, _: &ShaperFont, batch: NominalGlyphs<'_>) -> usize { let raw = batch.into_raw(); unsafe { hb_font_get_nominal_glyphs( @@ -199,11 +193,11 @@ impl FontFuncs for HBHarfBuzzFontFuncs { } } - fn advance_height(&mut self, _: &BuiltinFontFuncs, glyph: GlyphId) -> i32 { + fn glyph_v_advance(&self, _: &ShaperFont, glyph: GlyphId) -> i32 { unsafe { hb_font_get_glyph_v_advance(self.font, glyph.to_u32()) } } - fn vertical_origin(&mut self, _: &BuiltinFontFuncs, glyph: GlyphId) -> (i32, i32) { + fn glyph_v_origin(&self, _: &ShaperFont, glyph: GlyphId) -> (i32, i32) { let mut x = 0; let mut y = 0; unsafe { @@ -212,7 +206,7 @@ impl FontFuncs for HBHarfBuzzFontFuncs { (x, y) } - fn extents(&mut self, _: &BuiltinFontFuncs, glyph: GlyphId) -> Option { + fn glyph_extents(&self, _: &ShaperFont, glyph: GlyphId) -> Option { let mut extents = hb_glyph_extents_t { x_bearing: 0, y_bearing: 0, @@ -232,7 +226,7 @@ impl FontFuncs for HBHarfBuzzFontFuncs { } } -fn font_to_instance(font: *mut hb_font_t, font_ref: &Font) -> FontInstance { +fn font_to_instance(font: *mut hb_font_t, font_ref: &Font) -> Font { let mut num_coords: u32 = 0; let coords = unsafe { hb_font_get_var_coords_normalized(font, &mut num_coords) }; let coords = if coords.is_null() { @@ -241,7 +235,8 @@ fn font_to_instance(font: *mut hb_font_t, font_ref: &Font) -> FontInstance { unsafe { std::slice::from_raw_parts(coords, num_coords as usize) } }; let coords = coords.iter().map(|&v| NormalizedCoord::from_bits(v as i16)); - FontInstance::builder(font_ref) + font_ref + .instance_builder() .normalized_coords(coords) .build() } @@ -290,13 +285,13 @@ fn hb_language_to_hr_language(language: hb_language_t) -> Option *mut c_void { - let hr_buffer = Box::new(harfrust::UnicodeBuffer::new()); + let hr_buffer = Box::new(harfrust::Buffer::new()); Box::into_raw(hr_buffer) as *mut c_void } #[unsafe(no_mangle)] pub unsafe extern "C" fn _hb_harfrust_buffer_destroy_rs(data: *mut c_void) { - let data = data as *mut harfrust::UnicodeBuffer; + let data = data as *mut harfrust::Buffer; let _hr_buffer = Box::from_raw(data); } @@ -377,41 +372,41 @@ pub unsafe extern "C" fn _hb_harfrust_shape_rs( num_features: u32, ) -> hb_bool_t { let font_data = font_data as *const HBHarfRustFontData; - let hr_buffer_box = hr_buffer_box as *mut harfrust::UnicodeBuffer; - let mut hr_buffer_box = Box::from_raw(hr_buffer_box); - let mut hr_buffer = *hr_buffer_box; + let hr_buffer = &mut *(hr_buffer_box as *mut harfrust::Buffer); + hr_buffer.clear(); let shape_plan = (shape_plan as *const harfrust::ShapePlan).as_ref(); // Set buffer properties let cluster_level = hb_buffer_get_cluster_level(buffer); let cluster_level = match cluster_level { hb_buffer_cluster_level_t_HB_BUFFER_CLUSTER_LEVEL_MONOTONE_GRAPHEMES => { - harfrust::BufferClusterLevel::MonotoneGraphemes + harfrust::ClusterLevel::MonotoneGraphemes } hb_buffer_cluster_level_t_HB_BUFFER_CLUSTER_LEVEL_MONOTONE_CHARACTERS => { - harfrust::BufferClusterLevel::MonotoneCharacters + harfrust::ClusterLevel::MonotoneCharacters } hb_buffer_cluster_level_t_HB_BUFFER_CLUSTER_LEVEL_CHARACTERS => { - harfrust::BufferClusterLevel::Characters + harfrust::ClusterLevel::Characters } hb_buffer_cluster_level_t_HB_BUFFER_CLUSTER_LEVEL_GRAPHEMES => { - harfrust::BufferClusterLevel::Graphemes + harfrust::ClusterLevel::Graphemes } - _ => harfrust::BufferClusterLevel::default(), + _ => harfrust::ClusterLevel::MonotoneGraphemes, }; hr_buffer.set_cluster_level(cluster_level); let flags = hb_buffer_get_flags(buffer); hr_buffer.set_flags(harfrust::BufferFlags::from_bits_truncate(flags as u32)); let not_found_variation_selector_glyph = hb_buffer_get_not_found_variation_selector_glyph(buffer); - if not_found_variation_selector_glyph != u32::MAX { - hr_buffer.set_not_found_variation_selector_glyph(not_found_variation_selector_glyph); - } + hr_buffer.set_not_found_variation_selector_glyph( + (not_found_variation_selector_glyph != u32::MAX) + .then_some(not_found_variation_selector_glyph), + ); if let Some(plan) = shape_plan { // Language is only used to build the plan; shaping with an explicit // plan reads its cached segment properties instead of buffer language. - hr_buffer.set_script(plan.script().unwrap_or(harfrust::script::UNKNOWN)); + hr_buffer.set_script(Some(plan.script().unwrap_or(harfrust::Script::UNKNOWN))); hr_buffer.set_direction(plan.direction()); } else { // Convert segment properties when shaping without a cached plan. @@ -419,7 +414,7 @@ pub unsafe extern "C" fn _hb_harfrust_shape_rs( let language = hb_buffer_get_language(buffer); let direction = hb_buffer_get_direction(buffer); let script = harfrust::Script::from_iso15924_tag(Tag::from_u32(script as u32)) - .unwrap_or(harfrust::script::UNKNOWN); + .unwrap_or(harfrust::Script::UNKNOWN); let language = hb_language_to_hr_language(language); let direction = match direction { hb_direction_t_HB_DIRECTION_LTR => harfrust::Direction::LeftToRight, @@ -428,9 +423,9 @@ pub unsafe extern "C" fn _hb_harfrust_shape_rs( hb_direction_t_HB_DIRECTION_BTT => harfrust::Direction::BottomToTop, _ => harfrust::Direction::Invalid, }; - hr_buffer.set_script(script); + hr_buffer.set_script(Some(script)); if let Some(lang) = language { - hr_buffer.set_language(lang); + hr_buffer.set_language(Some(lang)); } hr_buffer.set_direction(direction); } @@ -449,20 +444,25 @@ pub unsafe extern "C" fn _hb_harfrust_shape_rs( hr_buffer.set_post_context_codepoints(post_context); let features = hb_feature_to_hr_feature(features, num_features); - let mut font_funcs = HBHarfBuzzFontFuncs { font }; + let font_funcs = HBHarfBuzzFontFuncs { font }; + let shaper_font = ShaperFont::new(&(*font_data).instance) + .with_scale_separate((*font_data).x_scale, (*font_data).y_scale) + .with_font_funcs(Some(&font_funcs)); let options = ShapeOptions::new() .plan(shape_plan) - .scale_separate(Some(((*font_data).x_scale, (*font_data).y_scale))) .point_size((*font_data).ptem) - .features(&features) - .font_funcs(Some(&mut font_funcs)); - let glyphs = harfrust::shape(&(*font_data).instance, hr_buffer, options); + .features(&features); + if harfrust::shape(&shaper_font, hr_buffer, options).is_err() + || !hr_buffer.allocation_successful() + { + return false as hb_bool_t; + } hb_buffer_set_content_type( buffer, hb_buffer_content_type_t_HB_BUFFER_CONTENT_TYPE_GLYPHS, ); - let count = glyphs.len(); + let count = hr_buffer.len(); hb_buffer_set_length(buffer, count as u32); let mut count_out: u32 = 0; let infos = hb_buffer_get_glyph_infos(buffer, &mut count_out); @@ -471,12 +471,14 @@ pub unsafe extern "C" fn _hb_harfrust_shape_rs( return false as hb_bool_t; } - std::ptr::copy_nonoverlapping(glyphs.glyph_infos().as_ptr().cast(), infos, count); - std::ptr::copy_nonoverlapping(glyphs.glyph_positions().as_ptr().cast(), positions, count); + std::ptr::copy_nonoverlapping(hr_buffer.glyph_infos().as_ptr().cast(), infos, count); + std::ptr::copy_nonoverlapping( + hr_buffer.glyph_positions().as_ptr().cast(), + positions, + count, + ); - let hr_buffer = glyphs.clear(); - *hr_buffer_box = hr_buffer; // Move the buffer back into the box - let _ = Box::into_raw(hr_buffer_box); // Prevent double free + hr_buffer.clear(); true as hb_bool_t } From 600f1cc8ae62f8dd0266f0bda63ca2251cc8f73e Mon Sep 17 00:00:00 2001 From: Behdad Esfahbod Date: Sat, 3 Oct 2026 17:25:05 -0600 Subject: [PATCH 02/15] [rust] Use read-fonts model for Fontations font functions Move character mapping, line and glyph metrics, vertical origins, and glyph names to the new Font model. Use its batched advance APIs while preserving horizontal rounding and HarfBuzz fallback callbacks. Share the blob owner with the shaper and remove the metrics lifetime transmute. Enable two existing vertical variation regressions for Fontations and add strided batch advance coverage. Tests: ninja -C build lib; meson test -C build (281 passed, 1 skipped). Font-only and shape-only cargo checks also passed; the shape-only check used CARGO_INCREMENTAL=0 after a nightly compiler crash. Assisted-by: OpenAI Codex --- src/rust/font.rs | 386 ++++++++---------- src/rust/lib.rs | 30 ++ src/rust/shape.rs | 27 +- test/api/test-font.c | 79 ++++ test/shape/data/in-house/tests/vertical.tests | 3 +- 5 files changed, 290 insertions(+), 235 deletions(-) diff --git a/src/rust/font.rs b/src/rust/font.rs index 5e336439b..b01e29af8 100644 --- a/src/rust/font.rs +++ b/src/rust/font.rs @@ -1,29 +1,30 @@ -use super::hb::*; +use super::{hb::*, HbBlob}; use std::collections::HashMap; use std::ffi::c_void; -use std::mem::transmute; use std::ptr::null_mut; use std::sync::atomic::{AtomicPtr, AtomicU32, Ordering}; -use std::sync::Mutex; +use std::sync::{Arc, Mutex}; + +use read_fonts::model::{ + metrics::{GlyphExtents, LineExtents, Scale, ScaledGlyphMetrics}, + Blob, Font, NormalizedCoord, +}; +use read_fonts::types::{BoundingBox as FontBounds, F48Dot16, GlyphId}; +use read_fonts::FontRef; use skrifa::bitmap::{BitmapFormat, BitmapGlyph, BitmapStrikes, Origin}; -use skrifa::charmap::Charmap; -use skrifa::charmap::MapVariant::{UseDefault, Variant}; use skrifa::color::ColorGlyphCollection; -use skrifa::font::FontRef; -use skrifa::instance::{Location, NormalizedCoord, Size}; -use skrifa::metrics::GlyphMetrics; -use skrifa::raw::tables::vmtx::Vmtx; -use skrifa::raw::tables::vorg::Vorg; -use skrifa::raw::tables::vvar::Vvar; -use skrifa::raw::TableProvider; +use skrifa::instance::Size; +use skrifa::MetadataProvider; use skrifa::OutlineGlyphCollection; -use skrifa::{GlyphId, GlyphNames, MetadataProvider}; #[cfg(feature = "draw")] use skrifa::outline::{pen::OutlinePen, DrawSettings}; +#[cfg(feature = "paint")] +use read_fonts::TableProvider; + #[cfg(feature = "paint")] use skrifa::{ bitmap::BitmapData, @@ -35,35 +36,28 @@ use skrifa::{ // A struct for storing your “fontations” data #[repr(C)] struct FontationsData<'a> { - face_blob: *mut hb_blob_t, + face_blob: Arc, font: *mut hb_font_t, - font_ref: FontRef<'a>, - char_map: Charmap<'a>, outline_glyphs: OutlineGlyphCollection<'a>, color_glyphs: ColorGlyphCollection<'a>, cbdt_strikes: Option>, sbix_strikes: Option>, - glyph_names: GlyphNames<'a>, size: Size, - vert_metrics: Option>, - vert_origin: Option>, - vert_vars: Option>, // Mutex for the below mutex: Mutex<()>, serial: AtomicU32, x_mult: f32, y_mult: f32, - location: Location, - glyph_metrics: Option>, + instance: Font, } impl FontationsData<'_> { unsafe fn from_hb_font(font: *mut hb_font_t) -> Option { let face_index = hb_face_get_index(hb_font_get_face(font)); - let face_blob = hb_face_reference_blob(hb_font_get_face(font)); - let blob_length = hb_blob_get_length(face_blob); - let blob_data: *const u8 = hb_blob_get_data(face_blob, null_mut()).cast(); + let face_blob = Arc::new(HbBlob(hb_face_reference_blob(hb_font_get_face(font)))); + let blob_length = hb_blob_get_length(face_blob.0); + let blob_data: *const u8 = hb_blob_get_data(face_blob.0, null_mut()).cast(); if blob_data.is_null() { return None; } @@ -75,7 +69,7 @@ impl FontationsData<'_> { Err(_) => return None, }; - let char_map = Charmap::new(&font_ref); + let instance = Font::new(Blob::Shared(face_blob.clone()), face_index)?; let outline_glyphs = font_ref.outline_glyphs(); @@ -84,34 +78,21 @@ impl FontationsData<'_> { let cbdt_strikes = BitmapStrikes::with_format(&font_ref, BitmapFormat::Cbdt); let sbix_strikes = BitmapStrikes::with_format(&font_ref, BitmapFormat::Sbix); - let glyph_names = font_ref.glyph_names(); - let upem = hb_face_get_upem(hb_font_get_face(font)); - let vert_metrics = font_ref.vmtx().ok(); - let vert_origin = font_ref.vorg().ok(); - let vert_vars = font_ref.vvar().ok(); - let mut data = FontationsData { face_blob, font, - font_ref, - char_map, outline_glyphs, color_glyphs, cbdt_strikes, sbix_strikes, - glyph_names, size: Size::new(upem as f32), - vert_metrics, - vert_origin, - vert_vars, mutex: Mutex::new(()), x_mult: 1.0, y_mult: 1.0, serial: AtomicU32::new(u32::MAX), - location: Location::default(), - glyph_metrics: None, + instance, }; data.check_for_updates(); @@ -142,38 +123,97 @@ impl FontationsData<'_> { } else { std::slice::from_raw_parts(coords, num_coords as usize) }; - let all_zeros = coords.iter().all(|&x| x == 0); - // if all zeros, use Location::default() - // otherwise, use the provided coords. - // This currently doesn't seem to have a perf effect on fontations, but it's a good idea to - // check if the coords are all zeros before creating a Location. - self.location = if all_zeros { - Location::default() - } else { - let mut location = Location::new(num_coords as usize); - let coords_mut = location.coords_mut(); - coords_mut - .iter_mut() - .zip(coords.iter().map(|v| NormalizedCoord::from_bits(*v as i16))) - .for_each(|(dest, source)| *dest = source); - location - }; - - let location = transmute::<&Location, &Location>(&self.location); - self.glyph_metrics = Some(self.font_ref.glyph_metrics(self.size, location)); + self.instance = self + .instance + .instance_builder() + .normalized_coords(coords.iter().map(|v| NormalizedCoord::from_bits(*v as i16))) + .build(); self.serial.store(font_serial, Ordering::Release); } fn check_for_updates(&mut self) { unsafe { self._check_for_updates() } } + + fn scale(&self) -> FontationsScale { + FontationsScale { + x_mult: self.x_mult, + y_mult: self.y_mult, + } + } + + fn glyph_metrics(&self) -> ScaledGlyphMetrics<'_, 'static, FontationsScale> { + self.instance.glyph_metrics().scaled(self.scale()) + } } extern "C" fn _hb_fontations_data_destroy(font_data: *mut c_void) { - let data = unsafe { Box::from_raw(font_data as *mut FontationsData) }; + let _data = unsafe { Box::from_raw(font_data as *mut FontationsData) }; +} +#[derive(Clone, Copy)] +struct FontationsScale { + x_mult: f32, + y_mult: f32, +} + +impl Scale for FontationsScale { + // Keep intermediate sums wide when combining HarfBuzz callback results. + type Value = i64; + + fn add(a: i64, b: i64) -> i64 { + a.saturating_add(b) + } + + fn sub(a: i64, b: i64) -> i64 { + a.saturating_sub(b) + } + + fn half(value: i64) -> i64 { + value >> 1 + } + + fn scale_x(&self, value: F48Dot16) -> i64 { + (value.to_f32() * self.x_mult).round() as hb_position_t as i64 + } + + fn scale_y(&self, value: F48Dot16) -> i64 { + (value.to_f32() * self.y_mult).round() as hb_position_t as i64 + } + + fn scale_glyph_extents(&self, extents: GlyphExtents) -> GlyphExtents { + let x_bearing = self.scale_x(extents.x_bearing); + let y_bearing = self.scale_y(extents.y_bearing); + GlyphExtents { + x_bearing, + y_bearing, + width: self.scale_x(extents.x_bearing.saturating_add(extents.width)) - x_bearing, + height: y_bearing - self.scale_y(extents.y_bearing.saturating_sub(extents.height)), + } + } + + fn scale_rect(&self, bounds: FontBounds) -> FontBounds { + FontBounds { + x_min: self.scale_x(bounds.x_min), + y_min: self.scale_y(bounds.y_min), + x_max: self.scale_x(bounds.x_max), + y_max: self.scale_y(bounds.y_max), + } + } +} + +fn hb_position(value: i64) -> hb_position_t { + value.clamp(hb_position_t::MIN as i64, hb_position_t::MAX as i64) as hb_position_t +} + +fn font_line_extents(font: *mut hb_font_t) -> LineExtents { + let mut extents: hb_font_extents_t = unsafe { std::mem::zeroed() }; unsafe { - hb_blob_destroy(data.face_blob); + hb_font_get_extents_for_direction(font, hb_direction_t_HB_DIRECTION_LTR, &mut extents); + } + LineExtents { + ascender: extents.ascender as i64, + descender: extents.descender as i64, } } @@ -250,11 +290,11 @@ extern "C" fn _hb_fontations_get_nominal_glyphs( _user_data: *mut ::std::os::raw::c_void, ) -> ::std::os::raw::c_uint { let data = unsafe { &*(font_data as *const FontationsData) }; - let char_map = &data.char_map; + let char_map = data.instance.charmap(); for i in 0..count { let unicode = struct_at_offset(first_unicode, i, unicode_stride); - let Some(glyph) = char_map.map(unicode) else { + let Some(glyph) = char_map.map_unicode(unicode) else { return i; }; let glyph_id = glyph.to_u32() as hb_codepoint_t; @@ -273,21 +313,16 @@ extern "C" fn _hb_fontations_get_variation_glyph( ) -> hb_bool_t { let data = unsafe { &*(font_data as *const FontationsData) }; - let char_map = &data.char_map; - - match char_map.map_variant(unicode, variation_selector) { - Some(Variant(glyph_id)) => { + match data + .instance + .charmap() + .map_unicode_variant(unicode, variation_selector) + { + Some(glyph_id) => { unsafe { *glyph = glyph_id.to_u32() as hb_codepoint_t }; true as hb_bool_t } - Some(UseDefault) => match char_map.map(unicode) { - Some(glyph_id) => { - unsafe { *glyph = glyph_id.to_u32() as hb_codepoint_t }; - true as hb_bool_t - } - None => false as hb_bool_t, - }, - _ => false as hb_bool_t, + None => false as hb_bool_t, } } @@ -304,15 +339,18 @@ extern "C" fn _hb_fontations_get_glyph_h_advances( let data = unsafe { &mut *(font_data as *mut FontationsData) }; data.check_for_updates(); - let glyph_metrics = &data.glyph_metrics.as_ref().unwrap(); - - for i in 0..count { - let glyph = struct_at_offset(first_glyph, i, glyph_stride); - let glyph_id = GlyphId::new(glyph); - let advance = glyph_metrics.advance_width(glyph_id).unwrap_or_default(); - let scaled = (advance * data.x_mult).round() as hb_position_t; - *struct_at_offset_mut(first_advance, i, advance_stride) = scaled; - } + let glyphs = (0..count).map(|i| { + let glyph = GlyphId::new(struct_at_offset(first_glyph, i, glyph_stride)); + ( + glyph, + struct_at_offset_mut(first_advance, i, advance_stride), + ) + }); + data.instance.glyph_metrics().h_advance_batched( + // Skrifa rounded advances to design units before applying our scale. + |advance| (advance.to_i32() as f32 * data.x_mult).round() as hb_position_t, + glyphs, + ); } extern "C" fn _hb_fontations_get_glyph_v_advances( @@ -328,42 +366,17 @@ extern "C" fn _hb_fontations_get_glyph_v_advances( let data = unsafe { &mut *(font_data as *mut FontationsData) }; data.check_for_updates(); - if let Some(vert_metrics) = &data.vert_metrics { - let vert_vars = &data.vert_vars; - for i in 0..count { - let glyph = struct_at_offset(first_glyph, i, glyph_stride); - let glyph_id = GlyphId::new(glyph); - let mut advance = vert_metrics.advance(glyph_id).unwrap_or_default() as f32; - if let Some(vert_vars) = vert_vars { - let coords = data.location.coords(); - if !coords.is_empty() { - advance += vert_vars - .advance_delta(glyph_id, coords) - .unwrap_or_default() - .to_f32(); - } - } - let scaled = ((advance * data.y_mult).round() as hb_position_t).saturating_neg(); - *struct_at_offset_mut(first_advance, i, advance_stride) = scaled; - } - } else { - let mut font_extents = unsafe { std::mem::zeroed() }; - unsafe { - hb_font_get_extents_for_direction( - font, - hb_direction_t_HB_DIRECTION_LTR, - &mut font_extents, - ); - } - let advance = font_extents - .ascender - .saturating_sub(font_extents.descender) - .saturating_neg(); - - for i in 0..count { - *struct_at_offset_mut(first_advance, i, advance_stride) = advance; - } - } + let line = font_line_extents(font); + let glyphs = (0..count).map(|i| { + let glyph = GlyphId::new(struct_at_offset(first_glyph, i, glyph_stride)); + ( + glyph, + struct_at_offset_mut(first_advance, i, advance_stride), + ) + }); + data.glyph_metrics() + .with_line_extents(Some(line)) + .v_advance_batched(|advance| hb_position(advance).saturating_neg(), glyphs); } extern "C" fn _hb_fontations_get_glyph_v_origin( @@ -381,76 +394,25 @@ extern "C" fn _hb_fontations_get_glyph_v_origin( *x = hb_font_get_glyph_h_advance(font, glyph) / 2; } - let vert_origin = &data.vert_origin; - if let Some(vert_origin) = vert_origin { - let glyph_id = GlyphId::new(glyph); - - let mut y_origin = vert_origin.vertical_origin_y(glyph_id) as f32; - let vert_vars = &data.vert_vars; - if let Some(vert_vars) = vert_vars { - let coords = data.location.coords(); - if !coords.is_empty() { - y_origin += vert_vars - .v_origin_y_delta(glyph_id, coords) - .unwrap_or_default() - .to_f32(); - } + let line = font_line_extents(font); + let extents = |glyph: GlyphId| { + let mut extents: hb_glyph_extents_t = unsafe { std::mem::zeroed() }; + if unsafe { hb_font_get_glyph_extents(font, glyph.to_u32(), &mut extents) } == 0 { + return None; } - - unsafe { - *y = (y_origin * data.y_mult).round() as hb_position_t; - } - - return true as hb_bool_t; - } - - let mut extents: hb_glyph_extents_t = unsafe { std::mem::zeroed() }; - if unsafe { hb_font_get_glyph_extents(font, glyph, &mut extents) != 0 } { - if let Some(vert_metrics) = &data.vert_metrics { - let glyph = GlyphId::new(glyph); - let mut tsb: f32 = vert_metrics.side_bearing(glyph).unwrap_or_default() as f32; - if let Some(vert_vars) = &data.vert_vars { - let coords = data.location.coords(); - if !coords.is_empty() { - tsb += vert_vars - .tsb_delta(glyph, coords) - .unwrap_or_default() - .to_f32(); - } - } - unsafe { - *y = extents - .y_bearing - .saturating_add((tsb * data.y_mult).round() as hb_position_t); - } - return true as hb_bool_t; - } - - let mut font_extents: hb_font_extents_t = unsafe { std::mem::zeroed() }; - unsafe { - hb_font_get_extents_for_direction( - font, - hb_direction_t_HB_DIRECTION_LTR, - &mut font_extents, - ); - } - let advance = font_extents.ascender as i64 - font_extents.descender as i64; - let diff = advance + extents.height as i64; - unsafe { - *y = (extents.y_bearing as i64 + (diff >> 1)) - .clamp(hb_position_t::MIN as i64, hb_position_t::MAX as i64) - as hb_position_t; - } - return true as hb_bool_t; - } - - let mut font_extents: hb_font_extents_t = unsafe { std::mem::zeroed() }; - unsafe { - hb_font_get_extents_for_direction(font, hb_direction_t_HB_DIRECTION_LTR, &mut font_extents); - } - unsafe { - *y = font_extents.ascender; - } + Some(GlyphExtents { + x_bearing: extents.x_bearing as i64, + y_bearing: extents.y_bearing as i64, + width: extents.width as i64, + height: -(extents.height as i64), + }) + }; + let y_origin = data + .glyph_metrics() + .with_line_extents(Some(line)) + .with_glyph_extents(Some(&extents)) + .v_origin_y(GlyphId::new(glyph)); + unsafe { *y = hb_position(y_origin) }; true as hb_bool_t } @@ -487,16 +449,25 @@ extern "C" fn _hb_fontations_get_glyph_extents( let color_glyphs = &data.color_glyphs; let glyph_extents = if let Some(color_glyph) = color_glyphs.get(glyph_id) { - let Some(glyph_extents) = color_glyph.bounding_box(&data.location, data.size) else { + let Some(glyph_extents) = + color_glyph.bounding_box(data.instance.normalized_coords(), data.size) + else { return false as hb_bool_t; }; glyph_extents } else { - let glyph_metrics = &data.glyph_metrics.as_ref().unwrap(); - let Some(glyph_extents) = glyph_metrics.bounds(glyph_id) else { + let Some(glyph_extents) = data.glyph_metrics().extents(glyph_id) else { return false as hb_bool_t; }; - glyph_extents + unsafe { + *extents = hb_glyph_extents_t { + x_bearing: hb_position(glyph_extents.x_bearing), + y_bearing: hb_position(glyph_extents.y_bearing), + width: hb_position(glyph_extents.width), + height: hb_position(-glyph_extents.height), + }; + } + return true as hb_bool_t; }; let x_bearing = (glyph_extents.x_min * data.x_mult).round() as hb_position_t; @@ -527,15 +498,17 @@ extern "C" fn _hb_fontations_get_font_h_extents( let data = unsafe { &mut *(font_data as *mut FontationsData) }; data.check_for_updates(); - let font_ref = &data.font_ref; - let size = &data.size; - let location = &data.location; - let metrics = font_ref.metrics(*size, location); + let line = data + .instance + .metrics() + .scaled(data.scale()) + .h_line() + .unwrap_or_default(); unsafe { - (*extents).ascender = (metrics.ascent * data.y_mult).round() as hb_position_t; - (*extents).descender = (metrics.descent * data.y_mult).round() as hb_position_t; - (*extents).line_gap = (metrics.leading * data.y_mult).round() as hb_position_t; + (*extents).ascender = hb_position(line.ascender); + (*extents).descender = hb_position(line.descender); + (*extents).line_gap = hb_position(line.line_gap); } true as hb_bool_t @@ -622,7 +595,7 @@ extern "C" fn _hb_fontations_draw_glyph_or_fail( data.check_for_updates(); let size = &data.size; - let location = &data.location; + let location = data.instance.normalized_coords(); let outline_glyphs = &data.outline_glyphs; let glyph_id = GlyphId::new(glyph); @@ -1060,7 +1033,7 @@ fn paint_bitmap_glyph( let Ok(image_length) = image.len().try_into() else { return false as hb_bool_t; }; - let face_blob = unsafe { hb_blob_reference(data.face_blob) }; + let face_blob = unsafe { hb_blob_reference(data.face_blob.0) }; let blob = unsafe { hb_blob_create_or_fail( image.as_ptr().cast(), @@ -1104,8 +1077,7 @@ extern "C" fn _hb_fontations_paint_glyph_or_fail( let data = unsafe { &mut *(font_data as *mut FontationsData) }; data.check_for_updates(); - let font_ref = &data.font_ref; - let location = &data.location; + let location = data.instance.normalized_coords(); let color_glyphs = &data.color_glyphs; let glyph_id = GlyphId::new(glyph); @@ -1113,7 +1085,7 @@ extern "C" fn _hb_fontations_paint_glyph_or_fail( return paint_bitmap_glyph(font, data, glyph_id, paint_funcs, paint_data); }; - let cpal = font_ref.cpal(); + let cpal = data.instance.tables().cpal(); let color_records = if let Ok(cpal) = cpal { let num_entries = cpal.num_palette_entries().into(); let color_records = cpal.color_records_array(); @@ -1177,7 +1149,7 @@ extern "C" fn _hb_fontations_glyph_name( ) -> hb_bool_t { let data = unsafe { &mut *(font_data as *mut FontationsData) }; - if let Some(glyph_name) = data.glyph_names.get(GlyphId::new(glyph)) { + if let Some(glyph_name) = data.instance.glyph_name(GlyphId::new(glyph)) { if size == 0 { return true as hb_bool_t; } @@ -1232,7 +1204,7 @@ extern "C" fn _hb_fontations_glyph_from_name( // Build the HashMap from glyph names to IDs let mut map = HashMap::new(); - for (glyph_id, glyph_name) in data.glyph_names.iter() { + for (glyph_id, glyph_name) in data.instance.glyph_names() { map.insert(glyph_name.to_string(), glyph_id.to_u32()); } diff --git a/src/rust/lib.rs b/src/rust/lib.rs index 71df5a50c..6c7a93735 100644 --- a/src/rust/lib.rs +++ b/src/rust/lib.rs @@ -7,6 +7,36 @@ mod font; #[cfg(feature = "shape")] mod shape; +#[cfg(any(feature = "font", feature = "shape"))] +struct HbBlob(*mut hb_blob_t); + +#[cfg(any(feature = "font", feature = "shape"))] +impl Drop for HbBlob { + fn drop(&mut self) { + unsafe { + hb_blob_destroy(self.0); + } + } +} + +#[cfg(any(feature = "font", feature = "shape"))] +impl AsRef<[u8]> for HbBlob { + fn as_ref(&self) -> &[u8] { + let mut length = 0; + let data = unsafe { hb_blob_get_data(self.0, &mut length) }; + if data.is_null() { + &[] + } else { + unsafe { std::slice::from_raw_parts(data.cast(), length as usize) } + } + } +} + +#[cfg(any(feature = "font", feature = "shape"))] +unsafe impl Send for HbBlob {} +#[cfg(any(feature = "font", feature = "shape"))] +unsafe impl Sync for HbBlob {} + #[cfg(feature = "hb-allocator")] use std::alloc::{GlobalAlloc, Layout}; #[cfg(feature = "hb-allocator")] diff --git a/src/rust/shape.rs b/src/rust/shape.rs index f31594377..ad8f05e86 100644 --- a/src/rust/shape.rs +++ b/src/rust/shape.rs @@ -2,7 +2,7 @@ // C enum becomes i32 on some systems (eg. Windows). #![allow(clippy::unnecessary_cast)] -use super::hb::*; +use super::{hb::*, HbBlob}; use std::ffi::c_void; use std::mem::{align_of, offset_of, size_of}; @@ -70,31 +70,6 @@ impl HbFace { unsafe impl Send for HbFace {} unsafe impl Sync for HbFace {} -struct HbBlob(*mut hb_blob_t); - -impl Drop for HbBlob { - fn drop(&mut self) { - unsafe { - hb_blob_destroy(self.0); - } - } -} - -impl AsRef<[u8]> for HbBlob { - fn as_ref(&self) -> &[u8] { - let mut length = 0; - let data = unsafe { hb_blob_get_data(self.0, &mut length) }; - if data.is_null() { - &[] - } else { - unsafe { std::slice::from_raw_parts(data.cast(), length as usize) } - } - } -} - -unsafe impl Send for HbBlob {} -unsafe impl Sync for HbBlob {} - #[unsafe(no_mangle)] pub unsafe extern "C" fn _hb_harfrust_shaper_face_data_create_rs( face: *mut hb_face_t, diff --git a/test/api/test-font.c b/test/api/test-font.c index e8087574e..2a8b291a9 100644 --- a/test/api/test-font.c +++ b/test/api/test-font.c @@ -26,6 +26,10 @@ #include "hb-test.h" +#ifdef HAVE_FONTATIONS +#include +#endif + /* Unit tests for hb-font.h */ @@ -712,6 +716,78 @@ test_synthetic_glyph_extents_overflow (void) hb_font_funcs_destroy (ffuncs); } +#ifdef HAVE_FONTATIONS +static void +test_fontations_advances (void) +{ + const char *fonts[] = { + "fonts/Roboto-Variable.abc.ttf", + "fonts/SourceSerifVariable-Roman-VVAR.abc.ttf", + "fonts/SourceSansVariable-Roman-nohvar-41,C1.ttf", + }; + const int coords[] = {0, 16384, -16384, 0}; + const struct { + hb_codepoint_t glyph; + hb_codepoint_t padding[2]; + } glyphs[] = {{1, {0}}, {2, {0}}, {3, {0}}, {HB_CODEPOINT_INVALID, {0}}}; + + for (unsigned f = 0; f < G_N_ELEMENTS (fonts); f++) + { + hb_face_t *face = hb_test_open_font_file (fonts[f]); + hb_font_t *font = hb_font_create (face); + hb_font_t *reference = hb_font_create (face); + int upem = hb_face_get_upem (face); + hb_fontations_font_set_funcs (font); + + for (int sign = 1; sign >= -1; sign -= 2) + { + hb_font_set_scale (font, sign * upem * 2, sign * upem * 3); + hb_font_set_scale (reference, sign * upem * 2, sign * upem * 3); + + for (unsigned c = 0; c < G_N_ELEMENTS (coords); c++) + { + hb_font_set_var_coords_normalized (font, &coords[c], 1); + hb_font_set_var_coords_normalized (reference, &coords[c], 1); + + hb_position_t h_advances[2 * G_N_ELEMENTS (glyphs)]; + hb_position_t v_advances[2 * G_N_ELEMENTS (glyphs)]; + for (unsigned i = 0; i < G_N_ELEMENTS (h_advances); i++) + h_advances[i] = v_advances[i] = 123456; + + hb_font_get_glyph_h_advances (font, G_N_ELEMENTS (glyphs), + &glyphs[0].glyph, sizeof (glyphs[0]), + h_advances, 2 * sizeof (h_advances[0])); + hb_font_get_glyph_v_advances (font, G_N_ELEMENTS (glyphs), + &glyphs[0].glyph, sizeof (glyphs[0]), + v_advances, 2 * sizeof (v_advances[0])); + + for (unsigned i = 0; i < G_N_ELEMENTS (glyphs); i++) + { + hb_codepoint_t glyph = glyphs[i].glyph; + g_assert_cmpint (h_advances[2 * i], ==, hb_font_get_glyph_h_advance (font, glyph)); + g_assert_cmpint (v_advances[2 * i], ==, hb_font_get_glyph_v_advance (font, glyph)); + /* OT can apply variation deltas even to invalid glyph IDs. */ + if (glyph < hb_face_get_glyph_count (face)) + { + g_assert_cmpint (h_advances[2 * i], ==, hb_font_get_glyph_h_advance (reference, glyph)); + g_assert_cmpint (v_advances[2 * i], ==, hb_font_get_glyph_v_advance (reference, glyph)); + } + g_assert_cmpint (h_advances[2 * i + 1], ==, 123456); + g_assert_cmpint (v_advances[2 * i + 1], ==, 123456); + } + + hb_font_get_glyph_h_advances (font, 0, NULL, 0, NULL, 0); + hb_font_get_glyph_v_advances (font, 0, NULL, 0, NULL, 0); + } + } + + hb_font_destroy (reference); + hb_font_destroy (font); + hb_face_destroy (face); + } +} +#endif + int main (int argc, char **argv) { @@ -730,6 +806,9 @@ main (int argc, char **argv) hb_test_add (test_font_empty); hb_test_add (test_font_properties); hb_test_add (test_synthetic_glyph_extents_overflow); +#ifdef HAVE_FONTATIONS + hb_test_add (test_fontations_advances); +#endif return hb_test_run(); } diff --git a/test/shape/data/in-house/tests/vertical.tests b/test/shape/data/in-house/tests/vertical.tests index 7dd50d503..cf57f17ed 100644 --- a/test/shape/data/in-house/tests/vertical.tests +++ b/test/shape/data/in-house/tests/vertical.tests @@ -7,8 +7,7 @@ @font-funcs=ot,ft,fontations ../fonts/NotoSansCJK-VF.abc.ttf;--direction=t;U+0041,U+0042;[gid1=0@-287,-880+0,-1000|gid2=1@-316,-880+0,-1000] ../fonts/NotoSerifHK-subset.ttf;--direction=t;U+0041,U+0042;[gid1=0@-353,-880+0,-1000|gid2=1@-327,-880+0,-1000] -# glyf+gvar+vmtx; TODO: fontations needs more work https://github.com/harfbuzz/harfbuzz/issues/5388 -@font-funcs=ot,ft +# glyf+gvar+vmtx ../fonts/NotoSansCJK-VF.abc.ttf;--direction=t --variations wght=700;U+0041,U+0042;[gid1=0@-320,-880+0,-1000|gid2=1@-340,-880+0,-1000] ../fonts/NotoSerifHK-subset.ttf;--direction=t --variations wght=700;U+0041,U+0042;[gid1=0@-373,-880+0,-1000|gid2=1@-354,-880+0,-1000] @font-funcs=ot,ft,fontations From a1d87bc72c5de93ccc9e3e917bf7f4ed79eb7336 Mon Sep 17 00:00:00 2001 From: Behdad Esfahbod Date: Sat, 3 Oct 2026 17:37:01 -0600 Subject: [PATCH 03/15] [rust] Make Skrifa optional for font functions Core font functions now use read-fonts, but the font feature still requires Skrifa for bitmap and COLR extents. Add explicit read-fonts and skrifa features. Make font require only read-fonts, and make draw and paint enable Skrifa. Keep the skrifa feature usable alone for bitmap and COLR extents without rendering. Gate Skrifa state and callbacks accordingly, and make smallvec optional under shape. Custom builders can omit Skrifa with --no-default-features and --features font. Default rendering support is preserved. Tests: meson test -C build (281 passed, 1 skipped); Clippy with warnings denied for nine Cargo feature configurations. Cargo dependency trees confirm no Skrifa for font, shape, or both with defaults disabled. Assisted-by: OpenAI Codex --- src/rust/Cargo.toml | 16 ++-- src/rust/font.rs | 193 ++++++++++++++++++++++++-------------------- 2 files changed, 116 insertions(+), 93 deletions(-) diff --git a/src/rust/Cargo.toml b/src/rust/Cargo.toml index a01965483..6f4861d90 100644 --- a/src/rust/Cargo.toml +++ b/src/rust/Cargo.toml @@ -6,9 +6,9 @@ rust-version = "1.87.0" [dependencies] # harfrust = { version = "0.13.3", optional = true } harfrust = { git = "https://github.com/harfbuzz/harfrust", optional = true } -read-fonts = "0.45.*" +read-fonts = { version = "0.45.*", optional = true } skrifa = { version = "0.48.*", optional = true } -smallvec = "1.*" +smallvec = { version = "1.*", optional = true } [lib] name = "harfbuzz_rust" @@ -17,10 +17,14 @@ crate-type = ["staticlib"] [features] default = ["paint", "draw", "hb-allocator"] -font = ["dep:skrifa"] -shape = ["dep:harfrust"] -paint = [] -draw = [] +# Core font functions require only read-fonts. +font = ["read-fonts"] +shape = ["dep:harfrust", "dep:smallvec"] +read-fonts = ["dep:read-fonts"] +# Skrifa also provides bitmap and COLR extents without drawing or painting. +skrifa = ["read-fonts", "dep:skrifa"] +paint = ["skrifa"] +draw = ["skrifa"] hb-allocator = [] [profile.release] diff --git a/src/rust/font.rs b/src/rust/font.rs index b01e29af8..12e40e917 100644 --- a/src/rust/font.rs +++ b/src/rust/font.rs @@ -11,12 +11,19 @@ use read_fonts::model::{ Blob, Font, NormalizedCoord, }; use read_fonts::types::{BoundingBox as FontBounds, F48Dot16, GlyphId}; + +#[cfg(feature = "skrifa")] use read_fonts::FontRef; +#[cfg(feature = "skrifa")] use skrifa::bitmap::{BitmapFormat, BitmapGlyph, BitmapStrikes, Origin}; +#[cfg(feature = "skrifa")] use skrifa::color::ColorGlyphCollection; +#[cfg(feature = "skrifa")] use skrifa::instance::Size; +#[cfg(feature = "skrifa")] use skrifa::MetadataProvider; +#[cfg(feature = "draw")] use skrifa::OutlineGlyphCollection; #[cfg(feature = "draw")] @@ -35,14 +42,12 @@ use skrifa::{ // A struct for storing your “fontations” data #[repr(C)] -struct FontationsData<'a> { +struct FontationsData { + #[cfg(feature = "paint")] face_blob: Arc, font: *mut hb_font_t, - outline_glyphs: OutlineGlyphCollection<'a>, - color_glyphs: ColorGlyphCollection<'a>, - cbdt_strikes: Option>, - sbix_strikes: Option>, - size: Size, + #[cfg(feature = "skrifa")] + skrifa: SkrifaData<'static>, // Mutex for the below mutex: Mutex<()>, @@ -52,42 +57,49 @@ struct FontationsData<'a> { instance: Font, } -impl FontationsData<'_> { +#[cfg(feature = "skrifa")] +struct SkrifaData<'a> { + #[cfg(feature = "draw")] + outline_glyphs: OutlineGlyphCollection<'a>, + color_glyphs: ColorGlyphCollection<'a>, + cbdt_strikes: Option>, + sbix_strikes: Option>, + size: Size, +} + +impl FontationsData { unsafe fn from_hb_font(font: *mut hb_font_t) -> Option { let face_index = hb_face_get_index(hb_font_get_face(font)); let face_blob = Arc::new(HbBlob(hb_face_reference_blob(hb_font_get_face(font)))); - let blob_length = hb_blob_get_length(face_blob.0); - let blob_data: *const u8 = hb_blob_get_data(face_blob.0, null_mut()).cast(); - if blob_data.is_null() { - return None; - } - let face_data = std::slice::from_raw_parts(blob_data, blob_length as usize); - - let font_ref = FontRef::from_index(face_data, face_index); - let font_ref = match font_ref { - Ok(f) => f, - Err(_) => return None, - }; - let instance = Font::new(Blob::Shared(face_blob.clone()), face_index)?; - let outline_glyphs = font_ref.outline_glyphs(); + #[cfg(feature = "skrifa")] + let skrifa = { + let blob_length = hb_blob_get_length(face_blob.0); + let blob_data: *const u8 = hb_blob_get_data(face_blob.0, null_mut()).cast(); + if blob_data.is_null() { + return None; + } + // The instance owns the blob for the lifetime of these collections. + let face_data = std::slice::from_raw_parts(blob_data, blob_length as usize); + let font_ref = FontRef::from_index(face_data, face_index).ok()?; - let color_glyphs = font_ref.color_glyphs(); - - let cbdt_strikes = BitmapStrikes::with_format(&font_ref, BitmapFormat::Cbdt); - let sbix_strikes = BitmapStrikes::with_format(&font_ref, BitmapFormat::Sbix); - - let upem = hb_face_get_upem(hb_font_get_face(font)); + SkrifaData { + #[cfg(feature = "draw")] + outline_glyphs: font_ref.outline_glyphs(), + color_glyphs: font_ref.color_glyphs(), + cbdt_strikes: BitmapStrikes::with_format(&font_ref, BitmapFormat::Cbdt), + sbix_strikes: BitmapStrikes::with_format(&font_ref, BitmapFormat::Sbix), + size: Size::new(hb_face_get_upem(hb_font_get_face(font)) as f32), + } + }; let mut data = FontationsData { + #[cfg(feature = "paint")] face_blob, font, - outline_glyphs, - color_glyphs, - cbdt_strikes, - sbix_strikes, - size: Size::new(upem as f32), + #[cfg(feature = "skrifa")] + skrifa, mutex: Mutex::new(()), x_mult: 1.0, y_mult: 1.0, @@ -225,6 +237,7 @@ fn struct_at_offset_mut(first: *mut T, index: u32, stride: u32) -> &'st unsafe { &mut *((first as *mut u8).offset((index * stride) as isize) as *mut T) } } +#[cfg(feature = "skrifa")] fn bitmap_size(font: *mut hb_font_t) -> Size { let mut x_ppem = 0; let mut y_ppem = 0; @@ -237,6 +250,7 @@ fn bitmap_size(font: *mut hb_font_t) -> Size { } } +#[cfg(feature = "skrifa")] fn bitmap_glyph_extents( data: &FontationsData, bitmap_glyph: &BitmapGlyph, @@ -251,7 +265,7 @@ fn bitmap_glyph_extents( return None; } - let upem = data.size.ppem()?; + let upem = data.skrifa.size.ppem()?; let x_scale = upem / bitmap_glyph.ppem_x; let y_scale = upem / bitmap_glyph.ppem_y; @@ -418,7 +432,7 @@ extern "C" fn _hb_fontations_get_glyph_v_origin( } extern "C" fn _hb_fontations_get_glyph_extents( - font: *mut hb_font_t, + _font: *mut hb_font_t, font_data: *mut ::std::os::raw::c_void, glyph: hb_codepoint_t, extents: *mut hb_glyph_extents_t, @@ -429,60 +443,63 @@ extern "C" fn _hb_fontations_get_glyph_extents( let glyph_id = GlyphId::new(glyph); - let size = bitmap_size(font); - let bitmap_glyph = data - .sbix_strikes - .as_ref() - .and_then(|strikes| strikes.glyph_for_size(size, glyph_id)) - .or_else(|| { - data.cbdt_strikes - .as_ref() - .and_then(|strikes| strikes.glyph_for_size(size, glyph_id)) - }); - if let Some(bitmap_glyph) = bitmap_glyph { - let Some(bitmap_extents) = bitmap_glyph_extents(data, &bitmap_glyph) else { - return false as hb_bool_t; - }; - unsafe { *extents = bitmap_extents }; - return true as hb_bool_t; + #[cfg(feature = "skrifa")] + { + let skrifa = &data.skrifa; + let size = bitmap_size(_font); + let bitmap_glyph = skrifa + .sbix_strikes + .as_ref() + .and_then(|strikes| strikes.glyph_for_size(size, glyph_id)) + .or_else(|| { + skrifa + .cbdt_strikes + .as_ref() + .and_then(|strikes| strikes.glyph_for_size(size, glyph_id)) + }); + if let Some(bitmap_glyph) = bitmap_glyph { + let Some(bitmap_extents) = bitmap_glyph_extents(data, &bitmap_glyph) else { + return false as hb_bool_t; + }; + unsafe { *extents = bitmap_extents }; + return true as hb_bool_t; + } + + if let Some(color_glyph) = skrifa.color_glyphs.get(glyph_id) { + let Some(glyph_extents) = + color_glyph.bounding_box(data.instance.normalized_coords(), skrifa.size) + else { + return false as hb_bool_t; + }; + + let x_bearing = (glyph_extents.x_min * data.x_mult).round() as hb_position_t; + let width = ((glyph_extents.x_max * data.x_mult).round() as hb_position_t) + .saturating_sub(x_bearing); + let y_bearing = (glyph_extents.y_max * data.y_mult).round() as hb_position_t; + let height = ((glyph_extents.y_min * data.y_mult).round() as hb_position_t) + .saturating_sub(y_bearing); + + unsafe { + *extents = hb_glyph_extents_t { + x_bearing, + y_bearing, + width, + height, + }; + } + return true as hb_bool_t; + } } - let color_glyphs = &data.color_glyphs; - let glyph_extents = if let Some(color_glyph) = color_glyphs.get(glyph_id) { - let Some(glyph_extents) = - color_glyph.bounding_box(data.instance.normalized_coords(), data.size) - else { - return false as hb_bool_t; - }; - glyph_extents - } else { - let Some(glyph_extents) = data.glyph_metrics().extents(glyph_id) else { - return false as hb_bool_t; - }; - unsafe { - *extents = hb_glyph_extents_t { - x_bearing: hb_position(glyph_extents.x_bearing), - y_bearing: hb_position(glyph_extents.y_bearing), - width: hb_position(glyph_extents.width), - height: hb_position(-glyph_extents.height), - }; - } - return true as hb_bool_t; + let Some(glyph_extents) = data.glyph_metrics().extents(glyph_id) else { + return false as hb_bool_t; }; - - let x_bearing = (glyph_extents.x_min * data.x_mult).round() as hb_position_t; - let width = - ((glyph_extents.x_max * data.x_mult).round() as hb_position_t).saturating_sub(x_bearing); - let y_bearing = (glyph_extents.y_max * data.y_mult).round() as hb_position_t; - let height = - ((glyph_extents.y_min * data.y_mult).round() as hb_position_t).saturating_sub(y_bearing); - unsafe { *extents = hb_glyph_extents_t { - x_bearing, - y_bearing, - width, - height, + x_bearing: hb_position(glyph_extents.x_bearing), + y_bearing: hb_position(glyph_extents.y_bearing), + width: hb_position(glyph_extents.width), + height: hb_position(-glyph_extents.height), }; } @@ -594,9 +611,9 @@ extern "C" fn _hb_fontations_draw_glyph_or_fail( let data = unsafe { &mut *(font_data as *mut FontationsData) }; data.check_for_updates(); - let size = &data.size; + let size = &data.skrifa.size; let location = data.instance.normalized_coords(); - let outline_glyphs = &data.outline_glyphs; + let outline_glyphs = &data.skrifa.outline_glyphs; let glyph_id = GlyphId::new(glyph); let Some(outline_glyph) = outline_glyphs.get(glyph_id) else { @@ -1007,11 +1024,13 @@ fn paint_bitmap_glyph( ) -> hb_bool_t { let size = bitmap_size(font); let bitmap_glyph = data + .skrifa .cbdt_strikes .as_ref() .and_then(|strikes| strikes.glyph_for_size(size, glyph_id)) .or_else(|| { - data.sbix_strikes + data.skrifa + .sbix_strikes .as_ref() .and_then(|strikes| strikes.glyph_for_size(size, glyph_id)) }); @@ -1078,7 +1097,7 @@ extern "C" fn _hb_fontations_paint_glyph_or_fail( data.check_for_updates(); let location = data.instance.normalized_coords(); - let color_glyphs = &data.color_glyphs; + let color_glyphs = &data.skrifa.color_glyphs; let glyph_id = GlyphId::new(glyph); let Some(color_glyph) = color_glyphs.get(glyph_id) else { From f902205a0ca0c604dee03b7d924d7f92bbf639ae Mon Sep 17 00:00:00 2001 From: Behdad Esfahbod Date: Sat, 3 Oct 2026 18:58:43 -0600 Subject: [PATCH 04/15] [rust] Publish the glyph-name cache without replacement Concurrent readers could replace and destroy a face's reverse-name map while another reader was using it. Publish with replace=false, reclaim losing maps, and retrieve the winner. Return failure if publication fails without a winner instead of retrying indefinitely on allocation failure. Add a concurrent initialization regression that fails before the fix. Tests: full Meson suite (281 passed, 1 skipped). Clippy used opt-level=0 to avoid a nightly compiler timeout; library compilation remained opt=3. Assisted-by: OpenAI Codex --- src/rust/font.rs | 29 ++++++++++---------- test/api/test-font.c | 64 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 79 insertions(+), 14 deletions(-) diff --git a/src/rust/font.rs b/src/rust/font.rs index 12e40e917..f5bc1fd31 100644 --- a/src/rust/font.rs +++ b/src/rust/font.rs @@ -1212,15 +1212,10 @@ extern "C" fn _hb_fontations_glyph_from_name( }; let face = unsafe { hb_font_get_face(font) }; - let mut user_data_ptr: *mut c_void; - - loop { - user_data_ptr = - unsafe { hb_face_get_user_data(face, std::ptr::addr_of_mut!(GLYPH_FROM_NAMES_KEY)) }; - if !user_data_ptr.is_null() { - break; - } + let mut user_data_ptr = + unsafe { hb_face_get_user_data(face, std::ptr::addr_of_mut!(GLYPH_FROM_NAMES_KEY)) }; + if user_data_ptr.is_null() { // Build the HashMap from glyph names to IDs let mut map = HashMap::new(); for (glyph_id, glyph_name) in data.instance.glyph_names() { @@ -1236,18 +1231,24 @@ extern "C" fn _hb_fontations_glyph_from_name( std::ptr::addr_of_mut!(GLYPH_FROM_NAMES_KEY), ptr, Some(_hb_glyph_from_names_destroy), - true as hb_bool_t, + false as hb_bool_t, ) }; if success != false as hb_bool_t { user_data_ptr = ptr; - break; + } else { + // Another reader may have published first. Never replace its map: + // readers keep using it until the face is destroyed. + _hb_glyph_from_names_destroy(ptr); + user_data_ptr = unsafe { + hb_face_get_user_data(face, std::ptr::addr_of_mut!(GLYPH_FROM_NAMES_KEY)) + }; + if user_data_ptr.is_null() { + // Publication failed without a winner (for example, on OOM). + return false as hb_bool_t; + } } - - // We failed to set user data — reclaim the pointer to avoid leaking - _hb_glyph_from_names_destroy(ptr); - // Try again in next loop iteration } let glyph_from_names = unsafe { &*(user_data_ptr as *const HashMap) }; diff --git a/test/api/test-font.c b/test/api/test-font.c index 2a8b291a9..c33cd3d9d 100644 --- a/test/api/test-font.c +++ b/test/api/test-font.c @@ -717,6 +717,69 @@ test_synthetic_glyph_extents_overflow (void) } #ifdef HAVE_FONTATIONS +typedef struct { + hb_font_t *font; + GMutex mutex; + GCond cond; + unsigned waiting; + hb_bool_t start; + char name[128]; +} fontations_name_test_t; + +static gpointer +fontations_name_thread (gpointer user_data) +{ + fontations_name_test_t *data = user_data; + g_mutex_lock (&data->mutex); + data->waiting++; + g_cond_broadcast (&data->cond); + while (!data->start) + g_cond_wait (&data->cond, &data->mutex); + g_mutex_unlock (&data->mutex); + + for (unsigned i = 0; i < 100; i++) + { + hb_codepoint_t glyph = HB_CODEPOINT_INVALID; + g_assert_true (hb_font_get_glyph_from_name (data->font, data->name, -1, &glyph)); + g_assert_cmpuint (glyph, ==, 1); + g_assert_false (hb_font_get_glyph_from_name (data->font, "nonexistent-glyph", -1, &glyph)); + } + return NULL; +} + +static void +test_fontations_glyph_from_name_threads (void) +{ + for (unsigned run = 0; run < 8; run++) + { + hb_face_t *face = hb_test_open_font_file ("fonts/NotoSans-Bold.ttf"); + fontations_name_test_t data = {0}; + data.font = hb_font_create (face); + hb_fontations_font_set_funcs (data.font); + hb_font_make_immutable (data.font); + g_assert_true (hb_font_get_glyph_name (data.font, 1, data.name, sizeof (data.name))); + g_mutex_init (&data.mutex); + g_cond_init (&data.cond); + + GThread *threads[8]; + for (unsigned i = 0; i < G_N_ELEMENTS (threads); i++) + threads[i] = g_thread_new ("fontations-names", fontations_name_thread, &data); + g_mutex_lock (&data.mutex); + while (data.waiting != G_N_ELEMENTS (threads)) + g_cond_wait (&data.cond, &data.mutex); + data.start = true; + g_cond_broadcast (&data.cond); + g_mutex_unlock (&data.mutex); + for (unsigned i = 0; i < G_N_ELEMENTS (threads); i++) + g_thread_join (threads[i]); + + g_cond_clear (&data.cond); + g_mutex_clear (&data.mutex); + hb_font_destroy (data.font); + hb_face_destroy (face); + } +} + static void test_fontations_advances (void) { @@ -807,6 +870,7 @@ main (int argc, char **argv) hb_test_add (test_font_properties); hb_test_add (test_synthetic_glyph_extents_overflow); #ifdef HAVE_FONTATIONS + hb_test_add (test_fontations_glyph_from_name_threads); hb_test_add (test_fontations_advances); #endif From c825beb7c5234accf5905a98857646acf1c0d9e7 Mon Sep 17 00:00:00 2001 From: Behdad Esfahbod Date: Sat, 3 Oct 2026 18:59:51 -0600 Subject: [PATCH 05/15] [rust] Disable unused Skrifa autohint shaping support Request Skrifa's std feature explicitly without its default features. The integration uses unhinted drawing and does not use autohint shaping. Keep this confined to Cargo for custom builders. Tests: full Meson suite (281 passed, 1 skipped); nine Cargo feature configurations passed Clippy with warnings denied. Dependency trees confirm font alone omits Skrifa and rendering enables only its std feature. Clippy used opt-level=0 for the nightly compiler workaround. Assisted-by: OpenAI Codex --- src/rust/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/rust/Cargo.toml b/src/rust/Cargo.toml index 6f4861d90..5431a86ba 100644 --- a/src/rust/Cargo.toml +++ b/src/rust/Cargo.toml @@ -7,7 +7,7 @@ rust-version = "1.87.0" # harfrust = { version = "0.13.3", optional = true } harfrust = { git = "https://github.com/harfbuzz/harfrust", optional = true } read-fonts = { version = "0.45.*", optional = true } -skrifa = { version = "0.48.*", optional = true } +skrifa = { version = "0.48.*", optional = true, default-features = false, features = ["std"] } smallvec = { version = "1.*", optional = true } [lib] From 59e454c8995f6bd7d188dfd95f478ed818bff383 Mon Sep 17 00:00:00 2001 From: Behdad Esfahbod Date: Sat, 3 Oct 2026 19:03:23 -0600 Subject: [PATCH 06/15] [rust] Reuse Fontations instances when coordinates are unchanged Font serial changes include scale changes, which need not discard the read-fonts instance's variation and metrics caches. Compare normalized coordinates using the builder's padding, truncation, and default-location rules, and rebuild only when the effective coordinates change. Test scale changes, zero coordinates, omitted axes, extra axes, and resets against fresh Fontations instances. Preserve existing rounding behavior. Tests: full Meson suite (281 passed, 1 skipped); 144 font/scale/location snapshots matched the previous implementation. Clippy used opt-level=0 for the nightly compiler workaround. Assisted-by: OpenAI Codex --- src/rust/font.rs | 29 ++++++++++++++++++------ test/api/test-font.c | 53 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+), 7 deletions(-) diff --git a/src/rust/font.rs b/src/rust/font.rs index f5bc1fd31..5e40c1da2 100644 --- a/src/rust/font.rs +++ b/src/rust/font.rs @@ -11,6 +11,7 @@ use read_fonts::model::{ Blob, Font, NormalizedCoord, }; use read_fonts::types::{BoundingBox as FontBounds, F48Dot16, GlyphId}; +use read_fonts::TableProvider; #[cfg(feature = "skrifa")] use read_fonts::FontRef; @@ -29,9 +30,6 @@ use skrifa::OutlineGlyphCollection; #[cfg(feature = "draw")] use skrifa::outline::{pen::OutlinePen, DrawSettings}; -#[cfg(feature = "paint")] -use read_fonts::TableProvider; - #[cfg(feature = "paint")] use skrifa::{ bitmap::BitmapData, @@ -135,11 +133,28 @@ impl FontationsData { } else { std::slice::from_raw_parts(coords, num_coords as usize) }; - self.instance = self + let current_coords = self.instance.normalized_coords(); + let axis_count = self .instance - .instance_builder() - .normalized_coords(coords.iter().map(|v| NormalizedCoord::from_bits(*v as i16))) - .build(); + .tables() + .fvar() + .map(|fvar| fvar.axis_count() as usize) + .unwrap_or(0); + // Match the builder's padding and truncation, including its empty + // representation of an all-default location. + if (0..axis_count).any(|i| { + current_coords + .get(i) + .copied() + .unwrap_or(NormalizedCoord::ZERO) + != NormalizedCoord::from_bits(coords.get(i).copied().unwrap_or(0) as i16) + }) { + self.instance = self + .instance + .instance_builder() + .normalized_coords(coords.iter().map(|v| NormalizedCoord::from_bits(*v as i16))) + .build(); + } self.serial.store(font_serial, Ordering::Release); } diff --git a/test/api/test-font.c b/test/api/test-font.c index c33cd3d9d..2bd40e15e 100644 --- a/test/api/test-font.c +++ b/test/api/test-font.c @@ -780,6 +780,58 @@ test_fontations_glyph_from_name_threads (void) } } +static void +test_fontations_scale_changes (void) +{ + const char *fonts[] = { + "fonts/Roboto-Variable.abc.ttf", + "fonts/SourceSerifVariable-Roman-VVAR.abc.ttf", + "fonts/Roboto-Regular.abc.ttf", + }; + const struct { + int values[3]; + unsigned count; + } locations[] = { + {{0, 0, 0}, 0}, {{0, 0, 0}, 3}, + {{9830, 0, 0}, 1}, {{9830, 0, 0}, 3}, + {{9830, 16384, 0}, 2}, {{9830, 16384, 16384}, 3}, + {{0, 0, 16384}, 3}, {{0, 0, 0}, 0}, + }; + const int scales[][2] = {{2048, 4096}, {-1234, -5678}, {0, 0}, {1234, 5678}}; + + for (unsigned f = 0; f < G_N_ELEMENTS (fonts); f++) + { + hb_face_t *face = hb_test_open_font_file (fonts[f]); + hb_font_t *font = hb_font_create (face); + hb_font_t *reference = hb_font_create (face); + hb_fontations_font_set_funcs (font); + + for (unsigned c = 0; c < G_N_ELEMENTS (locations); c++) + { + hb_font_set_var_coords_normalized (font, locations[c].values, locations[c].count); + hb_font_set_var_coords_normalized (reference, locations[c].values, locations[c].count); + for (unsigned s = 0; s < G_N_ELEMENTS (scales); s++) + { + hb_font_set_scale (font, scales[s][0], scales[s][1]); + hb_font_set_scale (reference, scales[s][0], scales[s][1]); + /* Compare the reused instance against a freshly initialized one. */ + hb_fontations_font_set_funcs (reference); + for (hb_codepoint_t glyph = 0; glyph < hb_face_get_glyph_count (face); glyph++) + { + g_assert_cmpint (hb_font_get_glyph_h_advance (font, glyph), ==, + hb_font_get_glyph_h_advance (reference, glyph)); + g_assert_cmpint (hb_font_get_glyph_v_advance (font, glyph), ==, + hb_font_get_glyph_v_advance (reference, glyph)); + } + } + } + + hb_font_destroy (reference); + hb_font_destroy (font); + hb_face_destroy (face); + } +} + static void test_fontations_advances (void) { @@ -871,6 +923,7 @@ main (int argc, char **argv) hb_test_add (test_synthetic_glyph_extents_overflow); #ifdef HAVE_FONTATIONS hb_test_add (test_fontations_glyph_from_name_threads); + hb_test_add (test_fontations_scale_changes); hb_test_add (test_fontations_advances); #endif From 71fc895c788dabd661689eea886e6ee077653a64 Mon Sep 17 00:00:00 2001 From: Behdad Esfahbod Date: Sat, 3 Oct 2026 19:11:51 -0600 Subject: [PATCH 07/15] [rust] Scope strided output references to each metrics batch Replace safe pointer helpers that manufactured static mutable references with explicit unsafe reads/writes and a callback-scoped output iterator. Compute byte offsets in pointer width. Preserve direct batch writes for aligned, disjoint buffers; use stack outputs for unaligned, repeated, or overlapping slots without allocating or creating aliased references. Add unaligned nominal/advance, padding, repeated output, and in-place advance coverage. Tests: full Meson suite (281 passed, 1 skipped), font-only Clippy, and unchanged 144-case metric snapshots. Clippy used opt-level=0 for the nightly compiler workaround. Seven-run medians across 36 nominal/horizontal/vertical advance cases, compared again with the saved old library on one CPU, showed no slowdown: nominal about 6% faster, horizontal unchanged, vertical about 36% faster. Assisted-by: OpenAI Codex --- src/rust/font.rs | 166 +++++++++++++++++++++++++++++++++++-------- test/api/test-font.c | 64 +++++++++++++++++ 2 files changed, 202 insertions(+), 28 deletions(-) diff --git a/src/rust/font.rs b/src/rust/font.rs index 5e40c1da2..292055152 100644 --- a/src/rust/font.rs +++ b/src/rust/font.rs @@ -2,6 +2,7 @@ use super::{hb::*, HbBlob}; use std::collections::HashMap; use std::ffi::c_void; +use std::marker::PhantomData; use std::ptr::null_mut; use std::sync::atomic::{AtomicPtr, AtomicU32, Ordering}; use std::sync::{Arc, Mutex}; @@ -244,12 +245,113 @@ fn font_line_extents(font: *mut hb_font_t) -> LineExtents { } } -fn struct_at_offset(first: *const T, index: u32, stride: u32) -> T { - unsafe { *((first as *const u8).offset((index * stride) as isize) as *const T) } +// SAFETY: The selected slot must be readable for a T. Alignment is not required. +unsafe fn struct_at_offset(first: *const T, index: u32, stride: u32) -> T { + first + .cast::() + .add(index as usize * stride as usize) + .cast::() + .read_unaligned() } -fn struct_at_offset_mut(first: *mut T, index: u32, stride: u32) -> &'static mut T { - unsafe { &mut *((first as *mut u8).offset((index * stride) as isize) as *mut T) } +// SAFETY: The selected slot must be writable for a T. Alignment is not required. +unsafe fn write_struct_at_offset(first: *mut T, index: u32, stride: u32, value: T) { + first + .cast::() + .add(index as usize * stride as usize) + .cast::() + .write_unaligned(value); +} + +// Constructed only by with_strided_glyphs: outputs are aligned, disjoint, +// and exclusively borrowed for 'a, and cannot alias the input slots. +struct StridedGlyphs<'a> { + index: u32, + count: u32, + first_glyph: *const hb_codepoint_t, + glyph_stride: u32, + first_value: *mut hb_position_t, + value_stride: u32, + lifetime: PhantomData<&'a mut hb_position_t>, +} + +impl<'a> Iterator for StridedGlyphs<'a> { + type Item = (GlyphId, &'a mut hb_position_t); + + fn next(&mut self) -> Option { + if self.index == self.count { + return None; + } + let i = self.index; + self.index += 1; + unsafe { + Some(( + GlyphId::new(struct_at_offset(self.first_glyph, i, self.glyph_stride)), + &mut *self + .first_value + .cast::() + .add(i as usize * self.value_stride as usize) + .cast::(), + )) + } + } +} + +// SAFETY: All input/output slots must be readable/writable for this call. +// The callback must access these buffers only through the supplied iterator. +unsafe fn with_strided_glyphs( + count: u32, + first_glyph: *const hb_codepoint_t, + glyph_stride: u32, + first_value: *mut hb_position_t, + value_stride: u32, + mut batch: impl for<'a> FnMut(StridedGlyphs<'a>), +) { + if count == 0 { + return; + } + let glyph_end = first_glyph as usize + + (count - 1) as usize * glyph_stride as usize + + std::mem::size_of::(); + let value_end = first_value as usize + + (count - 1) as usize * value_stride as usize + + std::mem::size_of::(); + let disjoint = glyph_end <= first_value as usize || value_end <= first_glyph as usize; + if disjoint + && first_value.is_aligned() + && (count == 1 + || (value_stride as usize >= std::mem::size_of::() + && (value_stride as usize).is_multiple_of(std::mem::align_of::()))) + { + batch(StridedGlyphs { + index: 0, + count, + first_glyph, + glyph_stride, + first_value, + value_stride, + lifetime: PhantomData, + }); + } else { + // Unaligned or overlapping slots cannot yield simultaneous &mut + // references. Use one stack output at a time and scatter it back. + for i in 0..count { + let mut value = 0; + batch(StridedGlyphs { + index: 0, + count: 1, + first_glyph: first_glyph + .cast::() + .add(i as usize * glyph_stride as usize) + .cast(), + glyph_stride: 0, + first_value: &mut value, + value_stride: 0, + lifetime: PhantomData, + }); + write_struct_at_offset(first_value, i, value_stride, value); + } + } } #[cfg(feature = "skrifa")] @@ -322,12 +424,12 @@ extern "C" fn _hb_fontations_get_nominal_glyphs( let char_map = data.instance.charmap(); for i in 0..count { - let unicode = struct_at_offset(first_unicode, i, unicode_stride); + let unicode = unsafe { struct_at_offset(first_unicode, i, unicode_stride) }; let Some(glyph) = char_map.map_unicode(unicode) else { return i; }; let glyph_id = glyph.to_u32() as hb_codepoint_t; - *struct_at_offset_mut(first_glyph, i, glyph_stride) = glyph_id; + unsafe { write_struct_at_offset(first_glyph, i, glyph_stride, glyph_id) }; } count @@ -368,18 +470,22 @@ extern "C" fn _hb_fontations_get_glyph_h_advances( let data = unsafe { &mut *(font_data as *mut FontationsData) }; data.check_for_updates(); - let glyphs = (0..count).map(|i| { - let glyph = GlyphId::new(struct_at_offset(first_glyph, i, glyph_stride)); - ( - glyph, - struct_at_offset_mut(first_advance, i, advance_stride), - ) - }); - data.instance.glyph_metrics().h_advance_batched( - // Skrifa rounded advances to design units before applying our scale. - |advance| (advance.to_i32() as f32 * data.x_mult).round() as hb_position_t, - glyphs, - ); + unsafe { + with_strided_glyphs( + count, + first_glyph, + glyph_stride, + first_advance, + advance_stride, + |glyphs| { + data.instance.glyph_metrics().h_advance_batched( + // Skrifa rounded advances to design units before applying our scale. + |advance| (advance.to_i32() as f32 * data.x_mult).round() as hb_position_t, + glyphs, + ); + }, + ); + } } extern "C" fn _hb_fontations_get_glyph_v_advances( @@ -396,16 +502,20 @@ extern "C" fn _hb_fontations_get_glyph_v_advances( data.check_for_updates(); let line = font_line_extents(font); - let glyphs = (0..count).map(|i| { - let glyph = GlyphId::new(struct_at_offset(first_glyph, i, glyph_stride)); - ( - glyph, - struct_at_offset_mut(first_advance, i, advance_stride), - ) - }); - data.glyph_metrics() - .with_line_extents(Some(line)) - .v_advance_batched(|advance| hb_position(advance).saturating_neg(), glyphs); + unsafe { + with_strided_glyphs( + count, + first_glyph, + glyph_stride, + first_advance, + advance_stride, + |glyphs| { + data.glyph_metrics() + .with_line_extents(Some(line)) + .v_advance_batched(|advance| hb_position(advance).saturating_neg(), glyphs); + }, + ); + } } extern "C" fn _hb_fontations_get_glyph_v_origin( diff --git a/test/api/test-font.c b/test/api/test-font.c index 2bd40e15e..01221d8c5 100644 --- a/test/api/test-font.c +++ b/test/api/test-font.c @@ -832,6 +832,69 @@ test_fontations_scale_changes (void) } } +static void +test_fontations_strides (void) +{ + hb_face_t *face = hb_test_open_font_file ("fonts/Roboto-Regular.abc.ttf"); + hb_font_t *font = hb_font_create (face); + hb_fontations_font_set_funcs (font); + const hb_codepoint_t unicodes[] = {'a', 'b', 'c'}; + hb_codepoint_t ids[3]; + uint8_t unicode_bytes[16], glyph_bytes[16], advance_bytes[16]; + memset (unicode_bytes, 0xA5, sizeof (unicode_bytes)); + memset (glyph_bytes, 0xA5, sizeof (glyph_bytes)); + for (unsigned i = 0; i < G_N_ELEMENTS (unicodes); i++) + { + memcpy (unicode_bytes + 1 + 5 * i, &unicodes[i], sizeof (unicodes[i])); + g_assert_true (hb_font_get_nominal_glyph (font, unicodes[i], &ids[i])); + } + g_assert_cmpuint (hb_font_get_nominal_glyphs (font, 3, + (const hb_codepoint_t *) (unicode_bytes + 1), 5, + (hb_codepoint_t *) (glyph_bytes + 1), 5), ==, 3); + for (unsigned i = 0; i < 3; i++) + { + hb_codepoint_t glyph; + memcpy (&glyph, glyph_bytes + 1 + 5 * i, sizeof (glyph)); + g_assert_cmpuint (glyph, ==, ids[i]); + g_assert_cmpuint (glyph_bytes[5 * i + 5], ==, 0xA5); + } + g_assert_cmpuint (glyph_bytes[0], ==, 0xA5); + + void (*get_advances[])(hb_font_t *, unsigned, const hb_codepoint_t *, unsigned, + hb_position_t *, unsigned) = { + hb_font_get_glyph_h_advances, hb_font_get_glyph_v_advances, + }; + for (unsigned axis = 0; axis < G_N_ELEMENTS (get_advances); axis++) + { + hb_position_t expected[3]; + get_advances[axis] (font, 3, ids, sizeof (ids[0]), expected, sizeof (expected[0])); + memset (advance_bytes, 0xA5, sizeof (advance_bytes)); + get_advances[axis] (font, 3, (const hb_codepoint_t *) (glyph_bytes + 1), 5, + (hb_position_t *) (advance_bytes + 1), 5); + for (unsigned i = 0; i < 3; i++) + { + hb_position_t advance; + memcpy (&advance, advance_bytes + 1 + 5 * i, sizeof (advance)); + g_assert_cmpint (advance, ==, expected[i]); + g_assert_cmpuint (advance_bytes[5 * i + 5], ==, 0xA5); + } + g_assert_cmpuint (advance_bytes[0], ==, 0xA5); + + hb_position_t last = 0; + get_advances[axis] (font, 3, ids, sizeof (ids[0]), &last, 0); + g_assert_cmpint (last, ==, expected[2]); + + hb_codepoint_t in_place[3]; + memcpy (in_place, ids, sizeof (ids)); + get_advances[axis] (font, 3, in_place, sizeof (in_place[0]), + (hb_position_t *) in_place, sizeof (in_place[0])); + for (unsigned i = 0; i < 3; i++) + g_assert_cmpint ((hb_position_t) in_place[i], ==, expected[i]); + } + hb_font_destroy (font); + hb_face_destroy (face); +} + static void test_fontations_advances (void) { @@ -924,6 +987,7 @@ main (int argc, char **argv) #ifdef HAVE_FONTATIONS hb_test_add (test_fontations_glyph_from_name_threads); hb_test_add (test_fontations_scale_changes); + hb_test_add (test_fontations_strides); hb_test_add (test_fontations_advances); #endif From cdf5edb49e9fe8e877c96a51db87e690bafdb419 Mon Sep 17 00:00:00 2001 From: Behdad Esfahbod Date: Sat, 3 Oct 2026 19:19:55 -0600 Subject: [PATCH 08/15] [rust] Batch Fontations vertical origins Register the vertical-origins batch callback. Compute X using HarfBuzz's batched horizontal advances, then compute Y with v_origin_y_batched. Retain HarfBuzz line and glyph-extents callbacks for fallback behavior. Preserve scalar write order for aliased inputs, overlapping outputs, and repeated X slots while batching normal interleaved position buffers. Add default/varied glyf, CFF, and CFF2 coverage with strided, unaligned, in-place, repeated, invalid-glyph, and zero-count queries. Tests: full Meson suite (281 passed, 1 skipped); font-only Clippy; unchanged 144-case metric snapshots. Another 48 full-font batch cases (53,622 glyph origins) matched the old scalar implementation. Clippy used opt-level=0 for the nightly compiler workaround. Seven-run origin medians improved about 19% overall, about 36-38% for unvaried glyf fonts; varied glyf and CFF/CFF2 remain dominated by extents. Assisted-by: OpenAI Codex --- src/rust/font.rs | 93 +++++++++++++++++++++++++++++++++++--------- test/api/test-font.c | 88 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 163 insertions(+), 18 deletions(-) diff --git a/src/rust/font.rs b/src/rust/font.rs index 292055152..904033a15 100644 --- a/src/rust/font.rs +++ b/src/rust/font.rs @@ -297,6 +297,23 @@ impl<'a> Iterator for StridedGlyphs<'a> { } } +fn strided_ranges_overlap( + count: u32, + first_a: *const T, + stride_a: u32, + first_b: *const U, + stride_b: u32, +) -> bool { + if count == 0 { + return false; + } + let end_a = + first_a as usize + (count - 1) as usize * stride_a as usize + std::mem::size_of::(); + let end_b = + first_b as usize + (count - 1) as usize * stride_b as usize + std::mem::size_of::(); + end_a > first_b as usize && end_b > first_a as usize +} + // SAFETY: All input/output slots must be readable/writable for this call. // The callback must access these buffers only through the supplied iterator. unsafe fn with_strided_glyphs( @@ -310,13 +327,8 @@ unsafe fn with_strided_glyphs( if count == 0 { return; } - let glyph_end = first_glyph as usize - + (count - 1) as usize * glyph_stride as usize - + std::mem::size_of::(); - let value_end = first_value as usize - + (count - 1) as usize * value_stride as usize - + std::mem::size_of::(); - let disjoint = glyph_end <= first_value as usize || value_end <= first_glyph as usize; + let disjoint = + !strided_ranges_overlap(count, first_glyph, glyph_stride, first_value, value_stride); if disjoint && first_value.is_aligned() && (count == 1 @@ -518,19 +530,54 @@ extern "C" fn _hb_fontations_get_glyph_v_advances( } } -extern "C" fn _hb_fontations_get_glyph_v_origin( +extern "C" fn _hb_fontations_get_glyph_v_origins( font: *mut hb_font_t, font_data: *mut ::std::os::raw::c_void, - glyph: hb_codepoint_t, - x: *mut hb_position_t, - y: *mut hb_position_t, + count: ::std::os::raw::c_uint, + first_glyph: *const hb_codepoint_t, + glyph_stride: ::std::os::raw::c_uint, + first_x: *mut hb_position_t, + x_stride: ::std::os::raw::c_uint, + first_y: *mut hb_position_t, + y_stride: ::std::os::raw::c_uint, _user_data: *mut ::std::os::raw::c_void, ) -> hb_bool_t { + // Preserve scalar write order for aliased buffers. Equal output strides + // can share an interleaved buffer while still having disjoint slots. + let outputs_overlap = strided_ranges_overlap(count, first_x, x_stride, first_y, y_stride); + let interleaved = x_stride == y_stride && x_stride != 0 && { + let gap = (first_x as usize).abs_diff(first_y as usize) % x_stride as usize; + gap >= std::mem::size_of::() + && x_stride as usize - gap >= std::mem::size_of::() + }; + if (count > 1 && (x_stride as usize) < std::mem::size_of::()) + || strided_ranges_overlap(count, first_glyph, glyph_stride, first_x, x_stride) + || strided_ranges_overlap(count, first_glyph, glyph_stride, first_y, y_stride) + || (outputs_overlap && !interleaved) + { + for i in 0..count { + let glyph = unsafe { struct_at_offset(first_glyph, i, glyph_stride) }; + let (mut x, mut y) = (0, 0); + _hb_fontations_get_glyph_v_origins( + font, font_data, 1, &glyph, 0, &mut x, 0, &mut y, 0, _user_data, + ); + unsafe { + write_struct_at_offset(first_x, i, x_stride, x); + write_struct_at_offset(first_y, i, y_stride, y); + } + } + return true as hb_bool_t; + } + let data = unsafe { &mut *(font_data as *mut FontationsData) }; data.check_for_updates(); unsafe { - *x = hb_font_get_glyph_h_advance(font, glyph) / 2; + hb_font_get_glyph_h_advances(font, count, first_glyph, glyph_stride, first_x, x_stride); + for i in 0..count { + let x = struct_at_offset(first_x, i, x_stride) / 2; + write_struct_at_offset(first_x, i, x_stride, x); + } } let line = font_line_extents(font); @@ -546,12 +593,22 @@ extern "C" fn _hb_fontations_get_glyph_v_origin( height: -(extents.height as i64), }) }; - let y_origin = data + let metrics = data .glyph_metrics() .with_line_extents(Some(line)) - .with_glyph_extents(Some(&extents)) - .v_origin_y(GlyphId::new(glyph)); - unsafe { *y = hb_position(y_origin) }; + .with_glyph_extents(Some(&extents)); + unsafe { + with_strided_glyphs( + count, + first_glyph, + glyph_stride, + first_y, + y_stride, + |glyphs| { + metrics.v_origin_y_batched(hb_position, glyphs); + }, + ); + } true as hb_bool_t } @@ -1424,9 +1481,9 @@ fn _hb_fontations_font_funcs_get() -> *mut hb_font_funcs_t { null_mut(), None, ); - hb_font_funcs_set_glyph_v_origin_func( + hb_font_funcs_set_glyph_v_origins_func( ffuncs, - Some(_hb_fontations_get_glyph_v_origin), + Some(_hb_fontations_get_glyph_v_origins), null_mut(), None, ); diff --git a/test/api/test-font.c b/test/api/test-font.c index 01221d8c5..c6bde9f26 100644 --- a/test/api/test-font.c +++ b/test/api/test-font.c @@ -895,6 +895,93 @@ test_fontations_strides (void) hb_face_destroy (face); } +static void +test_fontations_v_origins (void) +{ + const char *fonts[] = { + "fonts/Roboto-Regular.abc.ttf", + "fonts/Roboto-Variable.abc.ttf", + "fonts/SourceSerifVariable-Roman-VVAR.abc.ttf", + "fonts/AdobeVFPrototype.abc.otf", + "../shape/data/in-house/fonts/NotoSansCJK-VF.abc.ttf", + "../shape/data/in-house/fonts/NotoSansCJK-VF.abc.otf", + }; + const int coords[] = {0, 16384, -16384, 0}; + const hb_codepoint_t glyphs[] = {0, 1, 2, 3, HB_CODEPOINT_INVALID}; + for (unsigned f = 0; f < G_N_ELEMENTS (fonts); f++) + { + hb_face_t *face = hb_test_open_font_file (fonts[f]); + hb_font_t *font = hb_font_create (face); + hb_fontations_font_set_funcs (font); + int upem = hb_face_get_upem (face); + for (int sign = 1; sign >= -1; sign -= 2) + { + hb_font_set_scale (font, sign * upem * 2, sign * upem * 3); + for (unsigned c = 0; c < G_N_ELEMENTS (coords); c++) + { + hb_font_set_var_coords_normalized (font, &coords[c], 1); + hb_position_t expected_x[G_N_ELEMENTS (glyphs)], expected_y[G_N_ELEMENTS (glyphs)]; + for (unsigned i = 0; i < G_N_ELEMENTS (glyphs); i++) + g_assert_true (hb_font_get_glyph_v_origin (font, glyphs[i], &expected_x[i], &expected_y[i])); + + hb_position_t origins[4 * G_N_ELEMENTS (glyphs)]; + for (unsigned i = 0; i < G_N_ELEMENTS (origins); i++) + origins[i] = 123456; + g_assert_true (hb_font_get_glyph_v_origins (font, G_N_ELEMENTS (glyphs), + glyphs, sizeof (glyphs[0]), + origins, 4 * sizeof (origins[0]), + origins + 1, 4 * sizeof (origins[0]))); + for (unsigned i = 0; i < G_N_ELEMENTS (glyphs); i++) + { + g_assert_cmpint (origins[4 * i], ==, expected_x[i]); + g_assert_cmpint (origins[4 * i + 1], ==, expected_y[i]); + g_assert_cmpint (origins[4 * i + 2], ==, 123456); + g_assert_cmpint (origins[4 * i + 3], ==, 123456); + } + + hb_position_t last_x = 0, last_y = 0; + g_assert_true (hb_font_get_glyph_v_origins (font, G_N_ELEMENTS (glyphs), + glyphs, sizeof (glyphs[0]), &last_x, 0, &last_y, 0)); + g_assert_cmpint (last_x, ==, expected_x[G_N_ELEMENTS (glyphs) - 1]); + g_assert_cmpint (last_y, ==, expected_y[G_N_ELEMENTS (glyphs) - 1]); + + hb_codepoint_t in_place[G_N_ELEMENTS (glyphs)]; + memcpy (in_place, glyphs, sizeof (glyphs)); + g_assert_true (hb_font_get_glyph_v_origins (font, G_N_ELEMENTS (glyphs), + in_place, sizeof (in_place[0]), + (hb_position_t *) in_place, sizeof (in_place[0]), + origins, sizeof (origins[0]))); + for (unsigned i = 0; i < G_N_ELEMENTS (glyphs); i++) + { + g_assert_cmpint ((hb_position_t) in_place[i], ==, expected_x[i]); + g_assert_cmpint (origins[i], ==, expected_y[i]); + } + + uint8_t x_bytes[1 + 5 * G_N_ELEMENTS (glyphs)], y_bytes[sizeof (x_bytes)]; + memset (x_bytes, 0xA5, sizeof (x_bytes)); + memset (y_bytes, 0xA5, sizeof (y_bytes)); + g_assert_true (hb_font_get_glyph_v_origins (font, G_N_ELEMENTS (glyphs), + glyphs, sizeof (glyphs[0]), + (hb_position_t *) (x_bytes + 1), 5, + (hb_position_t *) (y_bytes + 1), 5)); + for (unsigned i = 0; i < G_N_ELEMENTS (glyphs); i++) + { + hb_position_t x, y; + memcpy (&x, x_bytes + 1 + 5 * i, sizeof (x)); + memcpy (&y, y_bytes + 1 + 5 * i, sizeof (y)); + g_assert_cmpint (x, ==, expected_x[i]); + g_assert_cmpint (y, ==, expected_y[i]); + g_assert_cmpuint (x_bytes[5 * i + 5], ==, 0xA5); + g_assert_cmpuint (y_bytes[5 * i + 5], ==, 0xA5); + } + g_assert_true (hb_font_get_glyph_v_origins (font, 0, NULL, 0, NULL, 0, NULL, 0)); + } + } + hb_font_destroy (font); + hb_face_destroy (face); + } +} + static void test_fontations_advances (void) { @@ -988,6 +1075,7 @@ main (int argc, char **argv) hb_test_add (test_fontations_glyph_from_name_threads); hb_test_add (test_fontations_scale_changes); hb_test_add (test_fontations_strides); + hb_test_add (test_fontations_v_origins); hb_test_add (test_fontations_advances); #endif From 5d86ce2980e06e0e6831d627eed142a861e1d652 Mon Sep 17 00:00:00 2001 From: Behdad Esfahbod Date: Sat, 3 Oct 2026 19:32:19 -0600 Subject: [PATCH 09/15] [rust] Keep disjoint interleaved fields on the batch path Overlapping bounding ranges do not imply that strided input and output slots overlap. For equal strides, check field separation modulo the stride, including the gap across record boundaries. Share this check between advances and vertical origins. Cover interleaved glyph/position records and hb-ot-normalize's mapping from codepoint to var1.u32 within the same glyph-info array. Tests: full Meson suite (281 passed, 1 skipped), using opt-level=0 for Clippy's nightly compiler workaround. An exhaustive standalone check covered 3,136,320 stride/offset/count layouts. Seven-run medians for interleaved Roboto improved 2.64x for horizontal advances, 22.77x for vertical advances, and 1.77x for vertical origins. Assisted-by: OpenAI Codex --- src/rust/font.rs | 38 +++++++++++++++++++------------ test/api/test-font.c | 54 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+), 14 deletions(-) diff --git a/src/rust/font.rs b/src/rust/font.rs index 904033a15..42730169f 100644 --- a/src/rust/font.rs +++ b/src/rust/font.rs @@ -297,7 +297,8 @@ impl<'a> Iterator for StridedGlyphs<'a> { } } -fn strided_ranges_overlap( +// Conservatively check the used slots, allowing disjoint interleaved fields. +fn strided_slots_overlap( count: u32, first_a: *const T, stride_a: u32, @@ -311,7 +312,22 @@ fn strided_ranges_overlap( first_a as usize + (count - 1) as usize * stride_a as usize + std::mem::size_of::(); let end_b = first_b as usize + (count - 1) as usize * stride_b as usize + std::mem::size_of::(); - end_a > first_b as usize && end_b > first_a as usize + if end_a <= first_b as usize || end_b <= first_a as usize { + return false; + } + if stride_a == stride_b && stride_a != 0 { + let gap = (first_a as usize).abs_diff(first_b as usize) % stride_a as usize; + let (size_low, size_high) = if first_a as usize <= first_b as usize { + (std::mem::size_of::(), std::mem::size_of::()) + } else { + (std::mem::size_of::(), std::mem::size_of::()) + }; + // Both gaps must fit the fields, including across record boundaries. + if gap >= size_low && stride_a as usize - gap >= size_high { + return false; + } + } + true } // SAFETY: All input/output slots must be readable/writable for this call. @@ -328,7 +344,7 @@ unsafe fn with_strided_glyphs( return; } let disjoint = - !strided_ranges_overlap(count, first_glyph, glyph_stride, first_value, value_stride); + !strided_slots_overlap(count, first_glyph, glyph_stride, first_value, value_stride); if disjoint && first_value.is_aligned() && (count == 1 @@ -542,18 +558,12 @@ extern "C" fn _hb_fontations_get_glyph_v_origins( y_stride: ::std::os::raw::c_uint, _user_data: *mut ::std::os::raw::c_void, ) -> hb_bool_t { - // Preserve scalar write order for aliased buffers. Equal output strides - // can share an interleaved buffer while still having disjoint slots. - let outputs_overlap = strided_ranges_overlap(count, first_x, x_stride, first_y, y_stride); - let interleaved = x_stride == y_stride && x_stride != 0 && { - let gap = (first_x as usize).abs_diff(first_y as usize) % x_stride as usize; - gap >= std::mem::size_of::() - && x_stride as usize - gap >= std::mem::size_of::() - }; + // Preserve scalar write order for aliased buffers, while batching disjoint + // glyph and position fields in the same interleaved records. if (count > 1 && (x_stride as usize) < std::mem::size_of::()) - || strided_ranges_overlap(count, first_glyph, glyph_stride, first_x, x_stride) - || strided_ranges_overlap(count, first_glyph, glyph_stride, first_y, y_stride) - || (outputs_overlap && !interleaved) + || strided_slots_overlap(count, first_glyph, glyph_stride, first_x, x_stride) + || strided_slots_overlap(count, first_glyph, glyph_stride, first_y, y_stride) + || strided_slots_overlap(count, first_x, x_stride, first_y, y_stride) { for i in 0..count { let glyph = unsafe { struct_at_offset(first_glyph, i, glyph_stride) }; diff --git a/test/api/test-font.c b/test/api/test-font.c index c6bde9f26..9f2a5cb84 100644 --- a/test/api/test-font.c +++ b/test/api/test-font.c @@ -860,6 +860,28 @@ test_fontations_strides (void) } g_assert_cmpuint (glyph_bytes[0], ==, 0xA5); + /* hb-ot-normalize maps codepoint to var1.u32 in the same glyph-info array. */ + hb_glyph_info_t infos[3] = {0}; + for (unsigned i = 0; i < G_N_ELEMENTS (infos); i++) + { + infos[i].codepoint = unicodes[i]; + infos[i].mask = 123456; + infos[i].cluster = i; + infos[i].var1.u32 = HB_CODEPOINT_INVALID; + infos[i].var2.u32 = 123456; + } + g_assert_cmpuint (hb_font_get_nominal_glyphs (font, G_N_ELEMENTS (infos), + &infos[0].codepoint, sizeof (infos[0]), + &infos[0].var1.u32, sizeof (infos[0])), ==, G_N_ELEMENTS (infos)); + for (unsigned i = 0; i < G_N_ELEMENTS (infos); i++) + { + g_assert_cmpuint (infos[i].codepoint, ==, unicodes[i]); + g_assert_cmpuint (infos[i].var1.u32, ==, ids[i]); + g_assert_cmpuint (infos[i].mask, ==, 123456); + g_assert_cmpuint (infos[i].cluster, ==, i); + g_assert_cmpuint (infos[i].var2.u32, ==, 123456); + } + void (*get_advances[])(hb_font_t *, unsigned, const hb_codepoint_t *, unsigned, hb_position_t *, unsigned) = { hb_font_get_glyph_h_advances, hb_font_get_glyph_v_advances, @@ -891,6 +913,38 @@ test_fontations_strides (void) for (unsigned i = 0; i < 3; i++) g_assert_cmpint ((hb_position_t) in_place[i], ==, expected[i]); } + + struct { + hb_codepoint_t glyph; + hb_position_t h_advance, v_advance, x, y, padding; + } records[3]; + for (unsigned i = 0; i < G_N_ELEMENTS (records); i++) + { + records[i].glyph = ids[i]; + records[i].h_advance = records[i].v_advance = records[i].x = records[i].y = 0; + records[i].padding = 123456; + } + hb_font_get_glyph_h_advances (font, G_N_ELEMENTS (records), + &records[0].glyph, sizeof (records[0]), + &records[0].h_advance, sizeof (records[0])); + hb_font_get_glyph_v_advances (font, G_N_ELEMENTS (records), + &records[0].glyph, sizeof (records[0]), + &records[0].v_advance, sizeof (records[0])); + g_assert_true (hb_font_get_glyph_v_origins (font, G_N_ELEMENTS (records), + &records[0].glyph, sizeof (records[0]), + &records[0].x, sizeof (records[0]), + &records[0].y, sizeof (records[0]))); + for (unsigned i = 0; i < G_N_ELEMENTS (records); i++) + { + hb_position_t x, y; + g_assert_cmpuint (records[i].glyph, ==, ids[i]); + g_assert_cmpint (records[i].h_advance, ==, hb_font_get_glyph_h_advance (font, ids[i])); + g_assert_cmpint (records[i].v_advance, ==, hb_font_get_glyph_v_advance (font, ids[i])); + g_assert_true (hb_font_get_glyph_v_origin (font, ids[i], &x, &y)); + g_assert_cmpint (records[i].x, ==, x); + g_assert_cmpint (records[i].y, ==, y); + g_assert_cmpint (records[i].padding, ==, 123456); + } hb_font_destroy (font); hb_face_destroy (face); } From 64259b67cdc64448b885d69d1a3eb62414f3d268 Mon Sep 17 00:00:00 2001 From: Behdad Esfahbod Date: Sat, 3 Oct 2026 19:37:14 -0600 Subject: [PATCH 10/15] Update HarfRust version to upcoming release --- src/rust/Cargo.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/rust/Cargo.toml b/src/rust/Cargo.toml index 5431a86ba..38fe6a633 100644 --- a/src/rust/Cargo.toml +++ b/src/rust/Cargo.toml @@ -4,8 +4,8 @@ edition = "2021" rust-version = "1.87.0" [dependencies] -# harfrust = { version = "0.13.3", optional = true } -harfrust = { git = "https://github.com/harfbuzz/harfrust", optional = true } +harfrust = { version = "0.14.0", optional = true } +# harfrust = { git = "https://github.com/harfbuzz/harfrust", optional = true } read-fonts = { version = "0.45.*", optional = true } skrifa = { version = "0.48.*", optional = true, default-features = false, features = ["std"] } smallvec = { version = "1.*", optional = true } From bc8e5d876081f37b200220dbf253aff76cabe091 Mon Sep 17 00:00:00 2001 From: Behdad Esfahbod Date: Sat, 3 Oct 2026 20:51:48 -0600 Subject: [PATCH 11/15] [rust] Round Fontations advances without a libm call Float rounding accounts for about a third of static horizontal advance lookup time. Bias in f64 before the saturating integer conversion to preserve ties away from zero without calling roundf for each glyph. Using f64 also preserves values immediately below half-integers. An exhaustive comparison of all f32 bit patterns produces the same integer results. All 144 font/scale/location metric snapshots match. The full Meson suite passes (281 tests, one skip); release Clippy uses opt-level=0 to work around a nightly compiler hang. Library and benchmark builds remain optimized. Assisted-by: OpenAI Codex --- src/rust/font.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/rust/font.rs b/src/rust/font.rs index 42730169f..f635b1e53 100644 --- a/src/rust/font.rs +++ b/src/rust/font.rs @@ -234,6 +234,13 @@ fn hb_position(value: i64) -> hb_position_t { value.clamp(hb_position_t::MIN as i64, hb_position_t::MAX as i64) as hb_position_t } +#[inline] +fn round_to_position(value: f32) -> hb_position_t { + // Bias in f64 so values just below a half-integer do not round up. + let value = f64::from(value); + (value + 0.5f64.copysign(value)) as hb_position_t +} + fn font_line_extents(font: *mut hb_font_t) -> LineExtents { let mut extents: hb_font_extents_t = unsafe { std::mem::zeroed() }; unsafe { @@ -508,7 +515,7 @@ extern "C" fn _hb_fontations_get_glyph_h_advances( |glyphs| { data.instance.glyph_metrics().h_advance_batched( // Skrifa rounded advances to design units before applying our scale. - |advance| (advance.to_i32() as f32 * data.x_mult).round() as hb_position_t, + |advance| round_to_position(advance.to_i32() as f32 * data.x_mult), glyphs, ); }, From eff2d6b995e0b45e3224079640457fa524c411b9 Mon Sep 17 00:00:00 2001 From: Behdad Esfahbod Date: Sat, 3 Oct 2026 20:56:18 -0600 Subject: [PATCH 12/15] [rust] Reuse fast rounding for scaled Fontations metrics Use the equivalent saturating integer conversion for both axes of the read-fonts scale adapter. This avoids roundf calls when scaling extents, vertical advances, origins, and font bounds. Repeated CPU-pinned benchmarks improve unvaried glyf extents and vertical origins by about 9-10%. All 144 metric snapshots remain unchanged. The full Meson suite passes (281 tests, one skip), with opt-level=0 for release Clippy's nightly compiler workaround; the library stays optimized. Assisted-by: OpenAI Codex --- src/rust/font.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/rust/font.rs b/src/rust/font.rs index f635b1e53..ba2ad21a7 100644 --- a/src/rust/font.rs +++ b/src/rust/font.rs @@ -202,11 +202,11 @@ impl Scale for FontationsScale { } fn scale_x(&self, value: F48Dot16) -> i64 { - (value.to_f32() * self.x_mult).round() as hb_position_t as i64 + round_to_position(value.to_f32() * self.x_mult) as i64 } fn scale_y(&self, value: F48Dot16) -> i64 { - (value.to_f32() * self.y_mult).round() as hb_position_t as i64 + round_to_position(value.to_f32() * self.y_mult) as i64 } fn scale_glyph_extents(&self, extents: GlyphExtents) -> GlyphExtents { From ac57fc11f48416e82ce57bb4c025a05c83616649 Mon Sep 17 00:00:00 2001 From: Behdad Esfahbod Date: Sat, 3 Oct 2026 23:07:23 -0600 Subject: [PATCH 13/15] [rust] Query bitmap ppem only when looking up a strike Move the ppem query into the optional bitmap-strike lookups. Fonts without sbix or CBDT strikes no longer cross the FFI boundary to read ppem for every extent query. Strike preference and extents are unchanged. CPU-pinned comparisons improve unvaried glyf extents and vertical origins by about 2%, with no material CFF or varied-outline regression. The full Meson suite passes (281 tests, one skip), rustfmt passes, and all 144 font/scale/location metric snapshots match. Assisted-by: OpenAI Codex --- src/rust/font.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/rust/font.rs b/src/rust/font.rs index ba2ad21a7..910516206 100644 --- a/src/rust/font.rs +++ b/src/rust/font.rs @@ -645,16 +645,15 @@ extern "C" fn _hb_fontations_get_glyph_extents( #[cfg(feature = "skrifa")] { let skrifa = &data.skrifa; - let size = bitmap_size(_font); let bitmap_glyph = skrifa .sbix_strikes .as_ref() - .and_then(|strikes| strikes.glyph_for_size(size, glyph_id)) + .and_then(|strikes| strikes.glyph_for_size(bitmap_size(_font), glyph_id)) .or_else(|| { skrifa .cbdt_strikes .as_ref() - .and_then(|strikes| strikes.glyph_for_size(size, glyph_id)) + .and_then(|strikes| strikes.glyph_for_size(bitmap_size(_font), glyph_id)) }); if let Some(bitmap_glyph) = bitmap_glyph { let Some(bitmap_extents) = bitmap_glyph_extents(data, &bitmap_glyph) else { From 21895566c30d0256557a31308fb0328cecde8571 Mon Sep 17 00:00:00 2001 From: Behdad Esfahbod Date: Sat, 3 Oct 2026 23:21:02 -0600 Subject: [PATCH 14/15] [rust] Defer bitmap ppem queries until painting a strike Fonts without CBDT or sbix data still queried ppem before returning from bitmap painting. Move the query into the optional strike lookups. Keep the existing CBDT preference and bitmap glyph handling. Unsupported painting in benchmark-font improves about 9-12% across the fixtures. These fonts contain no color glyphs, so this measures the early-return path rather than bitmap rendering. The full Meson suite passes (281 tests, one skip), rustfmt passes, and all 144 font/scale/location metric snapshots are unchanged. Assisted-by: OpenAI Codex --- src/rust/font.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/rust/font.rs b/src/rust/font.rs index 910516206..ee0c5bda5 100644 --- a/src/rust/font.rs +++ b/src/rust/font.rs @@ -1220,17 +1220,16 @@ fn paint_bitmap_glyph( paint_funcs: *mut hb_paint_funcs_t, paint_data: *mut ::std::os::raw::c_void, ) -> hb_bool_t { - let size = bitmap_size(font); let bitmap_glyph = data .skrifa .cbdt_strikes .as_ref() - .and_then(|strikes| strikes.glyph_for_size(size, glyph_id)) + .and_then(|strikes| strikes.glyph_for_size(bitmap_size(font), glyph_id)) .or_else(|| { data.skrifa .sbix_strikes .as_ref() - .and_then(|strikes| strikes.glyph_for_size(size, glyph_id)) + .and_then(|strikes| strikes.glyph_for_size(bitmap_size(font), glyph_id)) }); let Some(bitmap_glyph) = bitmap_glyph else { return false as hb_bool_t; From 692a0aa30e5962c6665f9f093519bb3f0cfff1ff Mon Sep 17 00:00:00 2001 From: Behdad Esfahbod Date: Sun, 4 Oct 2026 00:00:12 -0600 Subject: [PATCH 15/15] [rust] Reuse position rounding for COLRv1 bounds Convert COLRv1 clip bounds with the existing equivalent position rounding helper, retaining saturating width/height subtraction. This removes four roundf calls from each color glyph extent query. Seven CPU-pinned repetitions, confirmed against a repeated baseline, improve the 3845 color glyphs of Noto COLRv1 from 284.5 to 237.5 us (16.5%). Whole-font extents improve about 1%; Bungee controls without COLRv1 clip boxes remain within measurement noise. All glyph extents match across 36 color-font/scale/location cases, and the original 144 metric snapshots are unchanged. Rustfmt and the full Meson suite pass (281 tests, one skip). A local Clippy compiler crash cleared on rerun with a larger stack. Assisted-by: OpenAI Codex --- src/rust/font.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/rust/font.rs b/src/rust/font.rs index ee0c5bda5..5f0b3f285 100644 --- a/src/rust/font.rs +++ b/src/rust/font.rs @@ -670,12 +670,12 @@ extern "C" fn _hb_fontations_get_glyph_extents( return false as hb_bool_t; }; - let x_bearing = (glyph_extents.x_min * data.x_mult).round() as hb_position_t; - let width = ((glyph_extents.x_max * data.x_mult).round() as hb_position_t) - .saturating_sub(x_bearing); - let y_bearing = (glyph_extents.y_max * data.y_mult).round() as hb_position_t; - let height = ((glyph_extents.y_min * data.y_mult).round() as hb_position_t) - .saturating_sub(y_bearing); + let x_bearing = round_to_position(glyph_extents.x_min * data.x_mult); + let width = + round_to_position(glyph_extents.x_max * data.x_mult).saturating_sub(x_bearing); + let y_bearing = round_to_position(glyph_extents.y_max * data.y_mult); + let height = + round_to_position(glyph_extents.y_min * data.y_mult).saturating_sub(y_bearing); unsafe { *extents = hb_glyph_extents_t {