Factor out typst-utils crate (#4125)

This commit is contained in:
Laurenz 2024-05-13 17:25:43 +02:00 committed by GitHub
parent 7b656b3deb
commit 95cd6adf24
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
92 changed files with 193 additions and 162 deletions

11
Cargo.lock generated
View File

@ -2568,6 +2568,7 @@ dependencies = [
"typst-macros",
"typst-syntax",
"typst-timing",
"typst-utils",
"unicode-bidi",
"unicode-math-class",
"unicode-script",
@ -2803,6 +2804,16 @@ dependencies = [
"typst-syntax",
]
[[package]]
name = "typst-utils"
version = "0.11.0"
dependencies = [
"once_cell",
"portable-atomic",
"rayon",
"siphasher 1.0.0",
]
[[package]]
name = "unic-langid"
version = "0.9.4"

View File

@ -25,6 +25,7 @@ typst-render = { path = "crates/typst-render", version = "0.11.0" }
typst-svg = { path = "crates/typst-svg", version = "0.11.0" }
typst-syntax = { path = "crates/typst-syntax", version = "0.11.0" }
typst-timing = { path = "crates/typst-timing", version = "0.11.0" }
typst-utils = { path = "crates/typst-utils", version = "0.11.0" }
typst-assets = "0.11.0"
typst-dev-assets = { git = "https://github.com/typst/typst-dev-assets", rev = "ee8ae61cca138dc92f9d818fc7f2fc046d0148c5" }
az = "1.2"

View File

@ -380,7 +380,7 @@ impl ExportCache {
/// Returns true if the entry is cached and appends the new hash to the
/// cache (for the next compilation).
pub fn is_cached(&self, i: usize, frame: &Frame) -> bool {
let hash = typst::util::hash128(frame);
let hash = typst::utils::hash128(frame);
let mut cache = self.cache.upgradable_read();
if i >= cache.len() {

View File

@ -325,7 +325,7 @@ impl<T: Clone> SlotCell<T> {
// Read and hash the file.
let result = timed!("loading file", load());
let fingerprint = timed!("hashing file", typst::util::hash128(&result));
let fingerprint = timed!("hashing file", typst::utils::hash128(&result));
// If the file contents didn't change, yield the old processed data.
if mem::replace(&mut self.fingerprint, fingerprint) == fingerprint {

View File

@ -110,7 +110,7 @@ pub fn analyze_labels(document: &Document) -> (Vec<(Label, Option<EcoString>)>,
// Bibliography keys.
for (key, detail) in BibliographyElem::keys(document.introspector.track()) {
output.push((Label::new(&key), detail));
output.push((Label::new(key.as_str()), detail));
}
(output, split)

View File

@ -1229,7 +1229,7 @@ impl<'a> CompletionContext<'a> {
/// Add completions for a castable.
fn cast_completions(&mut self, cast: &'a CastInfo) {
// Prevent duplicate completions from appearing.
if !self.seen_casts.insert(typst::util::hash128(cast)) {
if !self.seen_casts.insert(typst::utils::hash128(cast)) {
return;
}

View File

@ -7,7 +7,7 @@ use typst::foundations::{repr, Capturer, CastInfo, Repr, Value};
use typst::layout::Length;
use typst::model::Document;
use typst::syntax::{ast, LinkedNode, Side, Source, SyntaxKind};
use typst::util::{round_2, Numeric};
use typst::utils::{round_2, Numeric};
use typst::World;
use crate::analyze::{analyze_expr, analyze_labels};

View File

@ -799,7 +799,7 @@ fn create_capable_impl(element: &Elem) -> TokenStream {
// Safety: The vtable function doesn't require initialized
// data, so it's fine to use a dangling pointer.
return Some(unsafe {
::typst::util::fat::vtable(dangling as *const dyn #capability)
::typst::utils::fat::vtable(dangling as *const dyn #capability)
});
}
}

View File

@ -9,7 +9,7 @@ use pdf_writer::{Filter, Finish, Name, Rect, Str};
use ttf_parser::{name_id, GlyphId, Tag};
use typst::layout::{Abs, Em, Ratio, Transform};
use typst::text::Font;
use typst::util::SliceExt;
use typst::utils::SliceExt;
use unicode_properties::{GeneralCategory, UnicodeGeneralCategory};
use crate::page::{write_frame, PageContext};
@ -320,7 +320,7 @@ fn subset_font(font: &Font, glyphs: &[u16]) -> Arc<Vec<u8>> {
fn subset_tag<T: Hash>(glyphs: &T) -> EcoString {
const LEN: usize = 6;
const BASE: u128 = 26;
let mut hash = typst::util::hash128(&glyphs);
let mut hash = typst::utils::hash128(&glyphs);
let mut letter = [b'A'; LEN];
for l in letter.iter_mut() {
*l = b'A' + (hash % BASE) as u8;

View File

@ -6,7 +6,7 @@ use pdf_writer::types::{ColorSpaceOperand, FunctionShadingType};
use pdf_writer::writers::StreamShadingType;
use pdf_writer::{Filter, Finish, Name, Ref};
use typst::layout::{Abs, Angle, Point, Quadrant, Ratio, Transform};
use typst::util::Numeric;
use typst::utils::Numeric;
use typst::visualize::{
Color, ColorSpace, Gradient, RatioOrAngle, RelativeTo, WeightedColor,
};

View File

@ -3,7 +3,7 @@ use std::io::Cursor;
use image::{DynamicImage, GenericImageView, Rgba};
use pdf_writer::{Chunk, Filter, Finish, Ref};
use typst::util::Deferred;
use typst::utils::Deferred;
use typst::visualize::{
ColorSpace, Image, ImageKind, RasterFormat, RasterImage, SvgImage,
};

View File

@ -25,7 +25,7 @@ use typst::layout::{Abs, Dir, Em, Frame, PageRanges, Transform};
use typst::model::{Document, HeadingElem};
use typst::text::color::frame_for_glyph;
use typst::text::{Font, Lang};
use typst::util::Deferred;
use typst::utils::Deferred;
use typst::visualize::Image;
use xmp_writer::{DateTime, LangId, RenditionClass, Timezone, XmpWriter};
@ -394,7 +394,7 @@ fn deflate_deferred(content: Vec<u8>) -> Deferred<Vec<u8>> {
/// Create a base64-encoded hash of the value.
fn hash_base64<T: Hash>(value: &T) -> String {
base64::engine::general_purpose::STANDARD
.encode(typst::util::hash128(value).to_be_bytes())
.encode(typst::utils::hash128(value).to_be_bytes())
}
/// Converts a datetime to a pdf-writer date.

View File

@ -19,7 +19,7 @@ use typst::layout::{
use typst::model::{Destination, Numbering};
use typst::text::color::is_color_glyph;
use typst::text::{Case, Font, TextItem, TextItemView};
use typst::util::{Deferred, Numeric, SliceExt};
use typst::utils::{Deferred, Numeric, SliceExt};
use typst::visualize::{
FixedStroke, Geometry, Image, LineCap, LineJoin, Paint, Path, PathItem, Shape,
};

View File

@ -2,7 +2,7 @@ use ecow::eco_format;
use pdf_writer::types::{ColorSpaceOperand, PaintType, TilingType};
use pdf_writer::{Filter, Finish, Name, Rect};
use typst::layout::{Abs, Ratio, Transform};
use typst::util::Numeric;
use typst::utils::Numeric;
use typst::visualize::{Pattern, RelativeTo};
use crate::color::PaintEncode;

View File

@ -14,7 +14,7 @@ use typst::layout::{
Abs, Frame, FrameItem, FrameKind, GroupItem, Point, Ratio, Size, Transform,
};
use typst::model::Document;
use typst::util::hash128;
use typst::utils::hash128;
use typst::visualize::{Gradient, Pattern};
use xmlwriter::XmlWriter;

View File

@ -4,7 +4,7 @@ use ecow::{eco_format, EcoString};
use ttf_parser::OutlineBuilder;
use typst::foundations::Repr;
use typst::layout::{Angle, Axes, Frame, Quadrant, Ratio, Size, Transform};
use typst::util::hash128;
use typst::utils::hash128;
use typst::visualize::{Color, Gradient, Paint, Pattern, RatioOrAngle};
use xmlwriter::XmlWriter;

View File

@ -5,7 +5,7 @@ use ecow::EcoString;
use ttf_parser::GlyphId;
use typst::layout::{Abs, Point, Ratio, Size, Transform};
use typst::text::{Font, TextItem};
use typst::util::hash128;
use typst::utils::hash128;
use typst::visualize::{Image, Paint, RasterFormat, RelativeTo};
use crate::{SVGRenderer, State, SvgMatrix, SvgPathBuilder};

View File

@ -0,0 +1,22 @@
[package]
name = "typst-utils"
description = "Utilities for Typst."
version = { workspace = true }
rust-version = { workspace = true }
authors = { workspace = true }
edition = { workspace = true }
homepage = { workspace = true }
repository = { workspace = true }
license = { workspace = true }
categories = { workspace = true }
keywords = { workspace = true }
readme = { workspace = true }
[dependencies]
once_cell = { workspace = true }
siphasher = { workspace = true }
portable-atomic = { workspace = true }
rayon = { workspace = true }
[lints]
workspace = true

View File

@ -44,7 +44,7 @@ impl<T: Default> Default for LazyHash<T> {
}
impl<T> LazyHash<T> {
/// Wrap an item without pre-computed hash.
/// Wraps an item without pre-computed hash.
#[inline]
pub fn new(value: T) -> Self {
Self { hash: AtomicU128::new(0), value }
@ -55,35 +55,30 @@ impl<T> LazyHash<T> {
/// **Important:** The hash must be correct for the value. This cannot be
/// enforced at compile time, so use with caution.
#[inline]
pub fn with_hash(value: T, hash: u128) -> Self {
Self { hash: AtomicU128::new(hash), value }
pub fn reuse<U: ?Sized>(value: T, existing: &LazyHash<U>) -> Self {
LazyHash { hash: AtomicU128::new(existing.load_hash()), value }
}
/// Return the wrapped value.
/// Returns the wrapped value.
#[inline]
pub fn into_inner(self) -> T {
self.value
}
}
impl<T: Hash + ?Sized + 'static> LazyHash<T> {
impl<T: ?Sized> LazyHash<T> {
/// Get the hash, returns zero if not computed yet.
#[inline]
pub fn hash(&self) -> u128 {
fn load_hash(&self) -> u128 {
self.hash.load(Ordering::SeqCst)
}
}
/// Reset the hash to zero.
#[inline]
fn reset_hash(&mut self) {
// Because we have a mutable reference, we can skip the atomic
*self.hash.get_mut() = 0;
}
impl<T: Hash + ?Sized + 'static> LazyHash<T> {
/// Get the hash or compute it if not set yet.
#[inline]
fn get_or_set_hash(&self) -> u128 {
let hash = self.hash();
fn load_or_compute_hash(&self) -> u128 {
let hash = self.load_hash();
if hash == 0 {
let hashed = hash_item(&self.value);
self.hash.store(hashed, Ordering::SeqCst);
@ -92,6 +87,13 @@ impl<T: Hash + ?Sized + 'static> LazyHash<T> {
hash
}
}
/// Reset the hash to zero.
#[inline]
fn reset_hash(&mut self) {
// Because we have a mutable reference, we can skip the atomic
*self.hash.get_mut() = 0;
}
}
/// Hash the item.
@ -108,7 +110,7 @@ fn hash_item<T: Hash + ?Sized + 'static>(item: &T) -> u128 {
impl<T: Hash + ?Sized + 'static> Hash for LazyHash<T> {
#[inline]
fn hash<H: Hasher>(&self, state: &mut H) {
state.write_u128(self.get_or_set_hash());
state.write_u128(self.load_or_compute_hash());
}
}
@ -124,7 +126,7 @@ impl<T: Hash + ?Sized + 'static> Eq for LazyHash<T> {}
impl<T: Hash + ?Sized + 'static> PartialEq for LazyHash<T> {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.get_or_set_hash() == other.get_or_set_hash()
self.load_or_compute_hash() == other.load_or_compute_hash()
}
}
@ -148,7 +150,7 @@ impl<T: Hash + ?Sized + 'static> DerefMut for LazyHash<T> {
impl<T: Hash + Clone + 'static> Clone for LazyHash<T> {
fn clone(&self) -> Self {
Self {
hash: AtomicU128::new(self.hash()),
hash: AtomicU128::new(self.load_hash()),
value: self.value.clone(),
}
}

View File

@ -1,4 +1,4 @@
//! Utilities.
//! Utilities for Typst.
pub mod fat;

View File

@ -1,4 +1,5 @@
/// Implement the `Sub` trait based on existing `Neg` and `Add` impls.
#[macro_export]
macro_rules! sub_impl {
($a:ident - $b:ident -> $c:ident) => {
impl std::ops::Sub<$b> for $a {
@ -12,6 +13,7 @@ macro_rules! sub_impl {
}
/// Implement an assign trait based on an existing non-assign trait.
#[macro_export]
macro_rules! assign_impl {
($a:ident += $b:ident) => {
impl std::ops::AddAssign<$b> for $a {

View File

@ -3,11 +3,8 @@ use std::collections::HashMap;
use std::fmt::{self, Debug, Formatter};
use std::sync::RwLock;
use ecow::EcoString;
use once_cell::sync::Lazy;
use crate::foundations::cast;
/// The global string interner.
static INTERNER: Lazy<RwLock<Interner>> =
Lazy::new(|| RwLock::new(Interner { to_id: HashMap::new(), from_id: Vec::new() }));
@ -52,12 +49,6 @@ impl PicoStr {
}
}
cast! {
PicoStr,
self => self.resolve().into_value(),
v: EcoString => Self::new(&v),
}
impl Debug for PicoStr {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
self.resolve().fmt(f)
@ -87,9 +78,3 @@ impl From<&str> for PicoStr {
Self::new(value)
}
}
impl From<&EcoString> for PicoStr {
fn from(value: &EcoString) -> Self {
Self::new(value)
}
}

View File

@ -6,7 +6,7 @@ use std::ops::{
Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Rem, RemAssign, Sub, SubAssign,
};
use crate::util::Numeric;
use crate::Numeric;
/// A 64-bit float that implements `Eq`, `Ord` and `Hash`.
///

View File

@ -17,6 +17,7 @@ typst-assets = { workspace = true }
typst-macros = { workspace = true }
typst-syntax = { workspace = true }
typst-timing = { workspace = true }
typst-utils = { workspace = true }
az = { workspace = true }
bitflags = { workspace = true }
chinese-number = { workspace = true }

View File

@ -14,7 +14,7 @@ use crate::symbols::Symbol;
use crate::syntax::ast::{self, AstNode};
use crate::syntax::{Span, Spanned, SyntaxNode};
use crate::text::TextElem;
use crate::util::LazyHash;
use crate::utils::LazyHash;
use crate::World;
impl Eval for ast::FuncCall<'_> {

View File

@ -10,7 +10,7 @@ use crate::foundations::{format_str, Datetime, IntoValue, Regex, Repr, Value};
use crate::layout::{Alignment, Length, Rel};
use crate::syntax::ast::{self, AstNode};
use crate::text::TextElem;
use crate::util::Numeric;
use crate::utils::Numeric;
use crate::visualize::Stroke;
impl Eval for ast::Unary<'_> {

View File

@ -5,7 +5,7 @@ use ecow::EcoVec;
use crate::diag::SourceDiagnostic;
use crate::foundations::{Styles, Value};
use crate::syntax::{FileId, Span};
use crate::util::hash128;
use crate::utils::hash128;
/// Traces warnings and which values existed for an expression at a span.
#[derive(Default, Clone)]

View File

@ -8,7 +8,7 @@ use serde::{Serialize, Serializer};
use crate::diag::{bail, StrResult};
use crate::foundations::{cast, func, scope, ty, Array, Reflect, Repr, Str, Value};
use crate::util::LazyHash;
use crate::utils::LazyHash;
/// A sequence of bytes.
///

View File

@ -24,7 +24,7 @@ use crate::model::{Destination, EmphElem, StrongElem};
use crate::realize::{Behave, Behaviour};
use crate::syntax::Span;
use crate::text::UnderlineElem;
use crate::util::{fat, BitSet, LazyHash};
use crate::utils::{fat, BitSet, LazyHash};
/// A piece of document content.
///
@ -711,7 +711,7 @@ impl<T: NativeElement> Bounds for T {
label: inner.label,
location: inner.location,
lifecycle: inner.lifecycle.clone(),
elem: LazyHash::with_hash(self.clone(), inner.elem.hash()),
elem: LazyHash::reuse(self.clone(), &inner.elem),
}),
span,
}

View File

@ -12,7 +12,7 @@ use crate::foundations::{
array, cast, func, repr, scope, ty, Array, Module, Repr, Str, Value,
};
use crate::syntax::is_ident;
use crate::util::ArcExt;
use crate::utils::ArcExt;
/// Create a new [`Dict`] from key-value pairs.
#[macro_export]

View File

@ -14,7 +14,7 @@ use crate::foundations::{
Styles, Value,
};
use crate::text::{Lang, Region};
use crate::util::Static;
use crate::utils::Static;
#[doc(inline)]
pub use typst_macros::elem;

View File

@ -12,7 +12,7 @@ use crate::foundations::{
Selector, Type, Value,
};
use crate::syntax::{ast, Span, SyntaxNode};
use crate::util::{LazyHash, Static};
use crate::utils::{LazyHash, Static};
#[doc(inline)]
pub use typst_macros::func;

View File

@ -1,7 +1,7 @@
use ecow::{eco_format, EcoString};
use crate::foundations::{func, scope, ty, Repr};
use crate::util::PicoStr;
use crate::utils::PicoStr;
/// A label for an element.
///

View File

@ -9,7 +9,7 @@ use crate::foundations::{
Element, Func, IntoValue, Module, NativeElement, NativeFunc, NativeFuncData,
NativeType, Type, Value,
};
use crate::util::Static;
use crate::utils::Static;
use crate::Library;
#[doc(inline)]

View File

@ -16,6 +16,7 @@ use crate::foundations::{
};
use crate::layout::Alignment;
use crate::syntax::{Span, Spanned};
use crate::utils::PicoStr;
/// Create a new [`Str`] from a format string.
#[macro_export]
@ -750,6 +751,12 @@ cast! {
v: Str => v.into(),
}
cast! {
PicoStr,
self => Value::Str(self.resolve().into()),
v: Str => v.as_str().into(),
}
cast! {
String,
self => Value::Str(self.into()),

View File

@ -16,7 +16,7 @@ use crate::foundations::{
use crate::introspection::Locatable;
use crate::syntax::Span;
use crate::text::{FontFamily, FontList, TextElem};
use crate::util::LazyHash;
use crate::utils::LazyHash;
/// Provides access to active styles.
///

View File

@ -6,7 +6,7 @@ use once_cell::sync::Lazy;
use crate::diag::StrResult;
use crate::foundations::{cast, func, Func, NativeFuncData, Repr, Scope, Value};
use crate::util::Static;
use crate::utils::Static;
#[rustfmt::skip]
#[doc(inline)]

View File

@ -20,7 +20,7 @@ use crate::layout::{Abs, Angle, Em, Fr, Length, Ratio, Rel};
use crate::symbols::Symbol;
use crate::syntax::{ast, Span};
use crate::text::{RawContent, RawElem, TextElem};
use crate::util::ArcExt;
use crate::utils::ArcExt;
use crate::visualize::{Color, Gradient, Pattern};
/// A computational value.

View File

@ -18,7 +18,7 @@ use crate::layout::{Frame, FrameItem, PageElem};
use crate::math::EquationElem;
use crate::model::{FigureElem, HeadingElem, Numbering, NumberingPattern};
use crate::syntax::Span;
use crate::util::NonZeroExt;
use crate::utils::NonZeroExt;
use crate::World;
/// Counts through pages, elements, and more.

View File

@ -13,7 +13,7 @@ use crate::foundations::{Content, Label, Repr, Selector};
use crate::introspection::{Location, Meta};
use crate::layout::{Frame, FrameItem, Page, Point, Position, Transform};
use crate::model::Numbering;
use crate::util::NonZeroExt;
use crate::utils::NonZeroExt;
/// Can be queried for elements and their positions.
#[derive(Clone)]
@ -108,7 +108,7 @@ impl Introspector {
impl Introspector {
/// Query for all matching elements.
pub fn query(&self, selector: &Selector) -> EcoVec<Content> {
let hash = crate::util::hash128(selector);
let hash = crate::utils::hash128(selector);
if let Some(output) = self.queries.get(hash) {
return output;
}

View File

@ -38,7 +38,7 @@ impl Location {
/// locations for reference entries from the bibliography's location.
pub fn variant(self, n: usize) -> Self {
Self {
hash: crate::util::hash128(&(self.hash, n)),
hash: crate::utils::hash128(&(self.hash, n)),
..self
}
}

View File

@ -5,7 +5,7 @@ use std::ops::{Add, Div, Mul, Neg, Rem};
use ecow::EcoString;
use crate::foundations::{cast, repr, Fold, Repr, Value};
use crate::util::{Numeric, Scalar};
use crate::utils::{Numeric, Scalar};
/// An absolute length.
#[derive(Default, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
@ -162,7 +162,7 @@ impl Add for Abs {
}
}
sub_impl!(Abs - Abs -> Abs);
typst_utils::sub_impl!(Abs - Abs -> Abs);
impl Mul<f64> for Abs {
type Output = Self;
@ -196,10 +196,10 @@ impl Div for Abs {
}
}
assign_impl!(Abs += Abs);
assign_impl!(Abs -= Abs);
assign_impl!(Abs *= f64);
assign_impl!(Abs /= f64);
typst_utils::assign_impl!(Abs += Abs);
typst_utils::assign_impl!(Abs -= Abs);
typst_utils::assign_impl!(Abs *= f64);
typst_utils::assign_impl!(Abs /= f64);
impl Rem for Abs {
type Output = Self;

View File

@ -6,7 +6,7 @@ use std::ops::{Add, Div, Mul, Neg};
use ecow::EcoString;
use crate::foundations::{func, repr, scope, ty, Repr};
use crate::util::{Numeric, Scalar};
use crate::utils::{Numeric, Scalar};
/// An angle describing a rotation.
///
@ -155,7 +155,7 @@ impl Add for Angle {
}
}
sub_impl!(Angle - Angle -> Angle);
typst_utils::sub_impl!(Angle - Angle -> Angle);
impl Mul<f64> for Angle {
type Output = Self;
@ -189,10 +189,10 @@ impl Div<f64> for Angle {
}
}
assign_impl!(Angle += Angle);
assign_impl!(Angle -= Angle);
assign_impl!(Angle *= f64);
assign_impl!(Angle /= f64);
typst_utils::assign_impl!(Angle += Angle);
typst_utils::assign_impl!(Angle -= Angle);
typst_utils::assign_impl!(Angle *= f64);
typst_utils::assign_impl!(Angle /= f64);
impl Sum for Angle {
fn sum<I: Iterator<Item = Angle>>(iter: I) -> Self {

View File

@ -5,7 +5,7 @@ use std::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, Deref, Not};
use crate::diag::bail;
use crate::foundations::{array, cast, Array, Resolve, Smart, StyleChain};
use crate::layout::{Abs, Dir, Length, Ratio, Rel};
use crate::util::Get;
use crate::utils::Get;
/// A container with a horizontal and vertical component.
#[derive(Default, Copy, Clone, Eq, PartialEq, Hash)]

View File

@ -9,7 +9,7 @@ use crate::layout::{
};
use crate::realize::{Behave, Behaviour};
use crate::text::TextElem;
use crate::util::Numeric;
use crate::utils::Numeric;
/// Separates a region into multiple equally sized columns.
///

View File

@ -7,7 +7,7 @@ use crate::layout::{
Abs, Axes, Corners, Em, Fr, Fragment, Frame, FrameKind, LayoutMultiple, Length,
Ratio, Regions, Rel, Sides, Size, Spacing, VElem,
};
use crate::util::Numeric;
use crate::utils::Numeric;
use crate::visualize::{clip_rect, Paint, Stroke};
/// An inline-level container that sizes content.

View File

@ -6,7 +6,7 @@ use crate::foundations::{
StyleChain, Value,
};
use crate::layout::Side;
use crate::util::Get;
use crate::utils::Get;
/// A container with components for the four corners of a rectangle.
#[derive(Default, Copy, Clone, Eq, PartialEq, Hash)]

View File

@ -7,7 +7,7 @@ use ecow::EcoString;
use crate::foundations::{cast, repr, Repr, Resolve, StyleChain, Value};
use crate::layout::Abs;
use crate::text::TextElem;
use crate::util::{Numeric, Scalar};
use crate::utils::{Numeric, Scalar};
/// A length that is relative to the font size.
///
@ -105,7 +105,7 @@ impl Add for Em {
}
}
sub_impl!(Em - Em -> Em);
typst_utils::sub_impl!(Em - Em -> Em);
impl Mul<f64> for Em {
type Output = Self;
@ -139,10 +139,10 @@ impl Div for Em {
}
}
assign_impl!(Em += Em);
assign_impl!(Em -= Em);
assign_impl!(Em *= f64);
assign_impl!(Em /= f64);
typst_utils::assign_impl!(Em += Em);
typst_utils::assign_impl!(Em -= Em);
typst_utils::assign_impl!(Em *= f64);
typst_utils::assign_impl!(Em /= f64);
impl Sum for Em {
fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {

View File

@ -18,7 +18,7 @@ use crate::layout::{
Rel, Size, Spacing, VElem,
};
use crate::model::{FootnoteElem, FootnoteEntry, ParElem};
use crate::util::Numeric;
use crate::utils::Numeric;
/// Arranges spacing, paragraphs and block-level elements into a flow.
///

View File

@ -6,7 +6,7 @@ use ecow::EcoString;
use crate::foundations::{repr, ty, Repr};
use crate::layout::Abs;
use crate::util::{Numeric, Scalar};
use crate::utils::{Numeric, Scalar};
/// Defines how the remaining space in a layout is distributed.
///
@ -99,7 +99,7 @@ impl Add for Fr {
}
}
sub_impl!(Fr - Fr -> Fr);
typst_utils::sub_impl!(Fr - Fr -> Fr);
impl Mul<f64> for Fr {
type Output = Self;
@ -133,10 +133,10 @@ impl Div<f64> for Fr {
}
}
assign_impl!(Fr += Fr);
assign_impl!(Fr -= Fr);
assign_impl!(Fr *= f64);
assign_impl!(Fr /= f64);
typst_utils::assign_impl!(Fr += Fr);
typst_utils::assign_impl!(Fr -= Fr);
typst_utils::assign_impl!(Fr *= f64);
typst_utils::assign_impl!(Fr /= f64);
impl Sum for Fr {
fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {

View File

@ -11,7 +11,7 @@ use crate::layout::{
};
use crate::syntax::Span;
use crate::text::TextItem;
use crate::util::{LazyHash, Numeric};
use crate::utils::{LazyHash, Numeric};
use crate::visualize::{
ellipse, styled_rect, Color, FixedStroke, Geometry, Image, Paint, Path, Shape,
};

View File

@ -19,7 +19,7 @@ use crate::layout::{
Sides, Sizing,
};
use crate::syntax::Span;
use crate::util::NonZeroExt;
use crate::utils::NonZeroExt;
use crate::visualize::{Paint, Stroke};
/// A value that can be configured per cell.

View File

@ -15,7 +15,7 @@ use crate::layout::{
};
use crate::syntax::Span;
use crate::text::TextElem;
use crate::util::{MaybeReverseIter, Numeric};
use crate::utils::{MaybeReverseIter, Numeric};
use crate::visualize::Geometry;
/// Performs grid layout.

View File

@ -603,7 +603,7 @@ mod test {
use super::*;
use crate::foundations::Content;
use crate::layout::{Axes, Cell, Sides, Sizing};
use crate::util::NonZeroExt;
use crate::utils::NonZeroExt;
fn sample_cell() -> Cell {
Cell {

View File

@ -28,7 +28,7 @@ use crate::layout::{
use crate::model::{TableCell, TableFooter, TableHLine, TableHeader, TableVLine};
use crate::syntax::Span;
use crate::text::TextElem;
use crate::util::NonZeroExt;
use crate::utils::NonZeroExt;
use crate::visualize::{Paint, Stroke};
/// Arranges content in a grid.

View File

@ -6,7 +6,7 @@ use crate::foundations::Resolve;
use crate::layout::{
Abs, Axes, Cell, Frame, GridLayouter, LayoutMultiple, Point, Regions, Size, Sizing,
};
use crate::util::MaybeReverseIter;
use crate::utils::MaybeReverseIter;
/// All information needed to layout a single rowspan.
pub(super) struct Rowspan {

View File

@ -25,7 +25,7 @@ use crate::syntax::Span;
use crate::text::{
Lang, LinebreakElem, SmartQuoteElem, SmartQuoter, SmartQuotes, SpaceElem, TextElem,
};
use crate::util::Numeric;
use crate::utils::Numeric;
use crate::World;
/// Layouts content inline.

View File

@ -18,7 +18,7 @@ use crate::text::{
decorate, families, features, variant, Font, FontVariant, Glyph, Lang, Region,
TextElem, TextItem,
};
use crate::util::SliceExt;
use crate::utils::SliceExt;
use crate::World;
/// The result of shaping text.

View File

@ -9,7 +9,7 @@ use crate::diag::{At, Hint, HintedStrResult, SourceResult};
use crate::foundations::{func, scope, ty, Context, Fold, Repr, Resolve, StyleChain};
use crate::layout::{Abs, Em};
use crate::syntax::Span;
use crate::util::Numeric;
use crate::utils::Numeric;
/// A size or distance, possibly expressed with contextual units.
///
@ -227,7 +227,7 @@ impl Add for Length {
}
}
sub_impl!(Length - Length -> Length);
typst_utils::sub_impl!(Length - Length -> Length);
impl Mul<f64> for Length {
type Output = Self;
@ -253,10 +253,10 @@ impl Div<f64> for Length {
}
}
assign_impl!(Length += Length);
assign_impl!(Length -= Length);
assign_impl!(Length *= f64);
assign_impl!(Length /= f64);
typst_utils::assign_impl!(Length += Length);
typst_utils::assign_impl!(Length -= Length);
typst_utils::assign_impl!(Length *= f64);
typst_utils::assign_impl!(Length /= f64);
impl Resolve for Length {
type Output = Abs;

View File

@ -21,7 +21,7 @@ use crate::layout::{
use crate::model::Numbering;
use crate::text::TextElem;
use crate::util::{NonZeroExt, Numeric, Scalar};
use crate::utils::{NonZeroExt, Numeric, Scalar};
use crate::visualize::Paint;
/// Layouts its child onto one or multiple pages.

View File

@ -2,7 +2,7 @@ use std::fmt::{self, Debug, Formatter};
use std::ops::{Add, Div, Mul, Neg};
use crate::layout::{Abs, Axis, Size, Transform};
use crate::util::{Get, Numeric};
use crate::utils::{Get, Numeric};
/// A point in 2D.
#[derive(Default, Copy, Clone, Eq, PartialEq, Hash)]
@ -135,7 +135,7 @@ impl Add for Point {
}
}
sub_impl!(Point - Point -> Point);
typst_utils::sub_impl!(Point - Point -> Point);
impl Mul<f64> for Point {
type Output = Self;
@ -161,7 +161,7 @@ impl Div<f64> for Point {
}
}
assign_impl!(Point += Point);
assign_impl!(Point -= Point);
assign_impl!(Point *= f64);
assign_impl!(Point /= f64);
typst_utils::assign_impl!(Point += Point);
typst_utils::assign_impl!(Point -= Point);
typst_utils::assign_impl!(Point *= f64);
typst_utils::assign_impl!(Point /= f64);

View File

@ -4,7 +4,7 @@ use std::ops::{Add, Div, Mul, Neg};
use ecow::EcoString;
use crate::foundations::{repr, ty, Repr};
use crate::util::{Numeric, Scalar};
use crate::utils::{Numeric, Scalar};
/// A ratio of a whole.
///
@ -96,7 +96,7 @@ impl Add for Ratio {
}
}
sub_impl!(Ratio - Ratio -> Ratio);
typst_utils::sub_impl!(Ratio - Ratio -> Ratio);
impl Mul for Ratio {
type Output = Self;
@ -146,8 +146,8 @@ impl Div<Ratio> for f64 {
}
}
assign_impl!(Ratio += Ratio);
assign_impl!(Ratio -= Ratio);
assign_impl!(Ratio *= Ratio);
assign_impl!(Ratio *= f64);
assign_impl!(Ratio /= f64);
typst_utils::assign_impl!(Ratio += Ratio);
typst_utils::assign_impl!(Ratio -= Ratio);
typst_utils::assign_impl!(Ratio *= Ratio);
typst_utils::assign_impl!(Ratio *= f64);
typst_utils::assign_impl!(Ratio /= f64);

View File

@ -6,7 +6,7 @@ use ecow::{eco_format, EcoString};
use crate::foundations::{cast, ty, Fold, Repr, Resolve, StyleChain};
use crate::layout::{Abs, Em, Length, Ratio};
use crate::util::Numeric;
use crate::utils::Numeric;
/// A length in relation to some known length.
///

View File

@ -4,7 +4,7 @@ use crate::foundations::{elem, Content, Packed, Resolve, StyleChain};
use crate::layout::{
Abs, AlignElem, Axes, Fragment, Frame, LayoutMultiple, Point, Regions, Size,
};
use crate::util::Numeric;
use crate::utils::Numeric;
/// Repeats content to the available space.
///

View File

@ -7,7 +7,7 @@ use crate::foundations::{
StyleChain, Value,
};
use crate::layout::{Abs, Alignment, Axes, Axis, Corner, Rel, Size};
use crate::util::Get;
use crate::utils::Get;
/// A container with left, top, right and bottom components.
#[derive(Default, Copy, Clone, Eq, PartialEq, Hash)]

View File

@ -1,7 +1,7 @@
use std::ops::{Add, Div, Mul, Neg};
use crate::layout::{Abs, Axes, Point, Ratio};
use crate::util::Numeric;
use crate::utils::Numeric;
/// A size in 2D.
pub type Size = Axes<Abs>;
@ -54,7 +54,7 @@ impl Add for Size {
}
}
sub_impl!(Size - Size -> Size);
typst_utils::sub_impl!(Size - Size -> Size);
impl Mul<f64> for Size {
type Output = Self;
@ -80,7 +80,7 @@ impl Div<f64> for Size {
}
}
assign_impl!(Size -= Size);
assign_impl!(Size += Size);
assign_impl!(Size *= f64);
assign_impl!(Size /= f64);
typst_utils::assign_impl!(Size -= Size);
typst_utils::assign_impl!(Size += Size);
typst_utils::assign_impl!(Size *= f64);
typst_utils::assign_impl!(Size /= f64);

View File

@ -1,7 +1,7 @@
use crate::foundations::{cast, elem, Content, Packed, Resolve, StyleChain};
use crate::layout::{Abs, Em, Fr, Length, Ratio, Rel};
use crate::realize::{Behave, Behaviour};
use crate::util::Numeric;
use crate::utils::Numeric;
/// Inserts horizontal spacing into a paragraph.
///

View File

@ -8,7 +8,7 @@ use crate::layout::{
Abs, AlignElem, Axes, Axis, Dir, FixedAlignment, Fr, Fragment, Frame, HElem,
LayoutMultiple, Point, Regions, Size, Spacing, VElem,
};
use crate::util::{Get, Numeric};
use crate::utils::{Get, Numeric};
/// Arranges content and spacing horizontally or vertically.
///

View File

@ -37,8 +37,6 @@
extern crate self as typst;
#[macro_use]
pub mod util;
pub mod diag;
pub mod engine;
pub mod eval;
@ -55,6 +53,8 @@ pub mod visualize;
#[doc(inline)]
pub use typst_syntax as syntax;
#[doc(inline)]
pub use typst_utils as utils;
use std::collections::HashSet;
use std::ops::{Deref, Range};
@ -168,7 +168,7 @@ fn typeset(
fn deduplicate(mut diags: EcoVec<SourceDiagnostic>) -> EcoVec<SourceDiagnostic> {
let mut unique = HashSet::new();
diags.retain(|diag| {
let hash = crate::util::hash128(&(&diag.span, &diag.message));
let hash = crate::utils::hash128(&(&diag.span, &diag.message));
unique.insert(hash)
});
diags

View File

@ -21,7 +21,7 @@ use crate::syntax::Span;
use crate::text::{
families, variant, Font, FontFamily, FontList, FontWeight, LocalName, TextElem,
};
use crate::util::{NonZeroExt, Numeric};
use crate::utils::{NonZeroExt, Numeric};
use crate::World;
/// A mathematical equation.

View File

@ -14,7 +14,7 @@ use crate::math::{
};
use crate::syntax::{Span, Spanned};
use crate::text::TextElem;
use crate::util::Numeric;
use crate::utils::Numeric;
use crate::visualize::{FixedStroke, Geometry, LineCap, Shape, Stroke};
const DEFAULT_ROW_GAP: Em = Em::new(0.5);

View File

@ -2,7 +2,7 @@ use crate::foundations::{func, Cast, Content, Smart, Style, StyleChain};
use crate::layout::Abs;
use crate::math::{EquationElem, MathContext};
use crate::text::TextElem;
use crate::util::LazyHash;
use crate::utils::LazyHash;
/// Bold font style in math.
///

View File

@ -40,7 +40,7 @@ use crate::syntax::{Span, Spanned};
use crate::text::{
FontStyle, Lang, LocalName, Region, SubElem, SuperElem, TextElem, WeightDelta,
};
use crate::util::{LazyHash, NonZeroExt, PicoStr};
use crate::utils::{LazyHash, NonZeroExt, PicoStr};
use crate::World;
/// A bibliography / reference listing.
@ -357,7 +357,7 @@ impl Bibliography {
Ok(Bibliography {
map: Arc::new(map),
hash: crate::util::hash128(data),
hash: crate::utils::hash128(data),
})
}

View File

@ -19,7 +19,7 @@ use crate::layout::{
};
use crate::model::{Numbering, NumberingPattern, Outlinable, Refable, Supplement};
use crate::text::{Lang, Region, TextElem};
use crate::util::NonZeroExt;
use crate::utils::NonZeroExt;
use crate::visualize::ImageElem;
/// A figure with an optional caption.

View File

@ -11,7 +11,7 @@ use crate::introspection::{Count, Counter, CounterUpdate, Locatable, Location};
use crate::layout::{Abs, Em, HElem, Length, Ratio};
use crate::model::{Destination, Numbering, NumberingPattern, ParElem};
use crate::text::{SuperElem, TextElem, TextSize};
use crate::util::NonZeroExt;
use crate::utils::NonZeroExt;
use crate::visualize::{LineElem, Stroke};
/// A footnote.

View File

@ -12,7 +12,7 @@ use crate::layout::{
};
use crate::model::{Numbering, Outlinable, ParElem, Refable, Supplement};
use crate::text::{FontWeight, LocalName, SpaceElem, TextElem, TextSize};
use crate::util::NonZeroExt;
use crate::utils::NonZeroExt;
/// A section heading.
///

View File

@ -16,7 +16,7 @@ use crate::model::{
};
use crate::syntax::Span;
use crate::text::{LinebreakElem, LocalName, SpaceElem, TextElem};
use crate::util::NonZeroExt;
use crate::utils::NonZeroExt;
/// A table of contents, figures, or other elements.
///

View File

@ -17,7 +17,7 @@ use crate::layout::{
use crate::model::Figurable;
use crate::syntax::Span;
use crate::text::{LocalName, TextElem};
use crate::util::NonZeroExt;
use crate::utils::NonZeroExt;
use crate::visualize::{Paint, Stroke};
/// A table of items.

View File

@ -9,7 +9,7 @@ use crate::layout::{
};
use crate::model::ParElem;
use crate::text::TextElem;
use crate::util::Numeric;
use crate::utils::Numeric;
/// A list of terms and their descriptions.
///

View File

@ -11,7 +11,7 @@ use crate::foundations::{
};
use crate::introspection::{Locatable, Meta, MetaElem};
use crate::text::TextElem;
use crate::util::{hash128, BitSet};
use crate::utils::{hash128, BitSet};
/// What to do with an element when encountering it during realization.
struct Verdict<'a> {

View File

@ -277,7 +277,7 @@ fn lang_str(lang: Lang, region: Option<Region>) -> EcoString {
#[cfg(test)]
mod tests {
use super::*;
use crate::util::option_eq;
use crate::utils::option_eq;
#[test]
fn test_region_option_eq() {

View File

@ -27,7 +27,7 @@ use crate::loading::Readable;
use crate::model::Figurable;
use crate::syntax::{Span, Spanned};
use crate::text::{families, LocalName};
use crate::util::LazyHash;
use crate::utils::LazyHash;
use crate::visualize::Path;
use crate::World;

View File

@ -4,7 +4,7 @@ use crate::foundations::{elem, Packed, StyleChain};
use crate::layout::{
Abs, Angle, Axes, Frame, FrameItem, LayoutSingle, Length, Regions, Rel, Size,
};
use crate::util::Numeric;
use crate::utils::Numeric;
use crate::visualize::{Geometry, Stroke};
/// A line from one point to another.

View File

@ -9,7 +9,7 @@ use crate::engine::Engine;
use crate::foundations::{func, repr, scope, ty, Content, Smart, StyleChain};
use crate::layout::{Abs, Axes, Frame, LayoutMultiple, Length, Regions, Size};
use crate::syntax::{Span, Spanned};
use crate::util::Numeric;
use crate::utils::Numeric;
use crate::visualize::RelativeTo;
use crate::World;

View File

@ -9,7 +9,7 @@ use crate::layout::{
Axes, Em, Frame, FrameItem, LayoutSingle, Length, Point, Regions, Rel,
};
use crate::syntax::Span;
use crate::util::Numeric;
use crate::utils::Numeric;
use crate::visualize::{FixedStroke, Geometry, Paint, Path, Shape, Stroke};
/// A closed polygon.

View File

@ -8,7 +8,7 @@ use crate::layout::{
Point, Ratio, Regions, Rel, Sides, Size,
};
use crate::syntax::Span;
use crate::util::Get;
use crate::utils::Get;
use crate::visualize::{FixedStroke, Paint, Path, Stroke};
/// A rectangle with optional content.

View File

@ -6,7 +6,7 @@ use crate::foundations::{
Resolve, Smart, StyleChain, Value,
};
use crate::layout::{Abs, Length};
use crate::util::{Numeric, Scalar};
use crate::utils::{Numeric, Scalar};
use crate::visualize::{Color, Gradient, Paint, Pattern};
/// Defines how to draw a line.

View File

@ -429,7 +429,7 @@ fn code_block(resolver: &dyn Resolver, lang: &str, text: &str) -> Html {
document.pages.truncate(1);
}
let hash = typst::util::hash128(text);
let hash = typst::utils::hash128(text);
resolver.example(hash, highlighted, &document)
}

View File

@ -101,7 +101,7 @@ fn test() {
//
// We use `par_bridge` instead of `par_iter` because the former
// results in a stack overflow during PDF export. Probably related
// to `typst::util::Deferred` yielding.
// to `typst::utils::Deferred` yielding.
tests.iter().par_bridge().for_each(|test| {
logger.lock().start(test);
let result = std::panic::catch_unwind(|| run::run(test));