summaryrefslogtreecommitdiff
path: root/src/font.rs
blob: e756f84ecde21d2e989e567ccadaa6b94e304b70 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
//! Font handling.

use std::collections::{hash_map::Entry, HashMap};
use std::fmt::{self, Debug, Display, Formatter};
use std::ops::Add;
use std::path::PathBuf;
use std::rc::Rc;

use decorum::N64;
use serde::{Deserialize, Serialize};

use crate::geom::Length;
use crate::loading::{FileHash, Loader};

/// A unique identifier for a loaded font face.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[derive(Serialize, Deserialize)]
pub struct FaceId(u32);

impl FaceId {
    /// Create a face id from the raw underlying value.
    ///
    /// This should only be called with values returned by
    /// [`into_raw`](Self::into_raw).
    pub const fn from_raw(v: u32) -> Self {
        Self(v)
    }

    /// Convert into the raw underlying value.
    pub const fn into_raw(self) -> u32 {
        self.0
    }
}

/// Storage for loaded and parsed font faces.
pub struct FontStore {
    loader: Rc<dyn Loader>,
    faces: Vec<Option<Face>>,
    families: HashMap<String, Vec<FaceId>>,
    buffers: HashMap<FileHash, Rc<Vec<u8>>>,
    on_load: Option<Box<dyn Fn(FaceId, &Face)>>,
}

impl FontStore {
    /// Create a new, empty font store.
    pub fn new(loader: Rc<dyn Loader>) -> Self {
        let mut faces = vec![];
        let mut families = HashMap::<String, Vec<FaceId>>::new();

        for (i, info) in loader.faces().iter().enumerate() {
            let id = FaceId(i as u32);
            faces.push(None);
            families
                .entry(info.family.to_lowercase())
                .and_modify(|vec| vec.push(id))
                .or_insert_with(|| vec![id]);
        }

        Self {
            loader,
            faces,
            families,
            buffers: HashMap::new(),
            on_load: None,
        }
    }

    /// Register a callback which is invoked each time a font face is loaded.
    pub fn on_load<F>(&mut self, f: F)
    where
        F: Fn(FaceId, &Face) + 'static,
    {
        self.on_load = Some(Box::new(f));
    }

    /// Query for and load the font face from the given `family` that most
    /// closely matches the given `variant`.
    pub fn select(&mut self, family: &str, variant: FontVariant) -> Option<FaceId> {
        // Check whether a family with this name exists.
        let ids = self.families.get(family)?;
        let infos = self.loader.faces();

        let mut best = None;
        let mut best_key = None;

        // Find the best matching variant of this font.
        for &id in ids {
            let current = infos[id.0 as usize].variant;

            // This is a perfect match, no need to search further.
            if current == variant {
                best = Some(id);
                break;
            }

            // If this is not a perfect match, we compute a key that we want to
            // minimize among all variants. This key prioritizes style, then
            // stretch distance and then weight distance.
            let key = (
                current.style != variant.style,
                current.stretch.distance(variant.stretch),
                current.weight.distance(variant.weight),
            );

            if best_key.map_or(true, |b| key < b) {
                best = Some(id);
                best_key = Some(key);
            }
        }

        let id = best?;

        // Load the face if it's not already loaded.
        let idx = id.0 as usize;
        let slot = &mut self.faces[idx];
        if slot.is_none() {
            let FaceInfo { ref path, index, .. } = infos[idx];

            // Check the buffer cache since multiple faces may
            // refer to the same data (font collection).
            let hash = self.loader.resolve(path).ok()?;
            let buffer = match self.buffers.entry(hash) {
                Entry::Occupied(entry) => entry.into_mut(),
                Entry::Vacant(entry) => {
                    let buffer = self.loader.load(path).ok()?;
                    entry.insert(Rc::new(buffer))
                }
            };

            let face = Face::new(Rc::clone(buffer), index)?;
            if let Some(callback) = &self.on_load {
                callback(id, &face);
            }

            *slot = Some(face);
        }

        Some(id)
    }

    /// Get a reference to a loaded face.
    ///
    /// This panics if no face with this id was loaded. This function should
    /// only be called with ids returned by this store's
    /// [`select()`](Self::select) method.
    #[track_caller]
    pub fn get(&self, id: FaceId) -> &Face {
        self.faces[id.0 as usize].as_ref().expect("font face was not loaded")
    }
}

/// A font face.
pub struct Face {
    buffer: Rc<Vec<u8>>,
    index: u32,
    ttf: rustybuzz::Face<'static>,
    units_per_em: f64,
    pub ascender: Em,
    pub cap_height: Em,
    pub x_height: Em,
    pub descender: Em,
    pub strikethrough: LineMetrics,
    pub underline: LineMetrics,
    pub overline: LineMetrics,
}

/// Metrics for a decorative line.
pub struct LineMetrics {
    pub strength: Em,
    pub position: Em,
}

impl Face {
    /// Parse a font face from a buffer and collection index.
    pub fn new(buffer: Rc<Vec<u8>>, index: u32) -> Option<Self> {
        // SAFETY:
        // - The slices's location is stable in memory:
        //   - We don't move the underlying vector
        //   - Nobody else can move it since we have a strong ref to the `Rc`.
        // - The internal static lifetime is not leaked because its rewritten
        //   to the self-lifetime in `ttf()`.
        let slice: &'static [u8] =
            unsafe { std::slice::from_raw_parts(buffer.as_ptr(), buffer.len()) };

        let ttf = rustybuzz::Face::from_slice(slice, index)?;

        let units_per_em = f64::from(ttf.units_per_em());
        let to_em = |units| Em::from_units(units, units_per_em);

        let ascender = to_em(ttf.typographic_ascender().unwrap_or(ttf.ascender()));
        let cap_height = ttf.capital_height().filter(|&h| h > 0).map_or(ascender, to_em);
        let x_height = ttf.x_height().filter(|&h| h > 0).map_or(ascender, to_em);
        let descender = to_em(ttf.typographic_descender().unwrap_or(ttf.descender()));
        let strikeout = ttf.strikeout_metrics();
        let underline = ttf.underline_metrics();

        let strikethrough = LineMetrics {
            strength: strikeout
                .or(underline)
                .map_or(Em::new(0.06), |s| to_em(s.thickness)),
            position: strikeout.map_or(Em::new(0.25), |s| to_em(s.position)),
        };

        let underline = LineMetrics {
            strength: underline
                .or(strikeout)
                .map_or(Em::new(0.06), |s| to_em(s.thickness)),
            position: underline.map_or(Em::new(-0.2), |s| to_em(s.position)),
        };

        let overline = LineMetrics {
            strength: underline.strength,
            position: cap_height + Em::new(0.1),
        };

        Some(Self {
            buffer,
            index,
            ttf,
            units_per_em,
            ascender,
            cap_height,
            x_height,
            descender,
            strikethrough,
            underline,
            overline,
        })
    }

    /// The underlying buffer.
    pub fn buffer(&self) -> &Rc<Vec<u8>> {
        &self.buffer
    }

    /// The collection index.
    pub fn index(&self) -> u32 {
        self.index
    }

    /// A reference to the underlying `ttf-parser` / `rustybuzz` face.
    pub fn ttf(&self) -> &rustybuzz::Face<'_> {
        // We can't implement Deref because that would leak the internal 'static
        // lifetime.
        &self.ttf
    }

    /// Get the number of units per em.
    pub fn units_per_em(&self) -> f64 {
        self.units_per_em
    }

    /// Convert from font units to an em length.
    pub fn to_em(&self, units: impl Into<f64>) -> Em {
        Em::from_units(units, self.units_per_em)
    }

    /// Look up a vertical metric.
    pub fn vertical_metric(&self, metric: VerticalFontMetric) -> Em {
        match metric {
            VerticalFontMetric::Ascender => self.ascender,
            VerticalFontMetric::CapHeight => self.cap_height,
            VerticalFontMetric::XHeight => self.x_height,
            VerticalFontMetric::Baseline => Em::zero(),
            VerticalFontMetric::Descender => self.descender,
        }
    }
}

/// A length in em units.
///
/// `1em` is the same as the font size.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, PartialOrd)]
pub struct Em(N64);

impl Em {
    /// The zero length.
    pub fn zero() -> Self {
        Self(N64::from(0.0))
    }

    /// Create an em length.
    pub fn new(em: f64) -> Self {
        Self(N64::from(em))
    }

    /// Convert units to an em length at the given units per em.
    pub fn from_units(units: impl Into<f64>, units_per_em: f64) -> Self {
        Self(N64::from(units.into() / units_per_em))
    }

    /// The number of em units.
    pub fn get(self) -> f64 {
        self.0.into()
    }

    /// Convert to a length at the given font size.
    pub fn to_length(self, font_size: Length) -> Length {
        self.get() * font_size
    }
}

impl Add for Em {
    type Output = Self;

    fn add(self, other: Self) -> Self {
        Self(self.0 + other.0)
    }
}

/// Identifies a vertical metric of a font.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum VerticalFontMetric {
    /// The distance from the baseline to the typographic ascender.
    ///
    /// Corresponds to the typographic ascender from the `OS/2` table if present
    /// and falls back to the ascender from the `hhea` table otherwise.
    Ascender,
    /// The approximate height of uppercase letters.
    CapHeight,
    /// The approximate height of non-ascending lowercase letters.
    XHeight,
    /// The baseline on which the letters rest.
    Baseline,
    /// The distance from the baseline to the typographic descender.
    ///
    /// Corresponds to the typographic descender from the `OS/2` table if
    /// present and falls back to the descender from the `hhea` table otherwise.
    Descender,
}

impl Display for VerticalFontMetric {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        f.pad(match self {
            Self::Ascender => "ascender",
            Self::CapHeight => "cap-height",
            Self::XHeight => "x-height",
            Self::Baseline => "baseline",
            Self::Descender => "descender",
        })
    }
}

/// A generic or named font family.
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum FontFamily {
    Serif,
    SansSerif,
    Monospace,
    Named(String),
}

impl Display for FontFamily {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        f.pad(match self {
            Self::Serif => "serif",
            Self::SansSerif => "sans-serif",
            Self::Monospace => "monospace",
            Self::Named(s) => s,
        })
    }
}

/// Properties of a single font face.
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct FaceInfo {
    /// The path to the font file.
    pub path: PathBuf,
    /// The collection index in the font file.
    pub index: u32,
    /// The typographic font family this face is part of.
    pub family: String,
    /// Properties that distinguish this face from other faces in the same
    /// family.
    #[serde(flatten)]
    pub variant: FontVariant,
}

/// Properties that distinguish a face from other faces in the same family.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash)]
#[derive(Serialize, Deserialize)]
pub struct FontVariant {
    /// The style of the face (normal / italic / oblique).
    pub style: FontStyle,
    /// How heavy the face is (100 - 900).
    pub weight: FontWeight,
    /// How condensed or expanded the face is (0.5 - 2.0).
    pub stretch: FontStretch,
}

impl FontVariant {
    /// Create a variant from its three components.
    pub fn new(style: FontStyle, weight: FontWeight, stretch: FontStretch) -> Self {
        Self { style, weight, stretch }
    }
}

/// The style of a font face.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum FontStyle {
    /// The default style.
    Normal,
    /// A cursive style.
    Italic,
    /// A slanted style.
    Oblique,
}

impl FontStyle {
    /// Create a font style from a lowercase name like `italic`.
    pub fn from_str(name: &str) -> Option<FontStyle> {
        Some(match name {
            "normal" => Self::Normal,
            "italic" => Self::Italic,
            "oblique" => Self::Oblique,
            _ => return None,
        })
    }

    /// The lowercase string representation of this style.
    pub fn to_str(self) -> &'static str {
        match self {
            Self::Normal => "normal",
            Self::Italic => "italic",
            Self::Oblique => "oblique",
        }
    }
}

impl Default for FontStyle {
    fn default() -> Self {
        Self::Normal
    }
}

impl Display for FontStyle {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        f.pad(self.to_str())
    }
}

/// The weight of a font face.
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[derive(Serialize, Deserialize)]
#[serde(transparent)]
pub struct FontWeight(u16);

impl FontWeight {
    /// Thin weight (100).
    pub const THIN: Self = Self(100);

    /// Extra light weight (200).
    pub const EXTRALIGHT: Self = Self(200);

    /// Light weight (300).
    pub const LIGHT: Self = Self(300);

    /// Regular weight (400).
    pub const REGULAR: Self = Self(400);

    /// Medium weight (500).
    pub const MEDIUM: Self = Self(500);

    /// Semibold weight (600).
    pub const SEMIBOLD: Self = Self(600);

    /// Bold weight (700).
    pub const BOLD: Self = Self(700);

    /// Extrabold weight (800).
    pub const EXTRABOLD: Self = Self(800);

    /// Black weight (900).
    pub const BLACK: Self = Self(900);

    /// Create a font weight from a number between 100 and 900, clamping it if
    /// necessary.
    pub fn from_number(weight: u16) -> Self {
        Self(weight.max(100).min(900))
    }

    /// Create a font weight from a lowercase name like `light`.
    pub fn from_str(name: &str) -> Option<Self> {
        Some(match name {
            "thin" => Self::THIN,
            "extralight" => Self::EXTRALIGHT,
            "light" => Self::LIGHT,
            "regular" => Self::REGULAR,
            "medium" => Self::MEDIUM,
            "semibold" => Self::SEMIBOLD,
            "bold" => Self::BOLD,
            "extrabold" => Self::EXTRABOLD,
            "black" => Self::BLACK,
            _ => return None,
        })
    }

    /// The number between 100 and 900.
    pub fn to_number(self) -> u16 {
        self.0
    }

    /// The lowercase string representation of this weight if it is divisible by
    /// 100.
    pub fn to_str(self) -> Option<&'static str> {
        Some(match self {
            Self::THIN => "thin",
            Self::EXTRALIGHT => "extralight",
            Self::LIGHT => "light",
            Self::REGULAR => "regular",
            Self::MEDIUM => "medium",
            Self::SEMIBOLD => "semibold",
            Self::BOLD => "bold",
            Self::EXTRABOLD => "extrabold",
            Self::BLACK => "black",
            _ => return None,
        })
    }

    /// Add (or remove) weight, saturating at the boundaries of 100 and 900.
    pub fn thicken(self, delta: i16) -> Self {
        Self((self.0 as i16).saturating_add(delta).max(100).min(900) as u16)
    }

    /// The absolute number distance between this and another font weight.
    pub fn distance(self, other: Self) -> u16 {
        (self.0 as i16 - other.0 as i16).abs() as u16
    }
}

impl Default for FontWeight {
    fn default() -> Self {
        Self::REGULAR
    }
}

impl Display for FontWeight {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        match self.to_str() {
            Some(name) => f.pad(name),
            None => write!(f, "{}", self.0),
        }
    }
}

impl Debug for FontWeight {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.pad(match *self {
            Self::THIN => "Thin",
            Self::EXTRALIGHT => "Extralight",
            Self::LIGHT => "Light",
            Self::REGULAR => "Regular",
            Self::MEDIUM => "Medium",
            Self::SEMIBOLD => "Semibold",
            Self::BOLD => "Bold",
            Self::EXTRABOLD => "Extrabold",
            Self::BLACK => "Black",
            _ => return write!(f, "{}", self.0),
        })
    }
}

/// The width of a font face.
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[derive(Serialize, Deserialize)]
#[serde(transparent)]
pub struct FontStretch(u16);

impl FontStretch {
    /// Ultra-condensed stretch (50%).
    pub const ULTRA_CONDENSED: Self = Self(500);

    /// Extra-condensed stretch weight (62.5%).
    pub const EXTRA_CONDENSED: Self = Self(625);

    /// Condensed stretch (75%).
    pub const CONDENSED: Self = Self(750);

    /// Semi-condensed stretch (87.5%).
    pub const SEMI_CONDENSED: Self = Self(875);

    /// Normal stretch (100%).
    pub const NORMAL: Self = Self(1000);

    /// Semi-expanded stretch (112.5%).
    pub const SEMI_EXPANDED: Self = Self(1125);

    /// Expanded stretch (125%).
    pub const EXPANDED: Self = Self(1250);

    /// Extra-expanded stretch (150%).
    pub const EXTRA_EXPANDED: Self = Self(1500);

    /// Ultra-expanded stretch (200%).
    pub const ULTRA_EXPANDED: Self = Self(2000);

    /// Create a font stretch from a ratio between 0.5 and 2.0, clamping it if
    /// necessary.
    pub fn from_ratio(ratio: f32) -> Self {
        Self((ratio.max(0.5).min(2.0) * 1000.0) as u16)
    }

    /// Create a font stretch from an OpenType-style number between 1 and 9,
    /// clamping it if necessary.
    pub fn from_number(stretch: u16) -> Self {
        match stretch {
            0 | 1 => Self::ULTRA_CONDENSED,
            2 => Self::EXTRA_CONDENSED,
            3 => Self::CONDENSED,
            4 => Self::SEMI_CONDENSED,
            5 => Self::NORMAL,
            6 => Self::SEMI_EXPANDED,
            7 => Self::EXPANDED,
            8 => Self::EXTRA_EXPANDED,
            _ => Self::ULTRA_EXPANDED,
        }
    }

    /// Create a font stretch from a lowercase name like `extra-expanded`.
    pub fn from_str(name: &str) -> Option<Self> {
        Some(match name {
            "ultra-condensed" => Self::ULTRA_CONDENSED,
            "extra-condensed" => Self::EXTRA_CONDENSED,
            "condensed" => Self::CONDENSED,
            "semi-condensed" => Self::SEMI_CONDENSED,
            "normal" => Self::NORMAL,
            "semi-expanded" => Self::SEMI_EXPANDED,
            "expanded" => Self::EXPANDED,
            "extra-expanded" => Self::EXTRA_EXPANDED,
            "ultra-expanded" => Self::ULTRA_EXPANDED,
            _ => return None,
        })
    }

    /// The ratio between 0.5 and 2.0 corresponding to this stretch.
    pub fn to_ratio(self) -> f32 {
        self.0 as f32 / 1000.0
    }

    /// The lowercase string representation of this stretch is one of the named
    /// ones.
    pub fn to_str(self) -> Option<&'static str> {
        Some(match self {
            Self::ULTRA_CONDENSED => "ultra-condensed",
            Self::EXTRA_CONDENSED => "extra-condensed",
            Self::CONDENSED => "condensed",
            Self::SEMI_CONDENSED => "semi-condensed",
            Self::NORMAL => "normal",
            Self::SEMI_EXPANDED => "semi-expanded",
            Self::EXPANDED => "expanded",
            Self::EXTRA_EXPANDED => "extra-expanded",
            Self::ULTRA_EXPANDED => "ultra-expanded",
            _ => return None,
        })
    }

    /// The absolute ratio distance between this and another font stretch.
    pub fn distance(self, other: Self) -> f32 {
        (self.to_ratio() - other.to_ratio()).abs()
    }
}

impl Default for FontStretch {
    fn default() -> Self {
        Self::NORMAL
    }
}

impl Display for FontStretch {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        match self.to_str() {
            Some(name) => f.pad(name),
            None => write!(f, "{}", self.to_ratio()),
        }
    }
}

impl Debug for FontStretch {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        f.pad(match *self {
            s if s == Self::ULTRA_CONDENSED => "UltraCondensed",
            s if s == Self::EXTRA_CONDENSED => "ExtraCondensed",
            s if s == Self::CONDENSED => "Condensed",
            s if s == Self::SEMI_CONDENSED => "SemiCondensed",
            s if s == Self::NORMAL => "Normal",
            s if s == Self::SEMI_EXPANDED => "SemiExpanded",
            s if s == Self::EXPANDED => "Expanded",
            s if s == Self::EXTRA_EXPANDED => "ExtraExpanded",
            s if s == Self::ULTRA_EXPANDED => "UltraExpanded",
            _ => return write!(f, "{}", self.0),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_font_weight_distance() {
        let d = |a, b| FontWeight(a).distance(FontWeight(b));
        assert_eq!(d(500, 200), 300);
        assert_eq!(d(500, 500), 0);
        assert_eq!(d(500, 900), 400);
        assert_eq!(d(10, 100), 90);
    }
}