kas_text/conv.rs
1// Licensed under the Apache License, Version 2.0 (the "License");
2// you may not use this file except in compliance with the License.
3// You may obtain a copy of the License in the LICENSE-APACHE file or at:
4// https://www.apache.org/licenses/LICENSE-2.0
5
6//! Type conversion utilities
7//!
8//! Many indices are represented as `u32` instead of `usize` by this library in
9//! order to save space (note that we do not expect `usize` smaller than `u32`
10//! and our text representations are not intended to scale anywhere close to
11//! `u32::MAX` bytes of text, so `u32` is always an appropriate index type).
12
13use easy_cast::Cast;
14
15/// Convert `usize` → `u32`
16///
17/// This is a "safer" wrapper around `as` ensuring (on debug builds) that the
18/// input value may be represented correctly by `u32`.
19#[inline]
20pub fn to_u32(x: usize) -> u32 {
21 x.cast()
22}
23
24/// Convert `u32` → `usize`
25///
26/// This is a "safer" wrapper around `as` ensuring that the operation is
27/// zero-extension.
28#[inline]
29pub fn to_usize(x: u32) -> usize {
30 x.cast()
31}
32
33/// Scale factor: pixels per font unit
34#[derive(Clone, Copy, Debug, Default, PartialEq)]
35pub struct DPU(pub f32);
36
37impl DPU {
38 #[cfg(feature = "rustybuzz")]
39 pub(crate) fn i32_to_px(self, x: i32) -> f32 {
40 x as f32 * self.0
41 }
42 pub(crate) fn i16_to_px(self, x: i16) -> f32 {
43 f32::from(x) * self.0
44 }
45 pub(crate) fn u16_to_px(self, x: u16) -> f32 {
46 f32::from(x) * self.0
47 }
48 pub(crate) fn to_line_metrics(self, metrics: ttf_parser::LineMetrics) -> LineMetrics {
49 LineMetrics {
50 position: self.i16_to_px(metrics.position),
51 thickness: self.i16_to_px(metrics.thickness),
52 }
53 }
54}
55
56/// Metrics for line marks
57#[derive(Clone, Copy, Debug, Default, PartialEq)]
58pub struct LineMetrics {
59 pub position: f32,
60 pub thickness: f32,
61}