### str::len examples Source: https://docs.rs/fontcull-read-fonts/0.38.0/fontcull_read_fonts/tables/post/struct.PString.html Examples demonstrating how to get the length of a string in bytes. ```rust let len = "foo".len(); assert_eq!(3, len); assert_eq!("ƒoo".len(), 4); // fancy f! assert_eq!("ƒoo".chars().count(), 3); ``` -------------------------------- ### Trim start matches example Source: https://docs.rs/fontcull-read-fonts/0.38.0/fontcull_read_fonts/tables/post/struct.PString.html Demonstrates using trim_start_matches with a slice of characters. ```rust let x: &[_] = &['1', '2']; assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12"); ``` -------------------------------- ### str::as_ptr examples Source: https://docs.rs/fontcull-read-fonts/0.38.0/fontcull_read_fonts/tables/post/struct.PString.html Example demonstrating how to get a raw pointer to the string's first byte. ```rust let s = "Hello"; let ptr = s.as_ptr(); ``` -------------------------------- ### get method example Source: https://docs.rs/fontcull-font-test-data/0.6.2/fontcull_font_test_data/bebuffer/struct.BeBuffer.html Shows how to use the get method to retrieve an element or subslice by index or range, returning None if out of bounds. ```rust let v = [10, 40, 30]; assert_eq!(Some(&40), v.get(1)); assert_eq!(Some(&[10, 40][..]), v.get(0..2)); assert_eq!(None, v.get(3)); assert_eq!(None, v.get(0..4)); ``` -------------------------------- ### str::get examples Source: https://docs.rs/fontcull-read-fonts/0.38.0/fontcull_read_fonts/tables/post/struct.PString.html Examples demonstrating how to safely retrieve a subslice of a string. ```rust let v = String::from("🗻∈🌏"); assert_eq!(Some("🗻"), v.get(0..4)); // indices not on UTF-8 sequence boundaries assert!(v.get(1..).is_none()); assert!(v.get(..8).is_none()); // out of bounds assert!(v.get(..42).is_none()); ``` -------------------------------- ### take example Source: https://docs.rs/fontcull-write-fonts/0.44.3/fontcull_write_fonts/struct.NullableOffsetMarker.html Takes the value out of the option, leaving None in its place. The example shows taking from Some and None options. ```rust let mut x = Some(2); let y = x.take(); assert_eq!(x, None); assert_eq!(y, Some(2)); let mut x: Option = None; let y = x.take(); assert_eq!(x, None); assert_eq!(y, None); ``` -------------------------------- ### iter method example Source: https://docs.rs/fontcull-font-test-data/0.6.2/fontcull_font_test_data/bebuffer/struct.BeBuffer.html Shows how to iterate over the slice using the iter method, yielding all items from start to end. ```rust let x = &[1, 2, 4]; let mut iterator = x.iter(); assert_eq!(iterator.next(), Some(&1)); assert_eq!(iterator.next(), Some(&2)); assert_eq!(iterator.next(), Some(&4)); assert_eq!(iterator.next(), None); ``` -------------------------------- ### str::is_empty examples Source: https://docs.rs/fontcull-read-fonts/0.38.0/fontcull_read_fonts/tables/post/struct.PString.html Examples demonstrating how to check if a string is empty. ```rust let s = ""; assert!(s.is_empty()); let s = "not empty"; assert!(!s.is_empty()); ``` -------------------------------- ### trim_start_matches examples Source: https://docs.rs/fontcull-read-fonts/0.38.0/fontcull_read_fonts/tables/post/struct.PString.html Examples for trim_start_matches: removes repeated prefixes matching a char or a closure. ```rust assert_eq!("11foo1bar11".trim_start_matches('1'), "foo1bar11"); assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123"); ``` -------------------------------- ### trim_start directionality example Source: https://docs.rs/fontcull-read-fonts/0.38.0/x86_64-unknown-linux-gnu/fontcull_read_fonts/tables/post/struct.PString.html Demonstrates the directionality of `trim_start` on a string with leading and trailing spaces. The example asserts that the first character after trimming the start is 'E'. ```rust let s = " English "; assert!(Some('E') == s.trim_start().chars().next()); ``` -------------------------------- ### str::as_bytes examples Source: https://docs.rs/fontcull-read-fonts/0.38.0/fontcull_read_fonts/tables/post/struct.PString.html Example demonstrating how to convert a string slice to a byte slice. ```rust let bytes = "bors".as_bytes(); assert_eq!(b"bors", bytes); ``` -------------------------------- ### str::floor_char_boundary examples Source: https://docs.rs/fontcull-read-fonts/0.38.0/fontcull_read_fonts/tables/post/struct.PString.html Examples demonstrating how to find the closest character boundary not exceeding a given index. ```rust let s = "❤️🧡💛💚💙💜"; assert_eq!(s.len(), 26); assert!(!s.is_char_boundary(13)); let closest = s.floor_char_boundary(13); assert_eq!(closest, 10); assert_eq!(&s[..closest], "❤️🧡"); ``` -------------------------------- ### str::ceil_char_boundary examples Source: https://docs.rs/fontcull-read-fonts/0.38.0/fontcull_read_fonts/tables/post/struct.PString.html Examples demonstrating how to find the closest character boundary not below a given index. ```rust let s = "❤️🧡💛💚💙💜"; assert_eq!(s.len(), 26); assert!(!s.is_char_boundary(13)); let closest = s.ceil_char_boundary(13); assert_eq!(closest, 14); assert_eq!(&s[..closest], "❤️🧡💛"); ``` -------------------------------- ### Complex Serializer Population Examples Source: https://docs.rs/fontcull-klippa/0.1.2/src/fontcull_klippa/graph.rs.html Examples of populating a Serializer with complex object structures. ```rust fn populate_serializer_complex_2(s: &mut Serializer) { let _ = s.start_serialize(); let obj_5 = add_object(s, b"mn", 2); let obj_4 = add_object(s, b"jkl", 3); start_object(s, b"ghi", 3); add_offset(s, obj_4); let obj_3 = s.pop_pack(false).unwrap(); start_object(s, b"def", 3); add_offset(s, obj_3); let obj_2 = s.pop_pack(false).unwrap(); start_object(s, b"abc", 3); add_offset(s, obj_2); add_offset(s, obj_4); add_offset(s, obj_5); s.pop_pack(false); s.end_serialize(); } fn populate_serializer_complex_3(s: &mut Serializer) { let _ = s.start_serialize(); let obj_6 = add_object(s, b"opqrst", 6); let obj_5 = add_object(s, b"mn", 2); start_object(s, b"jkl", 3); add_offset(s, obj_6); let obj_4 = s.pop_pack(false).unwrap(); start_object(s, b"ghi", 3); add_offset(s, obj_4); let obj_3 = s.pop_pack(false).unwrap(); start_object(s, b"def", 3); add_offset(s, obj_3); } ``` -------------------------------- ### word_to_titlecase example Source: https://docs.rs/fontcull-read-fonts/0.38.0/x86_64-unknown-linux-gnu/fontcull_read_fonts/tables/post/struct.PString.html Example from the documentation of the `word_to_titlecase` method, showing the expected output for a Greek phrase. ```rust assert_eq!("Ο οδυσσέας βασιλιάς της ιθάκης", odysseus_king_of_ithaca.word_to_titlecase()); ``` -------------------------------- ### insert example Source: https://docs.rs/fontcull-write-fonts/0.44.3/fontcull_write_fonts/struct.NullableOffsetMarker.html Inserts a value into the option, replacing any existing value, and returns a mutable reference to it. The example shows inserting and updating values. ```rust let mut opt = None; let val = opt.insert(1); assert_eq!(*val, 1); assert_eq!(opt.unwrap(), 1); let val = opt.insert(2); assert_eq!(*val, 2); *val = 3; assert_eq!(opt.unwrap(), 3); ``` -------------------------------- ### Using GlyfLocaBuilder to build tables Source: https://docs.rs/fontcull-write-fonts/0.44.3/fontcull_write_fonts/tables/glyf/struct.GlyfLocaBuilder.html Example showing how to initialize a builder, add glyphs, and generate the final tables. ```rust use fontcull_write_fonts::tables::glyf::{Glyph, GlyfLocaBuilder}; let names_and_glyphs: Vec<(String, Glyph)> = get_glyphs(); let mut builder = GlyfLocaBuilder::new(); for (name, glyph) in names_and_glyphs { // your error handling goes here if let Err(e) = builder.add_glyph(&glyph) { panic!("error compiling glyph '{name}': '{e}'"); } } let (_glyf, _loca, _loca_format) = builder.build(); // store the results somewhere ``` -------------------------------- ### as_slice examples Source: https://docs.rs/fontcull-write-fonts/0.44.3/fontcull_write_fonts/struct.NullableOffsetMarker.html Demonstrates converting options to slices and comparing them to first elements. ```rust assert_eq!( [Some(1234).as_slice(), None.as_slice()], [&[1234][..], &[][..]], ); ``` ```rust for i in [Some(1234_u16), None] { assert_eq!(i.as_ref(), i.as_slice().first()); } ``` -------------------------------- ### Test Utilities and Setup Source: https://docs.rs/fontcull-write-fonts/0.44.3/src/fontcull_write_fonts/tables/name.rs.html Helper functions for initializing logging and creating name records for testing purposes. ```rust fn init() { let _ = env_logger::builder().is_test(true).try_init(); } fn make_name_record( platform_id: u16, encoding_id: u16, language_id: u16, name_id: u16, name: &str, ) -> NameRecord { NameRecord { platform_id, encoding_id, language_id, name_id: NameId::new(name_id), string: name.to_string().into(), } } ``` -------------------------------- ### build_feat_example helper Source: https://docs.rs/fontcull-read-fonts/0.38.0/src/fontcull_read_fonts/tables/feat.rs.html Constructs a sample feat table buffer for testing purposes. ```rust fn build_feat_example() -> BeBuffer { // Example taken from bottom of let mut buf = BeBuffer::new(); // header buf = buf.push(0x00010000u32).extend([4u16, 0, 0, 0]); // feature name array buf = buf.extend([0u16, 1]).push(60u32).extend([0u16, 260]); buf = buf.extend([1u16, 1]).push(64u32).extend([0u16, 256]); buf = buf.extend([3u16, 3]).push(68u32).extend([0x8000u16, 262]); buf = buf.extend([6u16, 2]).push(80u32).extend([0xC001u16, 258]); // The setting name array buf.extend([0u16, 261, 2, 257, 0, 268, 3, 264, 4, 265, 0, 259, 1, 260]) } ``` -------------------------------- ### Get axis by tag Source: https://docs.rs/fontcull-skrifa/0.39.2/fontcull_skrifa/struct.AxisCollection.html Returns the axis with the given tag. The example asserts that the returned axis has the same tag. ```rust let opsz = Tag::new(b"opsz"); assert_eq!(font.axes().get_by_tag(opsz).unwrap().tag(), opsz); ``` -------------------------------- ### Example: creating a VariationSetting from a tuple Source: https://docs.rs/fontcull-skrifa/0.39.2/fontcull_skrifa/setting/type.VariationSetting.html Shows how to create a VariationSetting using the From<(&str, f32)> conversion and compare it with VariationSetting::new. ```rust use fontcull_skrifa::{Tag, setting::VariationSetting}; // For convenience, a conversion from (&str, f32) is provided. let slightly_bolder: VariationSetting = ("wght", 720.0).into(); assert_eq!(slightly_bolder, VariationSetting::new(Tag::new(b"wght"), 720.0)); ``` -------------------------------- ### trim_start example with Hebrew text Source: https://docs.rs/fontcull-read-fonts/0.38.0/fontcull_read_fonts/tables/post/struct.PString.html Shows that trim_start removes leading whitespace, including for right-to-left text where 'start' is the right side. ```rust let s = " עברית "; assert!(Some('ע') == s.trim_start().chars().next()); ``` -------------------------------- ### str::word_to_titlecase no word segmentation example Source: https://docs.rs/fontcull-skrifa/0.39.2/fontcull_skrifa/outline/pen/struct.SvgPen.html Shows that no word segmentation is performed, so only the first cased letter in the whole string gets uppercased. ```rust #![feature(titlecase)] let blazingly_fast = "ferris and I"; assert_eq!("Ferris and i", blazingly_fast.word_to_titlecase()); ``` -------------------------------- ### windows method examples Source: https://docs.rs/fontcull-font-test-data/0.6.2/fontcull_font_test_data/bebuffer/struct.BeBuffer.html Shows how to use windows to iterate over overlapping contiguous windows of a given size. Includes a case where the slice is shorter than the window size, and a workaround using Cell::as_slice_of_cells for mutation. ```rust let slice = ['l', 'o', 'r', 'e', 'm']; let mut iter = slice.windows(3); assert_eq!(iter.next().unwrap(), &['l', 'o', 'r']); assert_eq!(iter.next().unwrap(), &['o', 'r', 'e']); assert_eq!(iter.next().unwrap(), &['r', 'e', 'm']); assert!(iter.next().is_none()); ``` ```rust let slice = ['f', 'o', 'o']; let mut iter = slice.windows(4); assert!(iter.next().is_none()); ``` ```rust use std::cell::Cell; let mut array = ['R', 'u', 's', 't', ' ', '2', '0', '1', '5']; let slice = &mut array[..]; let slice_of_cells: &[Cell] = Cell::from_mut(slice).as_slice_of_cells(); for w in slice_of_cells.windows(3) { Cell::swap(&w[0], &w[2]); } assert_eq!(array, ['s', 't', ' ', '2', '0', '1', '5', 'u', 'R']); ``` -------------------------------- ### Get axis by tag using AxisCollection::get_by_tag Source: https://docs.rs/fontcull-skrifa/0.39.2/src/fontcull_skrifa/variation.rs.html Example from the get_by_tag method documentation. Creates a Tag for 'opsz' and asserts that the axis returned by font.axes().get_by_tag() has the same tag. Requires a FontRef instance. ```rust /// # use fontcull_skrifa::prelude::*; /// # fn wrapper(font: &FontRef) { /// let opsz = Tag::new(b"opsz"); /// assert_eq!(font.axes().get_by_tag(opsz).unwrap().tag(), opsz); /// # } ``` -------------------------------- ### element_offset: get index of element reference Source: https://docs.rs/fontcull-font-test-data/0.6.2/fontcull_font_test_data/bebuffer/struct.BeBuffer.html Returns the index of an element reference within the slice. The element must point to the start of an element; otherwise returns `None`. Uses pointer arithmetic and does not compare elements. Panics if `T` is zero-sized. ```rust let nums: &[u32] = &[1, 7, 1, 1]; let num = &nums[2]; assert_eq!(num, &1); assert_eq!(nums.element_offset(num), Some(2)); ``` -------------------------------- ### Connect Method Example Source: https://docs.rs/fontcull-font-test-data/0.6.2/fontcull_font_test_data/bebuffer/struct.BeBuffer.html Shows the usage of the deprecated connect method, which has been renamed to join. ```rust assert_eq!(["hello", "world"].connect(" "), "hello world"); assert_eq!([[1, 2], [3, 4]].connect(&0), [1, 2, 0, 3, 4]); ``` -------------------------------- ### Cycle forward through slice starting at start+1 Source: https://docs.rs/fontcull-skrifa/0.39.2/src/fontcull_skrifa/outline/autohint/metrics/blues.rs.html Returns an iterator that starts at `start + 1` and cycles forward through all items of the slice, ending with `start`. Each item is paired with its real index. ```rust /// Iterator that begins at `start + 1` and cycles through all items /// of the slice in forward order, ending with `start`. pub(super) fn cycle_forward(items: &[T], start: usize) -> impl Iterator { let len = items.len(); let start = start + 1; (0..len).map(move |ix| { let real_ix = (ix + start) % len; (real_ix, &items[real_ix]) }) } ``` -------------------------------- ### Cycle backward through slice starting at start-1 Source: https://docs.rs/fontcull-skrifa/0.39.2/src/fontcull_skrifa/outline/autohint/metrics/blues.rs.html Returns an iterator that begins at `start - 1` and cycles through all items of the slice in reverse order, ending with `start`. Each item is paired with its real index. ```rust /// Iterator that begins at `start - 1` and cycles through all items /// of the slice in reverse order, ending with `start`. pub(super) fn cycle_backward(items: &[T], start: usize) -> impl Iterator { let len = items.len(); (0..len).rev().map(move |ix| { let real_ix = (ix + start) % len; (real_ix, &items[real_ix]) }) } ``` -------------------------------- ### HintState Implementation Source: https://docs.rs/fontcull-skrifa/0.39.2/src/fontcull_skrifa/outline/cff/hint.rs.html Provides methods for initializing HintState and building zones from HintParams. ```rust 93impl HintState { 94 pub fn new(params: &HintParams, scale: Fixed) -> Self { 95 let mut state = Self { 96 scale, 97 blue_scale: params.blue_scale, 98 blue_shift: params.blue_shift, 99 blue_fuzz: params.blue_fuzz, 100 language_group: params.language_group, 101 suppress_overshoot: false, 102 do_em_box_hints: false, 103 boost: Fixed::ZERO, 104 darken_y: Fixed::ZERO, 105 zones: [BlueZone::default(); MAX_BLUE_ZONES], 106 zone_count: 0, 107 }; 108 state.build_zones(params); 109 state 110 } 111 112 fn zones(&self) -> &[BlueZone] { 113 &self.zones[..self.zone_count] 114 } 115 116 /// Initialize zones from the set of blues values. 117 /// 118 /// See 119 fn build_zones(&mut self, params: &HintParams) { 120 self.do_em_box_hints = false; 121 // 122 match (self.language_group, params.blues.values().len()) { 123 (1, 2) => { 124 let blues = params.blues.values(); 125 if blues[0].0 < ICF_BOTTOM ``` -------------------------------- ### Read/modify/write an existing font with FontBuilder Source: https://docs.rs/fontcull-write-fonts/%5E0.44.3 Reads an existing font file, retrieves the 'head' table, modifies its 'modified' field, and writes a new font file with the updated table. Uses FontRef::new to parse the font, head().to_owned_table() to get an owned copy, and FontBuilder to add the modified table and copy missing tables from the original font. The example assumes path_to_my_font_file and seconds_since_font_epoch are defined elsewhere. ```rust use fontcull_read_fonts::{FontRef, TableProvider}; use fontcull_write_fonts::{ from_obj::ToOwnedTable, tables::head::Head, types::LongDateTime, FontBuilder, }; let font_bytes = std::fs::read(path_to_my_font_file).unwrap(); let font = FontRef::new(&font_bytes).expect("failed to read font data"); let mut head: Head = font.head().expect("missing 'head' table").to_owned_table(); head.modified = seconds_since_font_epoch(); let new_bytes = FontBuilder::new() .add_table(&head) .unwrap() // errors if we can't compile 'head', unlikely here .copy_missing_tables(font) .build(); std::fs::write("mynewfont.ttf", &new_bytes).unwrap(); ``` -------------------------------- ### Join Method Example Source: https://docs.rs/fontcull-font-test-data/0.6.2/fontcull_font_test_data/bebuffer/struct.BeBuffer.html Demonstrates flattening a slice of items with a separator placed between each. ```rust assert_eq!(["hello", "world"].join(" "), "hello world"); assert_eq!([[1, 2], [3, 4]].join(&0), [1, 2, 0, 3, 4]); assert_eq!([[1, 2], [3, 4]].join(&[0, 0][..]), [1, 2, 0, 0, 3, 4]); ``` -------------------------------- ### pub fn start(&self) -> F2Dot14 Source: https://docs.rs/fontcull-read-fonts/0.38.0/fontcull_read_fonts/tables/varc/struct.SparseRegionAxisCoordinates.html Returns the start coordinate as an F2Dot14 value. ```APIDOC ## pub fn start(&self) -> F2Dot14 ### Description Returns the start coordinate of the sparse region axis. ### Method pub fn start(&self) -> F2Dot14 ### Parameters None ### Returns - **F2Dot14** - The start coordinate value. ``` -------------------------------- ### split with simple patterns Source: https://docs.rs/fontcull-read-fonts/0.38.0/fontcull_read_fonts/tables/post/struct.PString.html Shows basic `split` usage with `char`, `&str`, and closure patterns. The examples cover empty strings, multiple separators, and patterns that match characters. ```rust let v: Vec<&str> = "Mary had a little lamb".split(' ').collect(); assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]); let v: Vec<&str> = "".split('X').collect(); assert_eq!(v, [""]); let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect(); assert_eq!(v, ["lion", "", "tiger", "leopard"]); let v: Vec<&str> = "lion::tiger::leopard".split("::").collect(); assert_eq!(v, ["lion", "tiger", "leopard"]); let v: Vec<&str> = "AABBCC".split("DD").collect(); assert_eq!(v, ["AABBCC"]); let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect(); assert_eq!(v, ["abc", "def", "ghi"]); let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect(); assert_eq!(v, ["lion", "tiger", "leopard"]); ``` -------------------------------- ### Engine impl block start Source: https://docs.rs/fontcull-skrifa/0.39.2/src/fontcull_skrifa/outline/glyf/hint/engine/definition.rs.html Start of an impl block for Engine<'a> (the remainder is not shown on this page). ```rust impl<'a> Engine<'a> { ``` -------------------------------- ### feat_example test Source: https://docs.rs/fontcull-read-fonts/0.38.0/src/fontcull_read_fonts/tables/feat.rs.html Verifies the parsing of feature fields and setting names from a constructed feat table buffer. ```rust #[test] fn feat_example() { let feat_data = build_feat_example(); let feat = Feat::read(feat_data.data().into()).unwrap(); let names = feat.names(); #[rustfmt::skip] let expected_name_fields = [ // (feature, n_settings, flags, name, exclusive, default_index) (0, 1, 0, NameId::new(260), false, 0), (1, 1, 0, NameId::new(256), false, 0), (3, 3, 0x8000, NameId::new(262), true, 0), (6, 2, 0xC001, NameId::new(258), true, 1), ]; let name_fields = names .iter() .map(|name| { ( name.feature(), name.n_settings(), name.feature_flags(), name.name_index(), name.is_exclusive(), name.default_setting_index(), ) }) .collect::>(); assert_eq!(name_fields, expected_name_fields); #[rustfmt::skip] let expected_setting_names: [&[(u16, NameId)]; 4] = [ &[(0, NameId::new(261))], &[(2, NameId::new(257))], &[(0, NameId::new(268)), (3, NameId::new(264)), (4, NameId::new(265))], &[(0, NameId::new(259)), (1, NameId::new(260))], ]; let setting_names = names .iter() .map(|name| { let settings = name.setting_table(feat.offset_data()).unwrap(); settings .settings() .iter() .map(|setting| (setting.setting(), setting.name_index())) .collect::>() }) .collect::>(); assert!(expected_setting_names.iter().eq(setting_names.iter())); } ``` -------------------------------- ### Subsetting GSUB/GPOS tables Source: https://docs.rs/fontcull-klippa/0.1.2/src/fontcull_klippa/gsubgpos.rs.html Configures a Plan with glyph mappings and sets, initializes a Serializer, and executes the subsetting process on a contextsubst_table. The resulting serialized data is then verified against an expected byte array. ```rust let mut plan = Plan { font_num_glyphs: 1398, ..Default::default() }; plan.glyph_map_gsub .insert(GlyphId::from(0_u32), GlyphId::from(0_u32)); plan.glyph_map_gsub .insert(GlyphId::from(31_u32), GlyphId::from(1_u32)); plan.glyph_map_gsub .insert(GlyphId::from(38_u32), GlyphId::from(2_u32)); plan.glyph_map_gsub .insert(GlyphId::from(218_u32), GlyphId::from(3_u32)); plan.glyph_map_gsub .insert(GlyphId::from(275_u32), GlyphId::from(4_u32)); plan.glyphset_gsub.insert(GlyphId::from(0_u32)); plan.glyphset_gsub.insert(GlyphId::from(31_u32)); plan.glyphset_gsub.insert(GlyphId::from(38_u32)); plan.glyphset_gsub.insert(GlyphId::from(218_u32)); plan.glyphset_gsub.insert(GlyphId::from(275_u32)); let mut lookup_map = FnvHashMap::default(); lookup_map.insert(1_u16, 1_u16); let mut s = Serializer::new(1024); assert_eq!(s.start_serialize(), Ok(())); let subset_state = SubsetState::default(); contextsubst_table .subset(&plan, &mut s, (&subset_state, &font, &lookup_map)) .unwrap(); assert!(!s.in_error()); s.end_serialize(); let subsetted_data = s.copy_bytes(); let expected_data: [u8; 50] = [ 0x00, 0x03, 0x00, 0x03, 0x00, 0x2c, 0x00, 0x26, 0x00, 0x1e, 0x00, 0x01, 0x00, 0x18, 0x00, 0x01, 0x00, 0x26, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x03, 0x00, 0x01, 0x00, 0x02, 0x00, 0x03, 0x00, 0x04, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x02, ]; assert_eq!(subsetted_data, expected_data); } } ``` -------------------------------- ### as_ref example Source: https://docs.rs/fontcull-write-fonts/0.44.3/fontcull_write_fonts/struct.NullableOffsetMarker.html Converts an Option to an Option<&String> to calculate length without consuming the original value. ```rust let text: Option = Some("Hello, world!".to_string()); // First, cast `Option` to `Option<&String>` with `as_ref`, // then consume *that* with `map`, leaving `text` on the stack. let text_length: Option = text.as_ref().map(|s| s.len()); println!("still can print text: {text:?}"); ``` -------------------------------- ### str::is_char_boundary examples Source: https://docs.rs/fontcull-read-fonts/0.38.0/fontcull_read_fonts/tables/post/struct.PString.html Examples demonstrating how to check if an index is a valid UTF-8 character boundary. ```rust let s = "Löwe 老虎 Léopard"; assert!(s.is_char_boundary(0)); // start of `老` assert!(s.is_char_boundary(6)); assert!(s.is_char_boundary(s.len())); // second byte of `ö` assert!(!s.is_char_boundary(2)); // third byte of `老` assert!(!s.is_char_boundary(8)); ``` -------------------------------- ### iter example Source: https://docs.rs/fontcull-write-fonts/0.44.3/fontcull_write_fonts/struct.NullableOffsetMarker.html Returns an iterator over the possibly contained value. The example shows iterating over Some and None options. ```rust let x = Some(4); assert_eq!(x.iter().next(), Some(&4)); let x: Option = None; assert_eq!(x.iter().next(), None); ``` -------------------------------- ### Generate example track table Source: https://docs.rs/fontcull-read-fonts/0.38.0/src/fontcull_read_fonts/tables/trak.rs.html Creates a sample track table buffer for testing purposes, following the structure defined in the Apple TrueType Reference Manual. ```rust /// From fn example_track_table() -> Vec { let mut buf = BeBuffer::new(); // header buf = buf.push(MajorMinor::VERSION_1_0); buf = buf.extend([0u16, 12, 0, 0]); // TrackData buf = buf.extend([3u16, 2]); buf = buf.push(44u32); // Three sorted TrackTableEntry records buf = buf.push(0xFFFF0000u32).extend([256u16, 52]); buf = buf.push(0x00000000u32).extend([258u16, 60]); buf = buf.push(0x00010000u32).extend([257u16, 56]); // Size subtable buf = buf.push(0x000C0000u32); buf = buf.push(0x00180000u32); // Per-size tracking data values buf = buf.extend([-15i16, -7, 50, 20, 0, 0]); buf.to_vec() } ``` -------------------------------- ### to_binary test setup for VariationStoreBuilder Source: https://docs.rs/fontcull-write-fonts/0.44.3/src/fontcull_write_fonts/tables/variations/ivs_builder.rs.html Test that builds a variation store with several deltas, dumps the resulting table to bytes, and creates a FontData instance from those bytes. This is the setup for verifying the binary serialization of the variation store. ```rust let [r1, r2, r3] = test_regions(); let mut builder = VariationStoreBuilder::new(2); builder.add_deltas(vec![(r1.clone(), 512), (r2, 1000), (r3.clone(), 265)]); builder.add_deltas(vec![(r1.clone(), -3), (r3.clone(), 20)]); builder.add_deltas(vec![(r1.clone(), -12), (r3.clone(), 7)]); builder.add_deltas(vec![(r1.clone(), -11), (r3.clone(), 8)]); builder.add_deltas(vec![(r1.clone(), -10), (r3.clone(), 9)]); let (table, _) = builder.build(); let bytes = crate::dump_table(&table).unwrap(); let data = FontData::new(&bytes); ```