c2pa-rs

A fork of https://github.com/contentauth/c2pa-rs/
git clone git://archive.git.mtrnord.blog/mtrnords-photography-manager/c2pa-rs.git
Log | Files | Refs | README

commit aadbb3227d388e526bc1e1161481fc0c9eb1481a
parent 85e7223d319f72b99b7f18294b4b4209e66ae03d
Author: Eric Scouten <scouten@adobe.com>
Date:   Tue, 31 Jan 2023 11:04:33 -0800

Fix Clippy warnings from new Rust 1.67 (#182)


Diffstat:
Mmake_test_images/src/main.rs | 2+-
Mmake_test_images/src/make_test_images.rs | 22+++++++++++-----------
Msdk/examples/client/client.rs | 8++++----
Msdk/examples/custom_assertion.rs | 2+-
Msdk/examples/show.rs | 2+-
Msdk/src/assertion.rs | 10+++++-----
Msdk/src/assertions/exif.rs | 8++++----
Msdk/src/assertions/labels.rs | 6+++---
Msdk/src/asset_handlers/bmff_io.rs | 38+++++++++++++++++++-------------------
Msdk/src/asset_handlers/jpeg_io.rs | 20++++++++------------
Msdk/src/asset_handlers/png_io.rs | 2+-
Msdk/src/asset_handlers/tiff_io.rs | 18+++++++++---------
Msdk/src/asset_io.rs | 2+-
Msdk/src/claim.rs | 28++++++++++++++--------------
Msdk/src/ingredient.rs | 16++++++++--------
Msdk/src/jumbf/boxes.rs | 9+++------
Msdk/src/jumbf/labels.rs | 6+++---
Msdk/src/jumbf_io.rs | 2+-
Msdk/src/manifest.rs | 14+++++++-------
Msdk/src/manifest_store.rs | 10+++++-----
Msdk/src/manifest_store_report.rs | 12++++++------
Msdk/src/status_tracker.rs | 4++--
Msdk/src/store.rs | 37++++++++++++++++---------------------
Msdk/src/utils/hash_utils.rs | 6+++---
Msdk/src/utils/xmp_inmemory_utils.rs | 4++--
Msdk/tests/integration.rs | 2+-
26 files changed, 139 insertions(+), 151 deletions(-)

diff --git a/make_test_images/src/main.rs b/make_test_images/src/main.rs @@ -25,7 +25,7 @@ fn main() -> Result<()> { } else { "make_test_images/tests.json" }; - let buf = std::fs::read_to_string(path).context(format!("Reading {}", path))?; + let buf = std::fs::read_to_string(path).context(format!("Reading {path}"))?; let config: make_test_images::Config = serde_json::from_str(&buf).context("Config file format")?; diff --git a/make_test_images/src/make_test_images.rs b/make_test_images/src/make_test_images.rs @@ -78,7 +78,7 @@ impl Config { let mut signcert_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); signcert_path.push(format!("../sdk/tests/fixtures/certs/{}.pub", self.alg)); let mut pkey_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - pkey_path.push(format!("../sdk/tests/fixtures/certs/{}.pem", alg)); + pkey_path.push(format!("../sdk/tests/fixtures/certs/{alg}.pem")); create_signer::from_files(signcert_path, pkey_path, alg, tsa_url) } } @@ -181,7 +181,7 @@ impl MakeTestImages { fn make_image(&self, recipe: &Recipe) -> Result<PathBuf> { let src = recipe.parent.as_deref(); let dst_path = self.make_path(&recipe.output); - println!("Creating {:?}", dst_path); + println!("Creating {dst_path:?}"); // keep track of all actions here let mut actions = Actions::new(); @@ -223,7 +223,7 @@ impl MakeTestImages { // load the image for editing let mut img = - image::open(src_path).context(format!("opening parent {:?}", src_path))?; + image::open(src_path).context(format!("opening parent {src_path:?}"))?; // adjust brightness to show we made an edit img = img.brighten(30); @@ -270,7 +270,7 @@ impl MakeTestImages { // get the bits of the ingredient, resize it and overlay it on the base image let img_ingredient = - image::open(ing_path).context(format!("opening ingredient {:?}", ing_path))?; + image::open(ing_path).context(format!("opening ingredient {ing_path:?}"))?; let img_small = img_ingredient.thumbnail(width, height); image::imageops::overlay(&mut img, &img_small, x, 0); @@ -307,13 +307,13 @@ impl MakeTestImages { let src = recipe.parent.as_deref().unwrap_or_default(); let src_path = &self.make_path(src); let dst_path = self.make_path(recipe.output.as_str()); - println!("Creating OGP {:?}", dst_path); + println!("Creating OGP {dst_path:?}"); let jumbf = jumbf_io::load_jumbf_from_file(&PathBuf::from(src_path)) - .context(format!("loading OGP {:?}", src_path))?; + .context(format!("loading OGP {src_path:?}"))?; // save the edited image to our destination file let mut img = - image::open(Path::new(src_path)).context(format!("loading OGP image{:?}", src_path))?; + image::open(Path::new(src_path)).context(format!("loading OGP image{src_path:?}"))?; img = img.grayscale(); img.save(&dst_path) .context(format!("saving OGP image{:?}", &dst_path))?; @@ -330,7 +330,7 @@ impl MakeTestImages { let op = recipe.op.as_str(); let src = recipe.parent.as_deref().unwrap_or_default(); let dst_path = self.make_path(recipe.output.as_str()); - println!("Creating Error op={} {:?}", op, dst_path); + println!("Creating Error op={op} {dst_path:?}"); let (search_bytes, replace_bytes) = match op { // modify the XMP (change xmp magic id value) - this should cause a data hash mismatch (OTGP) @@ -364,7 +364,7 @@ impl MakeTestImages { std::fs::copy(self.make_path(src), &dst_path).context("copying for make_err")?; Self::patch_file(&dst_path, search_bytes, replace_bytes) - .context(format!("patching {}", op))?; + .context(format!("patching {op}"))?; Ok(dst_path) } @@ -372,10 +372,10 @@ impl MakeTestImages { /// copies a file from the parent to the output fn make_copy(&self, recipe: &Recipe) -> Result<PathBuf> { let dst_path = self.make_path(recipe.output.as_str()); - println!("Copying {:?}", dst_path); + println!("Copying {dst_path:?}"); let src = recipe.parent.as_deref().unwrap_or_default(); let dst = recipe.output.as_str(); - std::fs::copy(src, &dst_path).context(format!("copying {} to {}", src, dst))?; + std::fs::copy(src, &dst_path).context(format!("copying {src} to {dst}"))?; Ok(dst_path) } diff --git a/sdk/examples/client/client.rs b/sdk/examples/client/client.rs @@ -28,7 +28,7 @@ const INDENT_SPACE: usize = 2; fn show_manifest(manifest_store: &ManifestStore, manifest_label: &str, level: usize) -> Result<()> { let indent = " ".repeat(level * INDENT_SPACE); - println!("{}manifest_label: {}", indent, manifest_label); + println!("{indent}manifest_label: {manifest_label}"); if let Some(manifest) = manifest_store.get(manifest_label) { println!( "{}title: {} , format: {}, instance_id: {}", @@ -52,12 +52,12 @@ fn show_manifest(manifest_store: &ManifestStore, manifest_label: &str, level: us if let Some(authors) = creative_work.author() { for author in authors { if let Some(name) = author.name() { - println!("{}author = {} ", indent, name); + println!("{indent}author = {name} "); } } } if let Some(url) = creative_work.get::<String>("url") { - println!("{}url = {} ", indent, url); + println!("{indent}url = {url} "); } } _ => {} @@ -133,7 +133,7 @@ pub fn main() -> Result<()> { let manifest_store = ManifestStore::from_file(&dest)?; // example of how to print out the whole manifest as json - println!("{}\n", manifest_store); + println!("{manifest_store}\n"); // walk through the manifest and access data. if let Some(manifest_label) = manifest_store.active_label() { diff --git a/sdk/examples/custom_assertion.rs b/sdk/examples/custom_assertion.rs @@ -64,7 +64,7 @@ fn main() -> Result<()> { let original = Custom::new(); manifest.add_assertion(&original)?; let result: Custom = manifest.find_assertion(Custom::LABEL)?; - println!("{}\n", manifest); + println!("{manifest}\n"); println!("c2pa sdk version = {}", result.version); Ok(()) diff --git a/sdk/examples/show.rs b/sdk/examples/show.rs @@ -20,7 +20,7 @@ fn main() -> Result<()> { let args: Vec<String> = std::env::args().collect(); if args.len() > 1 { let ms = ManifestStore::from_file(&args[1])?; - println!("{}", ms); + println!("{ms}"); } else { println!("Prints a manifest report (requires a file path argument)") } diff --git a/sdk/src/assertion.rs b/sdk/src/assertion.rs @@ -40,7 +40,7 @@ fn get_mutable_label(var_label: &str) -> (String, Option<usize>) { let (ver, ver_inst_str) = last.split_at(1); if ver == "v" { if let Ok(ver_inst) = ver_inst_str.parse::<usize>() { - let ver_trim = format!(".{}", last); + let ver_trim = format!(".{last}"); let root_label = var_label.trim_end_matches(&ver_trim); return (root_label.to_string(), Some(ver_inst)); } @@ -185,10 +185,10 @@ pub enum AssertionData { impl fmt::Debug for AssertionData { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { - Self::Json(s) => write!(f, "{:?}", s), // json encoded data + Self::Json(s) => write!(f, "{s:?}"), // json encoded data Self::Binary(_) => write!(f, "<omitted>"), Self::Uuid(uuid, _) => { - write!(f, "uuid: {}, <omitted>", uuid) + write!(f, "uuid: {uuid}, <omitted>") } Self::Cbor(s) => { let buf: Vec<u8> = Vec::new(); @@ -286,7 +286,7 @@ impl Assertion { // thumbnails need the image_type added match get_thumbnail_image_type(&self.label).as_str() { "none" => label, - image_type => format!("{}.{}", label, image_type), + image_type => format!("{label}.{image_type}"), } } @@ -297,7 +297,7 @@ impl Assertion { Some(v) => { if v > 1 { // c2pa does not include v1 labels - format!("{}.v{}", base_label, v) + format!("{base_label}.v{v}") } else { base_label } diff --git a/sdk/src/assertions/exif.rs b/sdk/src/assertions/exif.rs @@ -169,7 +169,7 @@ pub mod tests { .insert("exif:GPSLatitude", "39,21.102N") .unwrap(); manifest.add_assertion(&original).expect("adding assertion"); - println!("{}", manifest); + println!("{manifest}"); let exif: Exif = manifest .find_assertion(Exif::LABEL) .expect("find_assertion"); @@ -182,7 +182,7 @@ pub mod tests { let mut manifest = Manifest::new("my_app".to_owned()); let original = Exif::from_json_str(SPEC_EXAMPLE).expect("from_json"); manifest.add_assertion(&original).expect("adding assertion"); - println!("{}", manifest); + println!("{manifest}"); let exif: Exif = manifest .find_assertion(Exif::LABEL) .expect("find_assertion"); @@ -195,9 +195,9 @@ pub mod tests { let original = Exif::from_json_str(SPEC_EXAMPLE).expect("from_json"); let assertion = original.to_assertion().expect("to_assertion"); assert_eq!(assertion.content_type(), "application/json"); - println!("{:?}", assertion); + println!("{assertion:?}"); let result = Exif::from_assertion(&assertion).expect("from_assertion"); - println!("{:?}", result); + println!("{result:?}"); let latitude: String = result.get("exif:GPSLatitude").unwrap(); assert_eq!(&latitude, "39,21.102N") } diff --git a/sdk/src/assertions/labels.rs b/sdk/src/assertions/labels.rs @@ -187,14 +187,14 @@ pub fn version(label: &str) -> Option<usize> { /// ``` pub fn add_thumbnail_format(label: &str, format: &str) -> String { match format { - "image/jpeg" | "jpeg" | "jpg" => format!("{}.jpeg", label), - "image/png" | "png" => format!("{}.png", label), + "image/jpeg" | "jpeg" | "jpg" => format!("{label}.jpeg"), + "image/png" | "png" => format!("{label}.png"), _ => { let p: Vec<&str> = format.split('/').collect(); if p.len() == 2 && p[0] == "image" { format!("{}/{}", label, p[1]) // try to parse other image types } else { - format!("{}/{}", label, format) + format!("{label}/{format}") } } } diff --git a/sdk/src/asset_handlers/bmff_io.rs b/sdk/src/asset_handlers/bmff_io.rs @@ -253,7 +253,7 @@ fn write_box_header_ext<W: Write>(w: &mut W, v: u8, f: u32) -> Result<u64> { } fn box_start(reader: &mut dyn CAIRead) -> Result<u64> { - Ok(reader.seek(SeekFrom::Current(0))? - HEADER_SIZE) + Ok(reader.stream_position()? - HEADER_SIZE) } fn _skip_bytes(reader: &mut dyn CAIRead, size: u64) -> Result<()> { @@ -364,7 +364,7 @@ pub fn bmff_to_jumbf_exclusions( reader: &mut dyn CAIRead, bmff_exclusions: &[ExclusionsMap], ) -> Result<Vec<Exclusion>> { - let start = reader.seek(SeekFrom::Current(0))?; + let start = reader.stream_position()?; let size = reader.seek(SeekFrom::End(0))?; reader.seek(SeekFrom::Start(start))?; @@ -502,7 +502,7 @@ fn adjust_stco_and_co64<W: Write + CAIRead>( bmff_path_map: &HashMap<String, Vec<Token>>, adjust: i32, ) -> Result<()> { - let start_pos = output.seek(SeekFrom::Current(0))?; // save starting point + let start_pos = output.stream_position()?; // save starting point // handle 32 bit offsets if let Some(stco_list) = bmff_path_map.get("/moov/trak/mdia/minf/stbl/stco") { @@ -529,7 +529,7 @@ fn adjust_stco_and_co64<W: Write + CAIRead>( let entry_count = output.read_u32::<BigEndian>()?; // read and patch offsets - let entry_start_pos = output.seek(SeekFrom::Current(0))?; + let entry_start_pos = output.stream_position()?; let mut entries: Vec<u32> = Vec::new(); for _e in 0..entry_count { let offset = output.read_u32::<BigEndian>()?; @@ -580,7 +580,7 @@ fn adjust_stco_and_co64<W: Write + CAIRead>( let entry_count = output.read_u32::<BigEndian>()?; // read and patch offsets - let entry_start_pos = output.seek(SeekFrom::Current(0))?; + let entry_start_pos = output.stream_position()?; let mut entries: Vec<u64> = Vec::new(); for _e in 0..entry_count { let offset = output.read_u64::<BigEndian>()?; @@ -620,7 +620,7 @@ pub(crate) fn build_bmff_tree( current_node: &Token, bmff_path_map: &mut HashMap<String, Vec<Token>>, ) -> Result<()> { - let start = reader.seek(SeekFrom::Current(0))?; + let start = reader.stream_position()?; let mut current = start; while current < end { @@ -716,18 +716,18 @@ pub(crate) fn build_bmff_tree( add_token_to_cache(bmff_path_map, path, new_token); // consume all sub-boxes - let mut current = reader.seek(SeekFrom::Current(0))?; + let mut current = reader.stream_position()?; let end = start + s; while current < end { build_bmff_tree(reader, end, bmff_tree, &new_token, bmff_path_map)?; - current = reader.seek(SeekFrom::Current(0))?; + current = reader.stream_position()?; } // position seek pointer skip_bytes_to(reader, start + s)?; } _ => { - let start = reader.seek(SeekFrom::Current(0))? - HEADER_SIZE; + let start = reader.stream_position()? - HEADER_SIZE; let b = if FULL_BOX_TYPES.contains(&header.fourcc.as_str()) { let (version, flags) = read_box_header_ext(reader)?; // box extensions @@ -763,7 +763,7 @@ pub(crate) fn build_bmff_tree( skip_bytes_to(reader, start + s)?; } } - current = reader.seek(SeekFrom::Current(0))?; + current = reader.stream_position()?; } Ok(()) @@ -793,7 +793,7 @@ fn get_manifest_token( impl CAILoader for BmffIO { fn read_cai(&self, reader: &mut dyn CAIRead) -> Result<Vec<u8>> { - let start = reader.seek(SeekFrom::Current(0))?; + let start = reader.stream_position()?; let size = reader.seek(SeekFrom::End(0))?; reader.seek(SeekFrom::Start(start))?; @@ -910,7 +910,7 @@ impl AssetIO for BmffIO { fn save_cai_store(&self, asset_path: &std::path::Path, store_bytes: &[u8]) -> Result<()> { let mut input = File::open(asset_path)?; let size = input.seek(SeekFrom::End(0))?; - input.seek(SeekFrom::Start(0))?; + input.rewind()?; // create root node let root_box = BoxInfo { @@ -974,7 +974,7 @@ impl AssetIO for BmffIO { }; // write content before ContentProvenanceBox - input.seek(SeekFrom::Start(0))?; + input.rewind()?; let mut b = vec![0u8; start]; input.read_exact(&mut b)?; temp_file.write_all(&b)?; @@ -1026,7 +1026,7 @@ impl AssetIO for BmffIO { let mut output_bmff_map: HashMap<String, Vec<Token>> = HashMap::new(); let size = temp_file.seek(SeekFrom::End(0))?; - temp_file.seek(SeekFrom::Start(0))?; + temp_file.rewind()?; build_bmff_tree( &mut temp_file, size, @@ -1064,7 +1064,7 @@ impl AssetIO for BmffIO { fn remove_cai_store(&self, asset_path: &Path) -> Result<()> { let mut input = File::open(asset_path)?; let size = input.seek(SeekFrom::End(0))?; - input.seek(SeekFrom::Start(0))?; + input.rewind()?; // create root node let root_box = BoxInfo { @@ -1112,7 +1112,7 @@ impl AssetIO for BmffIO { }; // write content before ContentProvenanceBox - input.seek(SeekFrom::Start(0))?; + input.rewind()?; let mut b = vec![0u8; start]; input.read_exact(&mut b)?; temp_file.write_all(&b)?; @@ -1157,7 +1157,7 @@ impl AssetIO for BmffIO { let mut output_bmff_map: HashMap<String, Vec<Token>> = HashMap::new(); let size = temp_file.seek(SeekFrom::End(0))?; - temp_file.seek(SeekFrom::Start(0))?; + temp_file.rewind()?; build_bmff_tree( &mut temp_file, size, @@ -1193,7 +1193,7 @@ impl AssetPatch for BmffIO { .create(false) .open(asset_path)?; let size = asset.seek(SeekFrom::End(0))?; - asset.seek(SeekFrom::Start(0))?; + asset.rewind()?; // create root node let root_box = BoxInfo { @@ -1286,7 +1286,7 @@ pub mod tests { assert!(errors.is_empty()); if let Ok(s) = store { - print!("Store: \n{}", s); + print!("Store: \n{s}"); } } diff --git a/sdk/src/asset_handlers/jpeg_io.rs b/sdk/src/asset_handlers/jpeg_io.rs @@ -11,11 +11,7 @@ // specific language governing permissions and limitations under // each license. -use std::{ - fs::File, - io::{Cursor, SeekFrom}, - path::*, -}; +use std::{fs::File, io::Cursor, path::*}; use byteorder::{BigEndian, ReadBytesExt}; use img_parts::{ @@ -68,9 +64,9 @@ fn xmp_from_bytes(asset_bytes: &[u8]) -> Option<String> { fn add_required_segs_to_stream(stream: &mut dyn CAIReadWrite) -> Result<()> { let mut buf: Vec<u8> = Vec::new(); - stream.seek(SeekFrom::Start(0))?; + stream.rewind()?; stream.read_to_end(&mut buf).map_err(Error::IoError)?; - stream.seek(SeekFrom::Start(0))?; + stream.rewind()?; let dimg_opt = DynImage::from_bytes(buf.into()) .map_err(|_err| Error::InvalidAsset("Could not parse input JPEG".to_owned()))?; @@ -153,7 +149,7 @@ impl CAILoader for JpegIO { // load the bytes let mut buf: Vec<u8> = Vec::new(); - asset_reader.seek(SeekFrom::Start(0))?; + asset_reader.rewind()?; asset_reader.read_to_end(&mut buf).map_err(Error::IoError)?; let dimg_opt = DynImage::from_bytes(buf.into()) @@ -238,7 +234,7 @@ impl CAIWriter for JpegIO { //fn write_cai<W: Write>(buf: Vec<u8>, writer: W, store_bytes: &[u8]) -> Result<()> { let mut buf = Vec::new(); // read the whole asset - stream.seek(SeekFrom::Start(0))?; + stream.rewind()?; stream.read_to_end(&mut buf).map_err(Error::IoError)?; let mut jpeg = Jpeg::from_bytes(buf.into()).map_err(|_err| Error::EmbeddingError)?; @@ -289,7 +285,7 @@ impl CAIWriter for JpegIO { jpeg.segments_mut().insert(seg, app11_segment); // we put this in the beginning... } - stream.seek(SeekFrom::Start(0))?; + stream.rewind()?; jpeg.encoder() .write_to(stream) .map_err(|_err| Error::InvalidAsset("JPEG write error".to_owned()))?; @@ -310,9 +306,9 @@ impl CAIWriter for JpegIO { add_required_segs_to_stream(stream)?; let mut buf: Vec<u8> = Vec::new(); - stream.seek(SeekFrom::Start(0))?; + stream.rewind()?; stream.read_to_end(&mut buf).map_err(Error::IoError)?; - stream.seek(SeekFrom::Start(0))?; + stream.rewind()?; let dimg = DynImage::from_bytes(buf.into()) .map_err(|e| Error::OtherError(Box::new(e)))? diff --git a/sdk/src/asset_handlers/png_io.rs b/sdk/src/asset_handlers/png_io.rs @@ -52,7 +52,7 @@ fn get_png_chunk_positions(f: &mut dyn CAIRead) -> Result<Vec<PngChunkPos>> { let mut chunk_positions: Vec<PngChunkPos> = Vec::new(); // move to beginning of file - f.seek(SeekFrom::Start(0))?; + f.rewind()?; let mut buf4 = [0; 4]; let mut hdr = [0; 8]; diff --git a/sdk/src/asset_handlers/tiff_io.rs b/sdk/src/asset_handlers/tiff_io.rs @@ -280,7 +280,7 @@ impl TiffStructure { { let mut byte_reader = ByteOrdered::runtime(reader, byte_order); - let ifd_offset = byte_reader.seek(SeekFrom::Current(0))?; + let ifd_offset = byte_reader.stream_position()?; //println!("IFD Offset: {:#x}", ifd_offset); let entry_cnt = if big_tiff { @@ -341,7 +341,7 @@ where R: Read + Seek, { let _size = input.seek(SeekFrom::End(0))?; - input.seek(SeekFrom::Start(0))?; + input.rewind()?; let ts = TiffStructure::load(input)?; @@ -496,7 +496,7 @@ impl<T: Read + Write + Seek> TiffCloner<T> { } fn offset(&mut self) -> Result<u64> { - Ok(self.writer.seek(SeekFrom::Current(0))?) + Ok(self.writer.stream_position()?) } fn pad_word_boundary(&mut self) -> Result<()> { @@ -522,13 +522,13 @@ impl<T: Read + Write + Seek> TiffCloner<T> { self.writer.write_u16(43u16)?; self.writer.write_u16(8u16)?; self.writer.write_u16(0u16)?; - offset = self.writer.seek(SeekFrom::Current(0))?; // first ifd offset + offset = self.writer.stream_position()?; // first ifd offset self.writer.write_u64(0)?; } else { self.writer.write_all(&[boi, boi])?; self.writer.write_u16(42u16)?; - offset = self.writer.seek(SeekFrom::Current(0))?; // first ifd offset + offset = self.writer.stream_position()?; // first ifd offset self.writer.write_u32(0)?; } @@ -564,7 +564,7 @@ impl<T: Read + Write + Seek> TiffCloner<T> { if value_bytes_ref.len() > data_bytes { // get location of entry data start - let offset = self.writer.seek(SeekFrom::Current(0))?; + let offset = self.writer.stream_position()?; // write out the data bytes self.writer.write_all(value_bytes_ref)?; @@ -599,7 +599,7 @@ impl<T: Read + Write + Seek> TiffCloner<T> { self.pad_word_boundary()?; // save location of start of IFD - let ifd_offset = self.writer.seek(SeekFrom::Current(0))?; + let ifd_offset = self.writer.stream_position()?; // write out the entry count self.write_entry_count(target_ifd.len())?; @@ -703,7 +703,7 @@ impl<T: Read + Write + Seek> TiffCloner<T> { _ => return Err(Error::InvalidAsset("invalid TIFF strip".to_string())), }; - let dest_offset = self.writer.seek(SeekFrom::Current(0))?; + let dest_offset = self.writer.stream_position()?; dest_offsets.push(dest_offset); // copy the strip to new file @@ -804,7 +804,7 @@ impl<T: Read + Write + Seek> TiffCloner<T> { _ => return Err(Error::InvalidAsset("invalid TIFF tile".to_string())), }; - let dest_offset = self.writer.seek(SeekFrom::Current(0))?; + let dest_offset = self.writer.stream_position()?; dest_offsets.push(dest_offset); // copy the tile to new file diff --git a/sdk/src/asset_io.rs b/sdk/src/asset_io.rs @@ -28,7 +28,7 @@ pub enum HashBlockObjectType { impl fmt::Display for HashBlockObjectType { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{:?}", self) + write!(f, "{self:?}") } } #[derive(Debug)] diff --git a/sdk/src/claim.rs b/sdk/src/claim.rs @@ -488,7 +488,7 @@ impl Claim { if let Some(append_val) = hint_value.as_str() { map.insert( hint_key.to_string(), - Value::String(format!("{}, {}", curr_val, append_val)), + Value::String(format!("{curr_val}, {append_val}")), ); } return; @@ -849,9 +849,9 @@ impl Claim { /// Verify claim signature, assertion store and asset hashes /// claim - claim to be verified /// asset_bytes - reference to bytes of the asset - pub fn verify_claim<'a>( + pub fn verify_claim( claim: &Claim, - asset_data: &ClaimAssetData<'a>, + asset_data: &ClaimAssetData<'_>, is_provenance: bool, validation_log: &mut impl StatusTracker, ) -> Result<()> { @@ -897,9 +897,9 @@ impl Claim { Ok(vi.cert_chain) } - fn verify_internal<'a>( + fn verify_internal( claim: &Claim, - asset_data: &ClaimAssetData<'a>, + asset_data: &ClaimAssetData<'_>, is_provenance: bool, verified: Result<ValidationInfo>, validation_log: &mut impl StatusTracker, @@ -1090,15 +1090,15 @@ impl Claim { Err(e) => { let log_item = log_item!( claim.assertion_uri(&dh_assertion.label()), - format!("asset hash error, name: {}, error: {}", name, e), + format!("asset hash error, name: {name}, error: {e}"), "verify_internal" ) - .error(Error::HashMismatch(format!("Asset hash failure: {}", e))) + .error(Error::HashMismatch(format!("Asset hash failure: {e}"))) .validation_status(validation_status::ASSERTION_DATAHASH_MISMATCH); validation_log.log( log_item, - Some(Error::HashMismatch(format!("Asset hash failure: {}", e))), + Some(Error::HashMismatch(format!("Asset hash failure: {e}"))), )?; } } @@ -1133,15 +1133,15 @@ impl Claim { Err(e) => { let log_item = log_item!( claim.assertion_uri(&dh_assertion.label()), - format!("asset hash error, name: {}, error: {}", name, e), + format!("asset hash error, name: {name}, error: {e}"), "verify_internal" ) - .error(Error::HashMismatch(format!("Asset hash failure: {}", e))) + .error(Error::HashMismatch(format!("Asset hash failure: {e}"))) .validation_status(validation_status::ASSERTION_DATAHASH_MISMATCH); validation_log.log( log_item, - Some(Error::HashMismatch(format!("Asset hash failure: {}", e))), + Some(Error::HashMismatch(format!("Asset hash failure: {e}"))), )?; } } @@ -1550,7 +1550,7 @@ impl Claim { let tn_type = get_thumbnail_image_type(label); format!("{}__{}.{}", get_thumbnail_type(label), instance, tn_type) } else { - format!("{}__{}", label, instance) + format!("{label}__{instance}") } } @@ -1675,7 +1675,7 @@ pub mod tests { let restored_binary = restored_claim.data().expect("failure returning data"); assert_eq!(orig_binary, restored_binary); - println!("Restored Claim: {:?}", restored_claim); + println!("Restored Claim: {restored_claim:?}"); // NOTE: I added a separate mirror of original data because a third-party's // JSON serialization could differ from our re-serialization of that same data. @@ -1689,7 +1689,7 @@ pub mod tests { .to_json(AssertionStoreJsonFormat::OrderedList, true) .expect("could not generate json"); - println!("Claim: {}", json_str); + println!("Claim: {json_str}"); } #[test] diff --git a/sdk/src/ingredient.rs b/sdk/src/ingredient.rs @@ -337,7 +337,7 @@ impl Ingredient { use uuid::Uuid; let uuid = Uuid::new_v4(); //warn!("Generating fake id {}", uuid); - format!("xmp:{}id:{}", id_type, uuid) + format!("xmp:{id_type}id:{uuid}") } // get required information from the file path @@ -818,7 +818,7 @@ mod tests_file_io { let ingredient = Ingredient::from_file(ap).expect("from_file"); stats(&ingredient); - println!("ingredient = {}", ingredient); + println!("ingredient = {ingredient}"); assert_eq!(ingredient.title(), "Purple Square.psd"); assert_eq!(ingredient.format(), "image/vnd.adobe.photoshop"); assert!(ingredient.thumbnail().is_none()); // should always be none @@ -832,7 +832,7 @@ mod tests_file_io { let ingredient = Ingredient::from_file(ap).expect("from_file"); stats(&ingredient); - println!("ingredient = {}", ingredient); + println!("ingredient = {ingredient}"); assert_eq!(&ingredient.title, MANIFEST_JPEG); assert_eq!(ingredient.format(), "image/jpeg"); assert!(ingredient.thumbnail().is_some()); // we don't generate this thumbnail @@ -848,7 +848,7 @@ mod tests_file_io { let ingredient = Ingredient::from_file(ap).expect("from_file"); stats(&ingredient); - println!("ingredient = {}", ingredient); + println!("ingredient = {ingredient}"); assert_eq!(&ingredient.title, NO_MANIFEST_JPEG); assert_eq!(ingredient.format(), "image/jpeg"); test_thumbnail(&ingredient, "image/jpeg"); @@ -877,7 +877,7 @@ mod tests_file_io { let ingredient = Ingredient::from_file_with_options(ap, &MyOptions {}).expect("from_file"); stats(&ingredient); - println!("ingredient = {}", ingredient); + println!("ingredient = {ingredient}"); assert_eq!(ingredient.title(), "MyTitle"); assert_eq!(ingredient.format(), "image/jpeg"); assert!(ingredient.hash().is_some()); @@ -894,7 +894,7 @@ mod tests_file_io { let ingredient = Ingredient::from_file(ap).expect("from_file"); stats(&ingredient); - println!("ingredient = {}", ingredient); + println!("ingredient = {ingredient}"); assert_eq!(ingredient.title(), "libpng-test.png"); test_thumbnail(&ingredient, "image/png"); assert!(ingredient.provenance().is_none()); @@ -929,7 +929,7 @@ mod tests_file_io { let ingredient = Ingredient::from_file(ap).expect("from_file"); stats(&ingredient); - println!("ingredient = {}", ingredient); + println!("ingredient = {ingredient}"); assert_eq!(ingredient.title(), PRERELEASE_JPEG); assert_eq!(ingredient.format(), "image/jpeg"); test_thumbnail(&ingredient, "image/jpeg"); @@ -947,7 +947,7 @@ mod tests_file_io { fn test_jpg_nested() { let ap = fixture_path("CIE-sig-CA.jpg"); let ingredient = Ingredient::from_file(ap).expect("from_file"); - println!("ingredient = {}", ingredient); + println!("ingredient = {ingredient}"); assert_eq!(ingredient.validation_status(), None); } } diff --git a/sdk/src/jumbf/boxes.rs b/sdk/src/jumbf/boxes.rs @@ -1710,7 +1710,7 @@ const TOGGLE_SIZE: u64 = 1; /// method for getting the current position pub fn current_pos<R: Seek>(seeker: &mut R) -> JumbfParseResult<u64> { - Ok(seeker.seek(SeekFrom::Current(0))?) + Ok(seeker.stream_position()?) } /// method for seeking back to the start of the box (header) @@ -2134,7 +2134,7 @@ impl BoxReader { let box_label = jdesc.label(); debug!( "{}", - format!("START#Label: {:?}", box_label /*jdesc.label()*/) + format!("START#Label: {box_label:?}" /*jdesc.label()*/) ); let mut sbox = JUMBFSuperBox::from(jdesc); @@ -2212,10 +2212,7 @@ impl BoxReader { } } - debug!( - "{}", - format!("END#Label: {:?}", box_label /*jdesc.label()*/) - ); + debug!("{}", format!("END#Label: {box_label:?}" /*jdesc.label()*/)); // return the filled out sbox Ok(sbox) diff --git a/sdk/src/jumbf/labels.rs b/sdk/src/jumbf/labels.rs @@ -49,7 +49,7 @@ const JUMBF_PREFIX: &str = "self#jumbf"; // Converts a manifest label to a JUMBF URI. pub(crate) fn to_manifest_uri(manifest_label: &str) -> String { - format!("{}=/{}/{}", JUMBF_PREFIX, MANIFEST_STORE, manifest_label) + format!("{JUMBF_PREFIX}=/{MANIFEST_STORE}/{manifest_label}") } // Converts a manifest label and an assertion label into a JUMBF URI. @@ -203,7 +203,7 @@ pub mod tests { let raw_uri = to_normalized_uri(&absolute_uri); let raw_uri_no_slash = - to_normalized_uri(&format!("{}={}/{}", JUMBF_PREFIX, MANIFEST_STORE, manifest)); + to_normalized_uri(&format!("{JUMBF_PREFIX}={MANIFEST_STORE}/{manifest}")); let raw_empty_uri = to_normalized_uri(empty_uri); @@ -231,7 +231,7 @@ pub mod tests { assert_eq!( assertion_relative, - format!("{}={}/{}", JUMBF_PREFIX, ASSERTIONS, assertion) + format!("{JUMBF_PREFIX}={ASSERTIONS}/{assertion}") ); assert_eq!( Some(assertion.to_string()), diff --git a/sdk/src/jumbf_io.rs b/sdk/src/jumbf_io.rs @@ -192,7 +192,7 @@ pub fn save_jumbf_to_file(data: &[u8], in_path: &Path, out_path: Option<&Path>) let filename_osstr = in_path.file_stem().ok_or(Error::UnsupportedType)?; let filename = filename_osstr.to_str().ok_or(Error::UnsupportedType)?; - let out_name = format!("{}-c2pa.{}", filename, ext); + let out_name = format!("{filename}-c2pa.{ext}"); in_path.to_owned().with_file_name(out_name) } }; diff --git a/sdk/src/manifest.rs b/sdk/src/manifest.rs @@ -1005,7 +1005,7 @@ pub(crate) mod tests { // convert to store let result = manifest.to_store(); - println!("{:?}", result); + println!("{result:?}"); assert!(result.is_err()) } @@ -1037,8 +1037,8 @@ pub(crate) mod tests { let _manifest2 = Manifest::from_store(&store, &store.provenance_label().unwrap()).expect("from_store"); - println!("{}", store); - println!("{:?}", _manifest2); + println!("{store}"); + println!("{_manifest2:?}"); let cbor2: UserCbor = manifest.find_assertion(LABEL).expect("get_assertion"); assert_eq!(cbor, cbor2); } @@ -1165,10 +1165,10 @@ pub(crate) mod tests { // convert to a store and read back again let store = manifest.to_store().expect("to_store"); - println!("{}", store); + println!("{store}"); let active_label = store.provenance_label().unwrap(); let manifest2 = Manifest::from_store(&store, &active_label).expect("from_store"); - println!("{}", manifest2); + println!("{manifest2}"); // now check to see if we have three separate assertions with different instances let action2: Result<Actions> = manifest2.find_assertion_with_instance(Actions::LABEL, 2); assert!(action2.is_ok()); @@ -1317,7 +1317,7 @@ pub(crate) mod tests { #[cfg(feature = "add_thumbnails")] assert!(manifest_store.get_active().unwrap().thumbnail().is_some()); - println!("{}", manifest_store); + println!("{manifest_store}"); } #[cfg(feature = "file_io")] @@ -1340,7 +1340,7 @@ pub(crate) mod tests { manifest.add_ingredient(ingredient); manifest.embed(&output, &output, &signer).expect("embed"); let manifest_store = crate::ManifestStore::from_file(&output).expect("from_file"); - println!("{}", manifest_store); + println!("{manifest_store}"); let manifest = manifest_store.get_active().unwrap(); let ingredient_status = manifest.ingredients()[0].validation_status(); assert_eq!( diff --git a/sdk/src/manifest_store.rs b/sdk/src/manifest_store.rs @@ -201,7 +201,7 @@ impl std::fmt::Display for ManifestStore { let mut json = serde_json::to_string_pretty(self).unwrap_or_default(); fn omit_tag(mut json: String, tag: &str) -> String { - while let Some(index) = json.find(&format!("\"{}\": [", tag)) { + while let Some(index) = json.find(&format!("\"{tag}\": [")) { if let Some(idx2) = json[index..].find(']') { json = format!( "{}\"{}\": \"<omitted>\"{}", @@ -216,7 +216,7 @@ impl std::fmt::Display for ManifestStore { // Make a base64 hash from Vec<u8> values. fn b64_tag(mut json: String, tag: &str) -> String { - while let Some(index) = json.find(&format!("\"{}\": [", tag)) { + while let Some(index) = json.find(&format!("\"{tag}\": [")) { if let Some(idx2) = json[index..].find(']') { let idx3 = json[index..].find('[').unwrap_or_default(); @@ -276,7 +276,7 @@ mod tests { let full_report = manifest_store.to_string(); assert!(!full_report.is_empty()); - println!("{}", full_report); + println!("{full_report}"); } #[test] @@ -320,7 +320,7 @@ mod tests { #[cfg(feature = "file_io")] fn manifest_report_from_file() { let manifest_store = ManifestStore::from_file("tests/fixtures/CA.jpg").unwrap(); - println!("{}", manifest_store); + println!("{manifest_store}"); assert!(manifest_store.active_label().is_some()); assert!(manifest_store.get_active().is_some()); @@ -344,6 +344,6 @@ mod tests { .unwrap(); assert!(!manifest_store.manifests().is_empty()); assert!(manifest_store.validation_status().is_none()); - println!("{}", manifest_store); + println!("{manifest_store}"); } } diff --git a/sdk/src/manifest_store_report.rs b/sdk/src/manifest_store_report.rs @@ -101,7 +101,7 @@ impl ManifestStoreReport { let store = crate::store::Store::load_from_asset(path.as_ref(), true, &mut validation_log)?; let cert_str = store.get_provenance_cert_chain()?; - println!("{}", cert_str); + println!("{cert_str}"); Ok(()) } @@ -168,7 +168,7 @@ impl ManifestStoreReport { let (label, instance) = Claim::assertion_label_from_link(&hashlink); let label = Claim::label_with_instance(&label, instance); - current_token.append(tree, format!("Assertion:{}", label)); + current_token.append(tree, format!("Assertion:{label}")); } // recurse down ingredients @@ -206,7 +206,7 @@ impl ManifestStoreReport { let data = if name_only { asset_name.to_string() } else { - format!("Asset:{}", asset_name) + format!("Asset:{asset_name}") }; current_token.append(tree, data); } @@ -327,7 +327,7 @@ struct SignatureReport { // replace the value of any field in the json string with a given key with the string <omitted> fn omit_tag(mut json: String, tag: &str) -> String { - while let Some(index) = json.find(&format!("\"{}\": [", tag)) { + while let Some(index) = json.find(&format!("\"{tag}\": [")) { if let Some(idx2) = json[index..].find(']') { json = format!( "{}\"{}\": \"<omitted>\"{}", @@ -342,7 +342,7 @@ fn omit_tag(mut json: String, tag: &str) -> String { // make a base64 hash from the value of any field in the json string with key base64 hash fn b64_tag(mut json: String, tag: &str) -> String { - while let Some(index) = json.find(&format!("\"{}\": [", tag)) { + while let Some(index) = json.find(&format!("\"{tag}\": [")) { if let Some(idx2) = json[index..].find(']') { let idx3 = json[index..].find('[').unwrap_or_default(); // ok since we just found it let bytes: Vec<u8> = @@ -372,7 +372,7 @@ mod tests { fn manifest_store_report() { let path = fixture_path("CIE-sig-CA.jpg"); let report = ManifestStoreReport::from_file(path).expect("load_from_asset"); - println!("{}", report); + println!("{report}"); } #[test] diff --git a/sdk/src/status_tracker.rs b/sdk/src/status_tracker.rs @@ -42,7 +42,7 @@ impl LogItem { // add an error value pub fn error(self, err: Error) -> Self { LogItem { - err_val: Some(format!("{:?}", err)), + err_val: Some(format!("{err:?}")), ..self } } @@ -50,7 +50,7 @@ impl LogItem { // add an error value pub fn set_error(self, err: &Error) -> Self { LogItem { - err_val: Some(format!("{:?}", err)), + err_val: Some(format!("{err:?}")), ..self } } diff --git a/sdk/src/store.rs b/sdk/src/store.rs @@ -993,10 +993,10 @@ impl Store { } // wake the ingredients and validate - fn ingredient_checks<'a>( + fn ingredient_checks( store: &Store, claim: &Claim, - asset_data: &ClaimAssetData<'a>, + asset_data: &ClaimAssetData<'_>, validation_log: &mut impl StatusTracker, ) -> Result<()> { let mut num_parent_ofs = 0; @@ -1047,15 +1047,13 @@ impl Store { "ingredient_checks" ) .error(Error::ClaimVerification(format!( - "ingredient: {} is missing", - label + "ingredient: {label} is missing" ))) .validation_status(validation_status::CLAIM_MISSING); validation_log.log( log_item, Some(Error::ClaimVerification(format!( - "ingredient: {} is missing", - label + "ingredient: {label} is missing" ))), )?; } @@ -1150,15 +1148,13 @@ impl Store { "ingredient_checks_async" ) .error(Error::ClaimVerification(format!( - "ingredient: {} is missing", - label + "ingredient: {label} is missing" ))) .validation_status(validation_status::CLAIM_MISSING); validation_log.log( log_item, Some(Error::ClaimVerification(format!( - "ingredient: {} is missing", - label + "ingredient: {label} is missing" ))), )?; } @@ -1204,9 +1200,9 @@ impl Store { /// xmp_str: String containing entire XMP block of the asset /// asset_bytes: bytes of the asset to be verified /// validation_log: If present all found errors are logged and returned, other wise first error causes exit and is returned - pub fn verify_store<'a>( + pub fn verify_store( store: &Store, - asset_data: &ClaimAssetData<'a>, + asset_data: &ClaimAssetData<'_>, validation_log: &mut impl StatusTracker, ) -> Result<()> { let claim = match store.provenance_claim() { @@ -1256,7 +1252,7 @@ impl Store { } let stream_len = stream.seek(SeekFrom::End(0))?; - stream.seek(SeekFrom::Start(0))?; + stream.rewind()?; let mut hashes: Vec<DataHash> = Vec::new(); @@ -1908,9 +1904,9 @@ impl Store { /// asset_path: path to input asset /// validation_log: If present all found errors are logged and returned, otherwise first error causes exit and is returned #[cfg(feature = "file_io")] - pub fn verify_from_path<'a>( + pub fn verify_from_path( &mut self, - asset_path: &'a Path, + asset_path: &'_ Path, validation_log: &mut impl StatusTracker, ) -> Result<()> { Store::verify_store(self, &ClaimAssetData::PathData(asset_path), validation_log) @@ -1974,8 +1970,7 @@ impl Store { resp.status_text() ))), Err(uError::Transport(_)) => Err(Error::RemoteManifestFetch(format!( - "fetch failed: url: {}", - url + "fetch failed: url: {url}" ))), } } @@ -2155,9 +2150,9 @@ impl Store { /// data: reference to bytes of the the file /// verify: if true will run verification checks when loading /// validation_log: If present all found errors are logged and returned, otherwise first error causes exit and is returned - pub fn load_from_memory<'a>( + pub fn load_from_memory( asset_type: &str, - data: &'a [u8], + data: &'_ [u8], verify: bool, validation_log: &mut impl StatusTracker, ) -> Result<Store> { @@ -2916,7 +2911,7 @@ pub mod tests { patch_file(&path, search_bytes, replace_bytes).expect("patch_file"); let mut report = DetailedStatusTracker::default(); let _r = Store::load_from_asset(&path, true, &mut report); // errs are in report - println!("report: {:?}", report); + println!("report: {report:?}"); report } @@ -3087,7 +3082,7 @@ pub mod tests { let ap = fixture_path("CA.jpg"); let mut report = DetailedStatusTracker::new(); let store = Store::load_from_asset(&ap, true, &mut report).expect("load_from_asset"); - println!("store = {}", store); + println!("store = {store}"); } #[test] diff --git a/sdk/src/utils/hash_utils.rs b/sdk/src/utils/hash_utils.rs @@ -203,7 +203,7 @@ pub fn hash_stream_by_alg( }; let data_len = data.seek(SeekFrom::End(0))?; - data.seek(SeekFrom::Start(0))?; + data.rewind()?; let ranges = match exclusions { Some(mut e) if !e.is_empty() => { @@ -377,9 +377,9 @@ pub fn verify_hash(hash: &str, data: &[u8]) -> bool { // Fast implementation for Blake3 hashing that can handle large assets pub fn blake3_from_asset(path: &Path) -> Result<String> { let mut data = File::open(path)?; - data.seek(SeekFrom::Start(0))?; + data.rewind()?; let data_len = data.seek(SeekFrom::End(0))?; - data.seek(SeekFrom::Start(0))?; + data.rewind()?; let mut hasher = blake3::Hasher::new(); diff --git a/sdk/src/utils/xmp_inmemory_utils.rs b/sdk/src/utils/xmp_inmemory_utils.rs @@ -223,12 +223,12 @@ mod tests { fn add_xmp() { let xmp = add_provenance(XMP_DATA, PROVENANCE).expect("adding provenance"); let unicorn = extract_provenance(&xmp); - println!("{}", xmp); + println!("{xmp}"); assert_eq!(unicorn, Some(PROVENANCE.to_string())); let xmp = add_provenance(MIN_XMP, PROVENANCE).expect("adding provenance"); let unicorn = extract_provenance(&xmp); - println!("{}", xmp); + println!("{xmp}"); assert_eq!(unicorn, Some(PROVENANCE.to_string())); } } diff --git a/sdk/tests/integration.rs b/sdk/tests/integration.rs @@ -91,7 +91,7 @@ mod integration_1 { // read our new file with embedded manifest let manifest_store = ManifestStore::from_file(&output_path)?; - println!("{}", manifest_store); + println!("{manifest_store}"); assert!(manifest_store.get_active().is_some()); if let Some(manifest) = manifest_store.get_active() {