Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rename TiledError to Error + Add Result type #185

Merged
merged 5 commits into from
Mar 8, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions src/animation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
use xml::attribute::OwnedAttribute;

use crate::{
error::TiledError,
error::{Error, Result},
util::{get_attrs, parse_tag, XmlEventResult},
};

Expand All @@ -20,15 +20,15 @@ pub struct Frame {
}

impl Frame {
pub(crate) fn new(attrs: Vec<OwnedAttribute>) -> Result<Frame, TiledError> {
pub(crate) fn new(attrs: Vec<OwnedAttribute>) -> Result<Frame> {
let ((), (tile_id, duration)) = get_attrs!(
attrs,
optionals: [],
required: [
("tileid", tile_id, |v:String| v.parse().ok()),
("duration", duration, |v:String| v.parse().ok()),
],
TiledError::MalformedAttributes("A frame must have tileid and duration".to_string())
Error::MalformedAttributes("A frame must have tileid and duration".to_string())
);
Ok(Frame {
tile_id: tile_id,
Expand All @@ -39,7 +39,7 @@ impl Frame {

pub(crate) fn parse_animation(
parser: &mut impl Iterator<Item = XmlEventResult>,
) -> Result<Vec<Frame>, TiledError> {
) -> Result<Vec<Frame>> {
let mut animation = Vec::new();
parse_tag!(parser, "animation", {
"frame" => |attrs| {
Expand Down
8 changes: 4 additions & 4 deletions src/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@ pub type ResourcePathBuf = PathBuf;
/// [`ResourcePath`] to prevent loading them more than once.
pub trait ResourceCache {
/// Obtains a tileset from the cache, if it exists.
///
///
/// # Example
/// ```
/// use std::fs::File;
/// use tiled::{FilesystemResourceCache, ResourceCache, Tileset};
/// # use tiled::TiledError;
/// # fn main() -> Result<(), TiledError> {
/// # use tiled::Result;
/// # fn main() -> Result<()> {
/// let mut cache = FilesystemResourceCache::new();
/// let path = "assets/tilesheet.tsx";
///
Expand All @@ -32,7 +32,7 @@ pub trait ResourceCache {
/// # }
/// ```
fn get_tileset(&self, path: impl AsRef<ResourcePath>) -> Option<Arc<Tileset>>;

/// Returns the tileset mapped to `path` if it exists, otherwise calls `f` and, depending on its
/// result, it will:
/// - Insert the object into the cache, if the result was [`Ok`].
Expand Down
43 changes: 23 additions & 20 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::{fmt, path::PathBuf};
/// Errors which occured when parsing the file
#[derive(Debug)]
#[non_exhaustive]
pub enum TiledError {
pub enum Error {
/// A attribute was missing, had the wrong type of wasn't formated
/// correctly.
MalformedAttributes(String),
Expand Down Expand Up @@ -51,56 +51,59 @@ pub enum TiledError {
},
}

impl fmt::Display for TiledError {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
/// A result with an error variant of [`TiledError`].
bjorn marked this conversation as resolved.
Show resolved Hide resolved
pub type Result<T> = std::result::Result<T, Error>;

impl fmt::Display for Error {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> std::result::Result<(), fmt::Error> {
match self {
TiledError::MalformedAttributes(s) => write!(fmt, "{}", s),
TiledError::DecompressingError(e) => write!(fmt, "{}", e),
TiledError::Base64DecodingError(e) => write!(fmt, "{}", e),
TiledError::XmlDecodingError(e) => write!(fmt, "{}", e),
TiledError::PrematureEnd(e) => write!(fmt, "{}", e),
TiledError::PathIsNotFile => {
Error::MalformedAttributes(s) => write!(fmt, "{}", s),
Error::DecompressingError(e) => write!(fmt, "{}", e),
Error::Base64DecodingError(e) => write!(fmt, "{}", e),
Error::XmlDecodingError(e) => write!(fmt, "{}", e),
Error::PrematureEnd(e) => write!(fmt, "{}", e),
Error::PathIsNotFile => {
write!(
fmt,
"The path given is invalid because it isn't contained in any folder."
)
}
TiledError::CouldNotOpenFile { path, err } => {
Error::CouldNotOpenFile { path, err } => {
write!(
fmt,
"Could not open '{}'. Error: {}",
path.to_string_lossy(),
err
)
}
TiledError::InvalidTileFound => write!(fmt, "Invalid tile found in map being parsed"),
TiledError::InvalidEncodingFormat { encoding: None, compression: None } =>
Error::InvalidTileFound => write!(fmt, "Invalid tile found in map being parsed"),
Error::InvalidEncodingFormat { encoding: None, compression: None } =>
write!(
fmt,
"Deprecated combination of encoding and compression"
),
TiledError::InvalidEncodingFormat { encoding, compression } =>
Error::InvalidEncodingFormat { encoding, compression } =>
write!(
fmt,
"Unknown encoding or compression format or invalid combination of both (for tile layers): {} encoding with {} compression",
encoding.as_deref().unwrap_or("no"),
compression.as_deref().unwrap_or("no")
),
TiledError::InvalidPropertyValue{description} =>
Error::InvalidPropertyValue{description} =>
write!(fmt, "Invalid property value: {}", description),
TiledError::UnknownPropertyType { type_name } =>
Error::UnknownPropertyType { type_name } =>
write!(fmt, "Unknown property value type '{}'", type_name),
}
}
}

impl std::error::Error for TiledError {
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
TiledError::DecompressingError(e) => Some(e as &dyn std::error::Error),
TiledError::Base64DecodingError(e) => Some(e as &dyn std::error::Error),
TiledError::XmlDecodingError(e) => Some(e as &dyn std::error::Error),
TiledError::CouldNotOpenFile { err, .. } => Some(err as &dyn std::error::Error),
Error::DecompressingError(e) => Some(e as &dyn std::error::Error),
Error::Base64DecodingError(e) => Some(e as &dyn std::error::Error),
Error::XmlDecodingError(e) => Some(e as &dyn std::error::Error),
Error::CouldNotOpenFile { err, .. } => Some(err as &dyn std::error::Error),
_ => None,
}
}
Expand Down
6 changes: 3 additions & 3 deletions src/image.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::path::{Path, PathBuf};

use xml::attribute::OwnedAttribute;

use crate::{error::TiledError, properties::Color, util::*};
use crate::{error::{Error, Result}, properties::Color, util::*};

/// A reference to an image stored somewhere within the filesystem.
#[derive(Debug, PartialEq, Eq, Clone)]
Expand All @@ -29,7 +29,7 @@ impl Image {
parser: &mut impl Iterator<Item = XmlEventResult>,
attrs: Vec<OwnedAttribute>,
path_relative_to: impl AsRef<Path>,
) -> Result<Image, TiledError> {
) -> Result<Image> {
let (c, (s, w, h)) = get_attrs!(
attrs,
optionals: [
Expand All @@ -40,7 +40,7 @@ impl Image {
("width", width, |v:String| v.parse().ok()),
("height", height, |v:String| v.parse().ok()),
],
TiledError::MalformedAttributes("Image must have a source, width and height with correct types".to_string())
Error::MalformedAttributes("Image must have a source, width and height with correct types".to_string())
);

parse_tag!(parser, "image", { "" => |_| Ok(()) });
Expand Down
4 changes: 2 additions & 2 deletions src/layers/group.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::collections::HashMap;
use std::path::Path;

use crate::{
error::TiledError,
error::Error,
layers::{LayerData, LayerTag},
map::MapTilesetGid,
properties::{parse_properties, Properties},
Expand All @@ -21,7 +21,7 @@ impl GroupLayerData {
infinite: bool,
map_path: &Path,
tilesets: &[MapTilesetGid],
) -> Result<(Self, Properties), TiledError> {
) -> Result<(Self, Properties), Error> {
let mut properties = HashMap::new();
let mut layers = Vec::new();
parse_tag!(parser, "group", {
Expand Down
8 changes: 4 additions & 4 deletions src/layers/image.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ use std::{collections::HashMap, path::Path};

use crate::{
parse_properties,
util::{parse_tag, XmlEventResult, map_wrapper},
Image, Properties, TiledError,
util::{map_wrapper, parse_tag, XmlEventResult},
Error, Image, Properties,
};

#[derive(Debug, PartialEq, Clone)]
Expand All @@ -15,11 +15,11 @@ impl ImageLayerData {
pub(crate) fn new(
parser: &mut impl Iterator<Item = XmlEventResult>,
map_path: &Path,
) -> Result<(Self, Properties), TiledError> {
) -> Result<(Self, Properties), Error> {
let mut image: Option<Image> = None;
let mut properties = HashMap::new();

let path_relative_to = map_path.parent().ok_or(TiledError::PathIsNotFile)?;
let path_relative_to = map_path.parent().ok_or(Error::PathIsNotFile)?;

parse_tag!(parser, "imagelayer", {
"image" => |attrs| {
Expand Down
11 changes: 8 additions & 3 deletions src/layers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@ use std::path::Path;

use xml::attribute::OwnedAttribute;

use crate::{error::TiledError, properties::Properties, util::*, Color, Map, MapTilesetGid};
use crate::{
error::{Error, Result},
properties::Properties,
util::*,
Color, Map, MapTilesetGid,
};

mod image;
pub use image::*;
Expand Down Expand Up @@ -52,7 +57,7 @@ impl LayerData {
infinite: bool,
map_path: &Path,
tilesets: &[MapTilesetGid],
) -> Result<Self, TiledError> {
) -> Result<Self> {
let (
(opacity, tint_color, visible, offset_x, offset_y, parallax_x, parallax_y, name, id),
(),
Expand All @@ -72,7 +77,7 @@ impl LayerData {
required: [
],

TiledError::MalformedAttributes("layer parsing error, no id attribute found".to_string())
Error::MalformedAttributes("layer parsing error, no id attribute found".to_string())
);

let (ty, properties) = match tag {
Expand Down
6 changes: 3 additions & 3 deletions src/layers/object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use xml::attribute::OwnedAttribute;
use crate::{
parse_properties,
util::{get_attrs, map_wrapper, parse_tag, XmlEventResult},
Color, Map, MapTilesetGid, Object, ObjectData, Properties, TiledError,
Color, Error, Map, MapTilesetGid, Object, ObjectData, Properties,
};

/// Raw data referring to a map object layer or tile collision data.
Expand All @@ -24,15 +24,15 @@ impl ObjectLayerData {
parser: &mut impl Iterator<Item = XmlEventResult>,
attrs: Vec<OwnedAttribute>,
tilesets: Option<&[MapTilesetGid]>,
) -> Result<(ObjectLayerData, Properties), TiledError> {
) -> Result<(ObjectLayerData, Properties), Error> {
let (c, ()) = get_attrs!(
attrs,
optionals: [
("color", colour, |v:String| v.parse().ok()),
],
required: [],
// this error should never happen since there are no required attrs
TiledError::MalformedAttributes("object group parsing error".to_string())
Error::MalformedAttributes("object group parsing error".to_string())
);
let mut objects = Vec::new();
let mut properties = HashMap::new();
Expand Down
8 changes: 4 additions & 4 deletions src/layers/tile/finite.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use xml::attribute::OwnedAttribute;

use crate::{
util::{get_attrs, map_wrapper, XmlEventResult},
LayerTile, LayerTileData, MapTilesetGid, TiledError,
Error, LayerTile, LayerTileData, MapTilesetGid, Result,
};

use super::util::parse_data_line;
Expand Down Expand Up @@ -31,15 +31,15 @@ impl FiniteTileLayerData {
width: u32,
height: u32,
tilesets: &[MapTilesetGid],
) -> Result<Self, TiledError> {
) -> Result<Self> {
let ((e, c), ()) = get_attrs!(
attrs,
optionals: [
("encoding", encoding, |v| Some(v)),
("compression", compression, |v| Some(v)),
],
required: [],
TiledError::MalformedAttributes("data must have an encoding and a compression".to_string())
Error::MalformedAttributes("data must have an encoding and a compression".to_string())
);

let tiles = parse_data_line(e, c, parser, tilesets)?;
Expand Down Expand Up @@ -67,7 +67,7 @@ map_wrapper!(

impl<'map> FiniteTileLayer<'map> {
/// Obtains the tile present at the position given.
///
///
/// If the position given is invalid or the position is empty, this function will return [`None`].
pub fn get_tile(&self, x: i32, y: i32) -> Option<LayerTile> {
self.data
Expand Down
10 changes: 5 additions & 5 deletions src/layers/tile/infinite.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use xml::attribute::OwnedAttribute;

use crate::{
util::{floor_div, get_attrs, map_wrapper, parse_tag, XmlEventResult},
LayerTile, LayerTileData, MapTilesetGid, TiledError,
Error, LayerTile, LayerTileData, MapTilesetGid, Result,
};

use super::util::parse_data_line;
Expand All @@ -25,15 +25,15 @@ impl InfiniteTileLayerData {
parser: &mut impl Iterator<Item = XmlEventResult>,
attrs: Vec<OwnedAttribute>,
tilesets: &[MapTilesetGid],
) -> Result<Self, TiledError> {
) -> Result<Self> {
let ((e, c), ()) = get_attrs!(
attrs,
optionals: [
("encoding", encoding, |v| Some(v)),
("compression", compression, |v| Some(v)),
],
required: [],
TiledError::MalformedAttributes("data must have an encoding and a compression".to_string())
Error::MalformedAttributes("data must have an encoding and a compression".to_string())
);

let mut chunks = HashMap::<(i32, i32), Chunk>::new();
Expand Down Expand Up @@ -125,7 +125,7 @@ impl InternalChunk {
encoding: Option<String>,
compression: Option<String>,
tilesets: &[MapTilesetGid],
) -> Result<Self, TiledError> {
) -> Result<Self> {
let ((), (x, y, width, height)) = get_attrs!(
attrs,
optionals: [],
Expand All @@ -135,7 +135,7 @@ impl InternalChunk {
("width", width, |v: String| v.parse().ok()),
("height", height, |v: String| v.parse().ok()),
],
TiledError::MalformedAttributes("chunk must have x, y, width & height attributes".to_string())
Error::MalformedAttributes("chunk must have x, y, width & height attributes".to_string())
);

let tiles = parse_data_line(encoding, compression, parser, tilesets)?;
Expand Down
8 changes: 4 additions & 4 deletions src/layers/tile/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use xml::attribute::OwnedAttribute;
use crate::{
parse_properties,
util::{get_attrs, map_wrapper, parse_tag, XmlEventResult},
Gid, Map, MapTilesetGid, Properties, Tile, TileId, TiledError, Tileset,
Error, Gid, Map, MapTilesetGid, Properties, Tile, TileId, Tileset,
};

mod finite;
Expand Down Expand Up @@ -74,7 +74,7 @@ impl TileLayerData {
attrs: Vec<OwnedAttribute>,
infinite: bool,
tilesets: &[MapTilesetGid],
) -> Result<(Self, Properties), TiledError> {
) -> Result<(Self, Properties), Error> {
let ((), (width, height)) = get_attrs!(
attrs,
optionals: [
Expand All @@ -83,7 +83,7 @@ impl TileLayerData {
("width", width, |v: String| v.parse().ok()),
("height", height, |v: String| v.parse().ok()),
],
TiledError::MalformedAttributes("layer parsing error, width and height attributes required".to_string())
Error::MalformedAttributes("layer parsing error, width and height attributes required".to_string())
);
let mut result = Self::Finite(Default::default());
let mut properties = HashMap::new();
Expand Down Expand Up @@ -176,7 +176,7 @@ impl<'map> TileLayer<'map> {
}

/// Obtains the tile present at the position given.
///
///
/// If the position given is invalid or the position is empty, this function will return [`None`].
pub fn get_tile(&self, x: i32, y: i32) -> Option<LayerTile> {
match self {
Expand Down
Loading