Directly use string conversion methods on Bytes

This lets `read` reuse the string for `Str`-backed `Bytes`. Also makes `within` more generally applicable just like `at`.
This commit is contained in:
Laurenz 2025-06-10 14:28:49 +02:00
parent 2fc89b8e5f
commit a8a2014422
6 changed files with 13 additions and 11 deletions

View File

@ -617,9 +617,15 @@ pub trait LoadedWithin<T> {
fn within(self, loaded: &Loaded) -> SourceResult<T>;
}
impl<T> LoadedWithin<T> for Result<T, LoadError> {
impl<T, E> LoadedWithin<T> for Result<T, E>
where
E: Into<LoadError>,
{
fn within(self, loaded: &Loaded) -> SourceResult<T> {
self.map_err(|err| load_err_in_text(loaded, err.pos, err.message))
self.map_err(|err| {
let LoadError { pos, message } = err.into();
load_err_in_text(loaded, pos, message)
})
}
}

View File

@ -131,10 +131,6 @@ impl Loaded {
pub fn new(source: Spanned<LoadSource>, bytes: Bytes) -> Self {
Self { source, data: bytes }
}
pub fn load_str(&self) -> SourceResult<&str> {
self.data.as_str().map_err(Into::into).within(self)
}
}
/// A loaded [`DataSource`].

View File

@ -1,7 +1,7 @@
use ecow::EcoString;
use typst_syntax::Spanned;
use crate::diag::SourceResult;
use crate::diag::{LoadedWithin, SourceResult};
use crate::engine::Engine;
use crate::foundations::{func, Cast};
use crate::loading::{DataSource, Load, Readable};
@ -38,7 +38,7 @@ pub fn read(
let loaded = path.map(DataSource::Path).load(engine.world)?;
Ok(match encoding {
None => Readable::Bytes(loaded.data),
Some(Encoding::Utf8) => Readable::Str(loaded.load_str()?.into()),
Some(Encoding::Utf8) => Readable::Str(loaded.data.to_str().within(&loaded)?),
})
}

View File

@ -33,7 +33,7 @@ pub fn toml(
source: Spanned<DataSource>,
) -> SourceResult<Value> {
let loaded = source.load(engine.world)?;
let raw = loaded.load_str()?;
let raw = loaded.data.as_str().within(&loaded)?;
::toml::from_str(raw).map_err(format_toml_error).within(&loaded)
}

View File

@ -61,7 +61,7 @@ pub fn xml(
source: Spanned<DataSource>,
) -> SourceResult<Value> {
let loaded = source.load(engine.world)?;
let text = loaded.load_str()?;
let text = loaded.data.as_str().within(&loaded)?;
let document = roxmltree::Document::parse_with_options(
text,
ParsingOptions { allow_dtd: true, ..Default::default() },

View File

@ -356,7 +356,7 @@ impl Debug for Bibliography {
/// Decode on library from one data source.
fn decode_library(loaded: &Loaded) -> SourceResult<Library> {
let data = loaded.load_str()?;
let data = loaded.data.as_str().within(loaded)?;
if let LoadSource::Path(file_id) = loaded.source.v {
// If we got a path, use the extension to determine whether it is