Switch StrResult to EcoString

This commit is contained in:
Laurenz 2022-11-27 00:49:02 +01:00
parent 6bafc63910
commit 7caf98fe42
12 changed files with 30 additions and 33 deletions

View File

@ -641,8 +641,7 @@ impl FontSearcher {
}
}
/// Search for all fonts in a directory.
/// recursively.
/// Search for all fonts in a directory recursively.
fn search_dir(&mut self, path: impl AsRef<Path>) {
for entry in WalkDir::new(path)
.follow_links(true)

View File

@ -196,7 +196,7 @@ impl Cast<Spanned<Value>> for Marginal {
Value::Str(v) => Ok(Self::Content(TextNode::packed(v))),
Value::Content(v) => Ok(Self::Content(v)),
Value::Func(v) => Ok(Self::Func(v, value.span)),
v => Err(format!(
v => Err(format_eco!(
"expected none, content or function, found {}",
v.type_name(),
)),

View File

@ -263,7 +263,7 @@ impl Cast<Spanned<Value>> for Label {
Value::Str(v) => Ok(Self::Pattern(v.parse()?)),
Value::Content(v) => Ok(Self::Content(v)),
Value::Func(v) => Ok(Self::Func(v, value.span)),
v => Err(format!(
v => Err(format_eco!(
"expected string, content or function, found {}",
v.type_name(),
)),

View File

@ -154,13 +154,13 @@ impl<T> Trace<T> for SourceResult<T> {
}
/// A result type with a string error message.
pub type StrResult<T> = Result<T, String>;
pub type StrResult<T> = Result<T, EcoString>;
/// Transform `expected X, found Y` into `expected X or A, found Y`.
pub fn with_alternative(msg: String, alt: &str) -> String {
pub fn with_alternative(msg: EcoString, alt: &str) -> EcoString {
let mut parts = msg.split(", found ");
if let (Some(a), Some(b)) = (parts.next(), parts.next()) {
format!("{} or {}, found {}", a, alt, b)
format_eco!("{} or {}, found {}", a, alt, b)
} else {
msg
}

View File

@ -21,10 +21,6 @@ use crate::image::Image;
/// Export a document into a PDF file.
///
/// This creates one page per frame. In addition to the frames, you need to pass
/// in the context used during compilation so that fonts and images can be
/// included in the PDF.
///
/// Returns the raw bytes making up the PDF file.
pub fn pdf(document: &Document) -> Vec<u8> {
let mut ctx = PdfContext::new(&document.metadata);

View File

@ -16,11 +16,8 @@ use crate::image::{DecodedImage, Image};
/// Export a frame into a raster image.
///
/// This renders the frame at the given number of pixels per printer's point and
/// returns the resulting `tiny-skia` pixel buffer.
///
/// In addition to the frame, you need to pass in the context used during
/// compilation so that fonts and images can be rendered.
/// This renders the frame at the given number of pixels per point and returns
/// the resulting `tiny-skia` pixel buffer.
pub fn render(frame: &Frame, pixel_per_pt: f32) -> sk::Pixmap {
let size = frame.size();
let pxw = (pixel_per_pt * size.x.to_f32()).round().max(1.0) as u32;

View File

@ -6,7 +6,7 @@ use std::sync::Arc;
use super::{ops, Args, Func, Value, Vm};
use crate::diag::{At, SourceResult, StrResult};
use crate::syntax::Spanned;
use crate::util::ArcExt;
use crate::util::{format_eco, ArcExt, EcoString};
/// Create a new [`Array`] from values.
#[macro_export]
@ -253,7 +253,7 @@ impl Array {
vec.sort_by(|a, b| {
a.partial_cmp(b).unwrap_or_else(|| {
if result.is_ok() {
result = Err(format!(
result = Err(format_eco!(
"cannot order {} and {}",
a.type_name(),
b.type_name(),
@ -294,13 +294,13 @@ impl Array {
/// The out of bounds access error message.
#[cold]
fn out_of_bounds(index: i64, len: i64) -> String {
format!("array index out of bounds (index: {}, len: {})", index, len)
fn out_of_bounds(index: i64, len: i64) -> EcoString {
format_eco!("array index out of bounds (index: {}, len: {})", index, len)
}
/// The error message when the array is empty.
#[cold]
fn array_is_empty() -> String {
fn array_is_empty() -> EcoString {
"array is empty".into()
}

View File

@ -9,7 +9,7 @@ use crate::geom::{
Axes, Corners, Dir, GenAlign, Get, Length, Paint, PartialStroke, Point, Rel, Sides,
};
use crate::syntax::Spanned;
use crate::util::EcoString;
use crate::util::{format_eco, EcoString};
/// Cast from a value to a specific type.
pub trait Cast<V = Value>: Sized {
@ -94,7 +94,11 @@ macro_rules! __castable {
v => v.type_name(),
};
Err(format!("expected {}, found {}", $expected, found))
Err($crate::util::format_eco!(
"expected {}, found {}",
$expected,
found,
))
}
}
};
@ -426,7 +430,7 @@ where
};
if let Some((key, _)) = dict.iter().next() {
return Err(format!("unexpected key {key:?}"));
return Err(format_eco!("unexpected key {key:?}"));
}
Ok(sides.map(Option::unwrap_or_default))
@ -468,7 +472,7 @@ where
};
if let Some((key, _)) = dict.iter().next() {
return Err(format!("unexpected key {key:?}"));
return Err(format_eco!("unexpected key {key:?}"));
}
Ok(corners.map(Option::unwrap_or_default))

View File

@ -7,7 +7,7 @@ use super::{Args, Array, Func, Str, Value, Vm};
use crate::diag::{SourceResult, StrResult};
use crate::syntax::is_ident;
use crate::syntax::Spanned;
use crate::util::ArcExt;
use crate::util::{format_eco, ArcExt, EcoString};
/// Create a new [`Dict`] from key-value pairs.
#[macro_export]
@ -122,8 +122,8 @@ impl Dict {
/// The missing key access error message.
#[cold]
fn missing_key(key: &str) -> String {
format!("dictionary does not contain key {:?}", Str::from(key))
fn missing_key(key: &str) -> EcoString {
format_eco!("dictionary does not contain key {:?}", Str::from(key))
}
impl Debug for Dict {

View File

@ -3,13 +3,14 @@
use super::{Regex, Smart, Value};
use crate::diag::StrResult;
use crate::geom::{Axes, Axis, GenAlign, Length, Numeric, PartialStroke, Rel};
use crate::util::format_eco;
use std::cmp::Ordering;
use Value::*;
/// Bail with a type mismatch error.
macro_rules! mismatch {
($fmt:expr, $($value:expr),* $(,)?) => {
return Err(format!($fmt, $($value.type_name()),*))
return Err(format_eco!($fmt, $($value.type_name()),*))
};
}
@ -104,7 +105,7 @@ pub fn add(lhs: Value, rhs: Value) -> StrResult<Value> {
(a.downcast::<GenAlign>(), b.downcast::<GenAlign>())
{
if a.axis() == b.axis() {
return Err(format!("cannot add two {:?} alignments", a.axis()));
return Err(format_eco!("cannot add two {:?} alignments", a.axis()));
}
return Ok(Value::dynamic(match a.axis() {

View File

@ -8,7 +8,7 @@ use unicode_segmentation::UnicodeSegmentation;
use super::{castable, dict, Array, Dict, Value};
use crate::diag::StrResult;
use crate::geom::GenAlign;
use crate::util::EcoString;
use crate::util::{format_eco, EcoString};
/// Create a new [`Str`] from a format string.
#[macro_export]
@ -401,7 +401,7 @@ pub struct Regex(regex::Regex);
impl Regex {
/// Create a new regular expression.
pub fn new(re: &str) -> StrResult<Self> {
regex::Regex::new(re).map(Self).map_err(|err| err.to_string())
regex::Regex::new(re).map(Self).map_err(|err| format_eco!("{err}"))
}
}

View File

@ -344,7 +344,7 @@ macro_rules! primitive {
match value {
Value::$variant(v) => Ok(v),
$(Value::$other$(($binding))? => Ok($out),)*
v => Err(format!(
v => Err(format_eco!(
"expected {}, found {}",
Self::TYPE_NAME,
v.type_name(),