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. /// Search for all fonts in a directory recursively.
/// recursively.
fn search_dir(&mut self, path: impl AsRef<Path>) { fn search_dir(&mut self, path: impl AsRef<Path>) {
for entry in WalkDir::new(path) for entry in WalkDir::new(path)
.follow_links(true) .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::Str(v) => Ok(Self::Content(TextNode::packed(v))),
Value::Content(v) => Ok(Self::Content(v)), Value::Content(v) => Ok(Self::Content(v)),
Value::Func(v) => Ok(Self::Func(v, value.span)), Value::Func(v) => Ok(Self::Func(v, value.span)),
v => Err(format!( v => Err(format_eco!(
"expected none, content or function, found {}", "expected none, content or function, found {}",
v.type_name(), v.type_name(),
)), )),

View File

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

View File

@ -154,13 +154,13 @@ impl<T> Trace<T> for SourceResult<T> {
} }
/// A result type with a string error message. /// 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`. /// 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 "); let mut parts = msg.split(", found ");
if let (Some(a), Some(b)) = (parts.next(), parts.next()) { if let (Some(a), Some(b)) = (parts.next(), parts.next()) {
format!("{} or {}, found {}", a, alt, b) format_eco!("{} or {}, found {}", a, alt, b)
} else { } else {
msg msg
} }

View File

@ -21,10 +21,6 @@ use crate::image::Image;
/// Export a document into a PDF file. /// 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. /// Returns the raw bytes making up the PDF file.
pub fn pdf(document: &Document) -> Vec<u8> { pub fn pdf(document: &Document) -> Vec<u8> {
let mut ctx = PdfContext::new(&document.metadata); 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. /// Export a frame into a raster image.
/// ///
/// This renders the frame at the given number of pixels per printer's point and /// This renders the frame at the given number of pixels per point and returns
/// returns the resulting `tiny-skia` pixel buffer. /// 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.
pub fn render(frame: &Frame, pixel_per_pt: f32) -> sk::Pixmap { pub fn render(frame: &Frame, pixel_per_pt: f32) -> sk::Pixmap {
let size = frame.size(); let size = frame.size();
let pxw = (pixel_per_pt * size.x.to_f32()).round().max(1.0) as u32; 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 super::{ops, Args, Func, Value, Vm};
use crate::diag::{At, SourceResult, StrResult}; use crate::diag::{At, SourceResult, StrResult};
use crate::syntax::Spanned; use crate::syntax::Spanned;
use crate::util::ArcExt; use crate::util::{format_eco, ArcExt, EcoString};
/// Create a new [`Array`] from values. /// Create a new [`Array`] from values.
#[macro_export] #[macro_export]
@ -253,7 +253,7 @@ impl Array {
vec.sort_by(|a, b| { vec.sort_by(|a, b| {
a.partial_cmp(b).unwrap_or_else(|| { a.partial_cmp(b).unwrap_or_else(|| {
if result.is_ok() { if result.is_ok() {
result = Err(format!( result = Err(format_eco!(
"cannot order {} and {}", "cannot order {} and {}",
a.type_name(), a.type_name(),
b.type_name(), b.type_name(),
@ -294,13 +294,13 @@ impl Array {
/// The out of bounds access error message. /// The out of bounds access error message.
#[cold] #[cold]
fn out_of_bounds(index: i64, len: i64) -> String { fn out_of_bounds(index: i64, len: i64) -> EcoString {
format!("array index out of bounds (index: {}, len: {})", index, len) format_eco!("array index out of bounds (index: {}, len: {})", index, len)
} }
/// The error message when the array is empty. /// The error message when the array is empty.
#[cold] #[cold]
fn array_is_empty() -> String { fn array_is_empty() -> EcoString {
"array is empty".into() "array is empty".into()
} }

View File

@ -9,7 +9,7 @@ use crate::geom::{
Axes, Corners, Dir, GenAlign, Get, Length, Paint, PartialStroke, Point, Rel, Sides, Axes, Corners, Dir, GenAlign, Get, Length, Paint, PartialStroke, Point, Rel, Sides,
}; };
use crate::syntax::Spanned; use crate::syntax::Spanned;
use crate::util::EcoString; use crate::util::{format_eco, EcoString};
/// Cast from a value to a specific type. /// Cast from a value to a specific type.
pub trait Cast<V = Value>: Sized { pub trait Cast<V = Value>: Sized {
@ -94,7 +94,11 @@ macro_rules! __castable {
v => v.type_name(), 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() { 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)) Ok(sides.map(Option::unwrap_or_default))
@ -468,7 +472,7 @@ where
}; };
if let Some((key, _)) = dict.iter().next() { 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)) 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::diag::{SourceResult, StrResult};
use crate::syntax::is_ident; use crate::syntax::is_ident;
use crate::syntax::Spanned; use crate::syntax::Spanned;
use crate::util::ArcExt; use crate::util::{format_eco, ArcExt, EcoString};
/// Create a new [`Dict`] from key-value pairs. /// Create a new [`Dict`] from key-value pairs.
#[macro_export] #[macro_export]
@ -122,8 +122,8 @@ impl Dict {
/// The missing key access error message. /// The missing key access error message.
#[cold] #[cold]
fn missing_key(key: &str) -> String { fn missing_key(key: &str) -> EcoString {
format!("dictionary does not contain key {:?}", Str::from(key)) format_eco!("dictionary does not contain key {:?}", Str::from(key))
} }
impl Debug for Dict { impl Debug for Dict {

View File

@ -3,13 +3,14 @@
use super::{Regex, Smart, Value}; use super::{Regex, Smart, Value};
use crate::diag::StrResult; use crate::diag::StrResult;
use crate::geom::{Axes, Axis, GenAlign, Length, Numeric, PartialStroke, Rel}; use crate::geom::{Axes, Axis, GenAlign, Length, Numeric, PartialStroke, Rel};
use crate::util::format_eco;
use std::cmp::Ordering; use std::cmp::Ordering;
use Value::*; use Value::*;
/// Bail with a type mismatch error. /// Bail with a type mismatch error.
macro_rules! mismatch { macro_rules! mismatch {
($fmt:expr, $($value:expr),* $(,)?) => { ($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>()) (a.downcast::<GenAlign>(), b.downcast::<GenAlign>())
{ {
if a.axis() == b.axis() { 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() { 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 super::{castable, dict, Array, Dict, Value};
use crate::diag::StrResult; use crate::diag::StrResult;
use crate::geom::GenAlign; use crate::geom::GenAlign;
use crate::util::EcoString; use crate::util::{format_eco, EcoString};
/// Create a new [`Str`] from a format string. /// Create a new [`Str`] from a format string.
#[macro_export] #[macro_export]
@ -401,7 +401,7 @@ pub struct Regex(regex::Regex);
impl Regex { impl Regex {
/// Create a new regular expression. /// Create a new regular expression.
pub fn new(re: &str) -> StrResult<Self> { 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 { match value {
Value::$variant(v) => Ok(v), Value::$variant(v) => Ok(v),
$(Value::$other$(($binding))? => Ok($out),)* $(Value::$other$(($binding))? => Ok($out),)*
v => Err(format!( v => Err(format_eco!(
"expected {}, found {}", "expected {}, found {}",
Self::TYPE_NAME, Self::TYPE_NAME,
v.type_name(), v.type_name(),