From 56680d88f4c873c778e45914199b22580b2a265b Mon Sep 17 00:00:00 2001 From: "w.pomp" Date: Fri, 26 Sep 2025 18:14:18 +0200 Subject: [PATCH] - replace anyhow with thiserror --- Cargo.toml | 11 +-- LICENSE-APACHE | 176 +++++++++++++++++++++++++++++++++++++++++ LICENSE => LICENSE-MIT | 0 src/error.rs | 14 ++++ src/lib.rs | 43 +++++----- src/py.rs | 6 ++ 6 files changed, 225 insertions(+), 25 deletions(-) create mode 100644 LICENSE-APACHE rename LICENSE => LICENSE-MIT (100%) create mode 100644 src/error.rs diff --git a/Cargo.toml b/Cargo.toml index 90a77b6..6f7c5e3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,13 +1,14 @@ [package] name = "tiffwrite" -version = "2025.8.1" +version = "2025.9.0" edition = "2024" rust-version = "1.85.1" authors = ["Wim Pomp "] -license = "MIT" +license = "MIT OR Apache-2.0" description = "Write BioFormats/ImageJ compatible tiffs with zstd compression in parallel." homepage = "https://github.com/wimpomp/tiffwrite" repository = "https://github.com/wimpomp/tiffwrite" +documentation = "https://docs.rs/tiffwrite" readme = "README.md" keywords = ["bioformats", "tiff", "ndarray", "zstd", "fiji"] categories = ["multimedia::images", "science"] @@ -17,7 +18,6 @@ name = "tiffwrite" crate-type = ["cdylib", "rlib"] [dependencies] -anyhow = "1.0.98" colorcet = "0.2.1" colorgrad = "0.7.2" chrono = "0.4.41" @@ -25,9 +25,10 @@ css-color = "0.2.8" flate2 = "1.1.1" ndarray = "0.16.1" num = "0.4.3" -rayon = "1.10.0" -zstd = "0.13.3" numpy = { version = "0.25.0", optional = true } +rayon = "1.10.0" +thiserror = "2.0.16" +zstd = "0.13.3" [dependencies.pyo3] version = "0.25.1" diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 0000000..a7e77cb --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/LICENSE b/LICENSE-MIT similarity index 100% rename from LICENSE rename to LICENSE-MIT diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 0000000..f3da639 --- /dev/null +++ b/src/error.rs @@ -0,0 +1,14 @@ +use thiserror::Error; + + +#[derive(Debug, Error)] +pub enum Error { + #[error("io error: {0}")] + IO(#[from] std::io::Error), + #[error("could not parse color: {0}")] + ColorParse(String), + #[error("colorcet error: {0}")] + ColorCet(#[from] colorcet::ColorcetError), + #[error("could not covert ColorMap into LinearGradient")] + Conversion +} \ No newline at end of file diff --git a/src/lib.rs b/src/lib.rs index dd6a34b..ca85824 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,7 +1,7 @@ #[cfg(feature = "python")] mod py; +mod error; -use anyhow::{Result, anyhow}; use chrono::Utc; use colorcet::ColorMap; use colorgrad::{Gradient, LinearGradient}; @@ -23,6 +23,7 @@ use std::{ }; use zstd::zstd_safe::CompressionLevel; use zstd::{DEFAULT_COMPRESSION_LEVEL, stream::Encoder}; +use crate::error::Error; const TAG_SIZE: usize = 20; const OFFSET_SIZE: usize = 8; @@ -59,7 +60,7 @@ impl IFD { } } - fn write(&mut self, ijtifffile: &mut IJTiffFile, where_to_write_offset: u64) -> Result { + fn write(&mut self, ijtifffile: &mut IJTiffFile, where_to_write_offset: u64) -> Result { let mut tags = self.tags.drain().collect::>(); tags.sort(); ijtifffile.file.seek(SeekFrom::End(0))?; @@ -322,7 +323,7 @@ impl Tag { c as u64 } - fn write_tag(&mut self, ijtifffile: &mut IJTiffFile) -> Result<()> { + fn write_tag(&mut self, ijtifffile: &mut IJTiffFile) -> Result<(), Error> { self.offset = ijtifffile.file.stream_position()?; ijtifffile.file.write_all(&self.code.to_le_bytes())?; ijtifffile.file.write_all(&self.ttype.to_le_bytes())?; @@ -338,7 +339,7 @@ impl Tag { Ok(()) } - fn write_data(&self, ijtifffile: &mut IJTiffFile) -> Result<()> { + fn write_data(&self, ijtifffile: &mut IJTiffFile) -> Result<(), Error> { if self.bytes.len() > OFFSET_SIZE { ijtifffile.file.seek(SeekFrom::End(0))?; let offset = ijtifffile.write(&self.bytes)?; @@ -493,7 +494,7 @@ impl CompressedFrame { slice: (usize, usize, usize, usize), tile_width: usize, tile_length: usize, - ) -> Result + ) -> Result where W: Write, T: Bytes, @@ -524,7 +525,7 @@ impl CompressedFrame { slice: (usize, usize, usize, usize), tile_width: usize, tile_length: usize, - ) -> Result> + ) -> Result, Error> where T: Bytes, { @@ -539,7 +540,7 @@ impl CompressedFrame { tile_width: usize, tile_length: usize, compression_level: i32, - ) -> Result> + ) -> Result, Error> where T: Bytes, { @@ -678,7 +679,7 @@ impl Drop for IJTiffFile { impl IJTiffFile { /// create new tifffile from path, use it's save() method to save frames /// the file is finalized when it goes out of scope - pub fn new>(path: P) -> Result { + pub fn new>(path: P) -> Result { let mut file = OpenOptions::new() .create(true) .truncate(true) @@ -711,7 +712,8 @@ impl IJTiffFile { } /// set colors from css color names and #C01085 - pub fn set_colors>(&mut self, colors: &[S]) -> Result<()> { + /// (see [css_color](https://crates.io/crates/css-color)) + pub fn set_colors>(&mut self, colors: &[S]) -> Result<(), Error> { self.colors = Colors::Colors( colors .iter() @@ -735,17 +737,18 @@ impl IJTiffFile { (255.0 * c.green).round() as u8, (255.0 * c.blue).round() as u8, ]), - Err(_) => Err(anyhow!("could not parse color: {}", c)), + Err(_) => Err(Error::ColorParse(c.to_string())), } }) - .collect::>>()?, + .collect::, Error>>()?, ); Ok(()) } - pub fn set_colormap>(&mut self, name: S) -> Result<()> { + /// set colormap from named colormap (see [colorcet](https://crates.io/crates/colorcet)) + pub fn set_colormap>(&mut self, name: S) -> Result<(), Error> { let name = name.as_ref(); - let colormap: LinearGradient = name.parse::()?.try_into()?; + let colormap: LinearGradient = name.parse::()?.try_into().map_err(|_| Error::Conversion)?; let mut colormap = colormap .colors(256) .into_iter() @@ -832,7 +835,7 @@ impl IJTiffFile { hasher.finish() } - fn hash_check(&mut self, bytes: &Vec, offset: u64) -> Result { + fn hash_check(&mut self, bytes: &Vec, offset: u64) -> Result { let current_offset = self.file.stream_position()?; self.file.seek(SeekFrom::Start(offset))?; let mut buffer = vec![0; bytes.len()]; @@ -842,7 +845,7 @@ impl IJTiffFile { Ok(same) } - fn write(&mut self, bytes: &Vec) -> Result { + fn write(&mut self, bytes: &Vec) -> Result { let hash = IJTiffFile::hash(&bytes); if self.hashes.contains_key(&hash) && self.hash_check(bytes, *self.hashes.get(&hash).unwrap())? @@ -860,7 +863,7 @@ impl IJTiffFile { } /// save a 2d array to the tiff file at channel c, slice z, and time t - pub fn save<'a, A, T>(&mut self, frame: A, c: usize, z: usize, t: usize) -> Result<()> + pub fn save<'a, A, T>(&mut self, frame: A, c: usize, z: usize, t: usize) -> Result<(), Error> where A: AsArray<'a, T, Ix2>, T: Bytes + Clone + Send + Sync + 'static, @@ -882,7 +885,7 @@ impl IJTiffFile { Ok(()) } - fn collect_threads(&mut self, block: bool) -> Result<()> { + fn collect_threads(&mut self, block: bool) -> Result<(), Error> { for (c, z, t) in self.threads.keys().cloned().collect::>() { if block || self.threads[&(c, z, t)].is_finished() { if let Some(thread) = self.threads.remove(&(c, z, t)) { @@ -893,7 +896,7 @@ impl IJTiffFile { Ok(()) } - fn write_frame(&mut self, frame: CompressedFrame, c: usize, z: usize, t: usize) -> Result<()> { + fn write_frame(&mut self, frame: CompressedFrame, c: usize, z: usize, t: usize) -> Result<(), Error> { let mut offsets = Vec::new(); let mut bytecounts = Vec::new(); for tile in frame.bytes { @@ -940,7 +943,7 @@ impl IJTiffFile { c } - fn close(&mut self) -> Result<()> { + fn close(&mut self) -> Result<(), Error> { self.collect_threads(true)?; let mut c_size = 1; let mut z_size = 1; @@ -1074,7 +1077,7 @@ mod tests { #[test] /// An example of generating julia fractals. - fn julia_test() -> Result<()> { + fn julia_test() -> Result<(), Error> { let imgx = 800; let imgy = 600; diff --git a/src/py.rs b/src/py.rs index 42a3226..6998fad 100644 --- a/src/py.rs +++ b/src/py.rs @@ -4,6 +4,12 @@ use numpy::PyReadonlyArray2; use pyo3::exceptions::PyValueError; use pyo3::prelude::*; +impl From for PyErr { + fn from(err: crate::error::Error) -> PyErr { + PyErr::new::(err.to_string()) + } +} + #[pyclass(subclass)] #[pyo3(name = "Tag")] #[derive(Clone, Debug)]