diff --git a/benches/byod.rs b/benches/byod.rs index e5e3266e..30171cc4 100644 --- a/benches/byod.rs +++ b/benches/byod.rs @@ -40,9 +40,9 @@ mod benchmark { #[cfg(feature = "experimental")] mod benchmark { + use criterion::{BenchmarkId, Criterion}; + use ion_rs::{v1_1::BinaryWriter, Element, *}; use std::{env, fs, hint::black_box}; - use criterion::{Criterion, BenchmarkId}; - use ion_rs::{v1_1::BinaryWriter, *, Element}; pub fn bench_byod_full(c: &mut Criterion) { let Some(file) = env::var("ION_BENCH").ok() else { @@ -56,15 +56,12 @@ mod benchmark { read_group.measurement_time(std::time::Duration::from_secs(30)); // Read the provided data as-is with an encoding-agnostic reader. - read_group.bench_with_input( - BenchmarkId::new("full-read", &file), - &data, - |b, data| b.iter(|| { - let reader = Reader::new(AnyEncoding, data) - .expect("Unable to create reader"); + read_group.bench_with_input(BenchmarkId::new("full-read", &file), &data, |b, data| { + b.iter(|| { + let reader = Reader::new(AnyEncoding, data).expect("Unable to create reader"); full_read(reader); }) - ); + }); // Convert the provided data into an ion 1.0 stream, and then measure the performance of // reading the stream-equivalent data using a 1.0 reader. @@ -75,11 +72,10 @@ mod benchmark { |b, data| { // Benchmark Read of known 1.0 data. b.iter(|| { - let reader = Reader::new(AnyEncoding, data) - .expect("Unable to create reader"); + let reader = Reader::new(AnyEncoding, data).expect("Unable to create reader"); full_read(reader); }); - } + }, ); drop(one_oh_data); @@ -91,11 +87,10 @@ mod benchmark { &delimited_data, |b, data| { b.iter(|| { - let reader = Reader::new(AnyEncoding, data) - .expect("unable to create reader"); + let reader = Reader::new(AnyEncoding, data).expect("unable to create reader"); full_read(reader); }); - } + }, ); drop(delimited_data); @@ -107,11 +102,10 @@ mod benchmark { &prefixed_data, |b, data| { b.iter(|| { - let reader = Reader::new(AnyEncoding, data) - .expect("unable to create reader"); + let reader = Reader::new(AnyEncoding, data).expect("unable to create reader"); full_read(reader); }); - } + }, ); drop(prefixed_data); @@ -123,11 +117,10 @@ mod benchmark { &inlined_data, |b, data| { b.iter(|| { - let reader = Reader::new(AnyEncoding, data) - .expect("unable to create reader"); + let reader = Reader::new(AnyEncoding, data).expect("unable to create reader"); full_read(reader); }); - } + }, ); drop(inlined_data); @@ -139,11 +132,10 @@ mod benchmark { &referenced_data, |b, data| { b.iter(|| { - let reader = Reader::new(AnyEncoding, data) - .expect("unable to create reader"); + let reader = Reader::new(AnyEncoding, data).expect("unable to create reader"); full_read(reader); }); - } + }, ); drop(referenced_data); @@ -162,14 +154,13 @@ mod benchmark { let elems = Element::read_all(data).expect("unable to read elements"); b.iter(|| { let buffer = Vec::::with_capacity(size); - let mut writer = BinaryWriter::new(v1_1::Binary, buffer).expect("unable to create writer"); + let mut writer = + BinaryWriter::new(v1_1::Binary, buffer).expect("unable to create writer"); for elem in &elems { - writer - .write(elem) - .expect("unable to write value"); + writer.write(elem).expect("unable to write value"); } }); - } + }, ); // Read the original data using the Element API, and re-write it to an ion 1.1 stream using @@ -182,7 +173,8 @@ mod benchmark { let elems = Element::read_all(data).expect("unable to read elements"); b.iter(|| { let buffer = Vec::::with_capacity(size); - let mut writer = BinaryWriter::new(v1_1::Binary, buffer).expect("unable to create writer"); + let mut writer = + BinaryWriter::new(v1_1::Binary, buffer).expect("unable to create writer"); for elem in &elems { writer .value_writer() @@ -191,7 +183,7 @@ mod benchmark { .expect("unable to write value"); } }); - } + }, ); // Read the original data using the Element API, and re-write it to an ion 1.1 stream using @@ -204,7 +196,8 @@ mod benchmark { let elems = Element::read_all(data).expect("unable to read elements"); b.iter(|| { let buffer = Vec::::with_capacity(size); - let mut writer = BinaryWriter::new(v1_1::Binary, buffer).expect("unable to create writer"); + let mut writer = + BinaryWriter::new(v1_1::Binary, buffer).expect("unable to create writer"); for elem in &elems { writer .value_writer() @@ -213,7 +206,7 @@ mod benchmark { .expect("unable to write value"); } }); - } + }, ); // Read the original data using the Element API, and re-write it to an ion 1.1 stream using @@ -226,7 +219,8 @@ mod benchmark { let elems = Element::read_all(data).expect("unable to read elements"); b.iter(|| { let buffer = Vec::::with_capacity(size); - let mut writer = Writer::new(v1_1::Binary, buffer).expect("unable to create writer"); + let mut writer = + Writer::new(v1_1::Binary, buffer).expect("unable to create writer"); for elem in &elems { writer .value_writer() @@ -235,7 +229,7 @@ mod benchmark { .expect("unable to write value"); } }); - } + }, ); // Read the original data using the Element API, and re-write it to an ion 1.0 stream using @@ -248,15 +242,14 @@ mod benchmark { let elems = Element::read_all(data).expect("unable to read elements"); b.iter(|| { let buffer = Vec::::with_capacity(size); - let mut writer = Writer::new(v1_0::Binary, buffer).expect("unable to create writer"); + let mut writer = + Writer::new(v1_0::Binary, buffer).expect("unable to create writer"); for elem in &elems { - writer - .write(elem) - .expect("unable to write value"); + writer.write(elem).expect("unable to write value"); } let _ = writer.close(); }); - } + }, ); write_group.finish(); @@ -274,9 +267,7 @@ mod benchmark { .write(elem) .expect("unable to write value"); } - writer - .close() - .expect("unable to close writer") + writer.close().expect("unable to close writer") } fn rewrite_delimited_containers(data: &Vec) -> Vec { @@ -291,9 +282,7 @@ mod benchmark { .write(elem) .expect("unable to write value"); } - writer - .close() - .expect("unable to close writer") + writer.close().expect("unable to close writer") } fn rewrite_inline_symbols(data: &Vec) -> Vec { @@ -310,9 +299,7 @@ mod benchmark { .write(elem) .expect("unable to write value"); } - writer - .close() - .expect("unable to close writer") + writer.close().expect("unable to close writer") } fn rewrite_referenced_symbols(data: &Vec) -> Vec { @@ -329,9 +316,7 @@ mod benchmark { .write(elem) .expect("unable to write value"); } - writer - .close() - .expect("unable to close writer") + writer.close().expect("unable to close writer") } fn rewrite_inline_annotations(data: &Vec) -> Vec { @@ -346,9 +331,7 @@ mod benchmark { .write(elem) .expect("unable to write value"); } - writer - .close() - .expect("unable to close writer") + writer.close().expect("unable to close writer") } fn rewrite_as_1_0(data: &Vec) -> Vec { @@ -357,7 +340,9 @@ mod benchmark { let elems = Element::read_all(data).expect("unable to read elements"); // Write data as 1.0 let buffer = Vec::::with_capacity(size); - elems.encode_to(buffer, v1_0::Binary).expect("unable to re-encode elements") + elems + .encode_to(buffer, v1_0::Binary) + .expect("unable to re-encode elements") } fn rewrite_as_1_1(data: &Vec) -> Vec { @@ -366,7 +351,9 @@ mod benchmark { let elems = Element::read_all(data).expect("unable to read elements"); // Write data as 1.1 let buffer = Vec::::with_capacity(size); - elems.encode_to(buffer, v1_1::Binary).expect("unable to re-encode elements") + elems + .encode_to(buffer, v1_1::Binary) + .expect("unable to re-encode elements") } #[inline] diff --git a/benches/encoding_primitives.rs b/benches/encoding_primitives.rs index 5a6648c5..467bc315 100644 --- a/benches/encoding_primitives.rs +++ b/benches/encoding_primitives.rs @@ -11,7 +11,7 @@ mod benchmark { #[cfg(feature = "experimental")] mod benchmark { use criterion::{black_box, Criterion}; - use ion_rs::{IonResult, EncodingContext}; + use ion_rs::{EncodingContext, IonResult}; use rand::prelude::StdRng; use rand::{distributions::Uniform, Rng, SeedableRng}; use std::io; @@ -73,7 +73,8 @@ mod benchmark { b.iter(|| { let encoding_context = EncodingContext::empty(); let mut decoded_length: usize = 0; - let mut input = BinaryBuffer::new(encoding_context.get_ref(), encoded_var_uints.as_slice()); + let mut input = + BinaryBuffer::new(encoding_context.get_ref(), encoded_var_uints.as_slice()); for _ in 0..unsigned_values.len() { let (var_uint, remaining) = input.read_var_uint().unwrap(); input = remaining; @@ -96,7 +97,8 @@ mod benchmark { b.iter(|| { let encoding_context = EncodingContext::empty(); let mut decoded_length: usize = 0; - let mut input = BinaryBuffer::new(encoding_context.get_ref(), encoded_var_ints.as_slice()); + let mut input = + BinaryBuffer::new(encoding_context.get_ref(), encoded_var_ints.as_slice()); for _ in 0..unsigned_values.len() { let (var_int, remaining) = input.read_var_int().unwrap(); input = remaining; @@ -122,7 +124,8 @@ mod benchmark { b.iter(|| { let encoding_context = EncodingContext::empty(); let mut decoded_length: usize = 0; - let mut input = BinaryBuffer::new(encoding_context.get_ref(), encoded_flex_uints.as_slice()); + let mut input = + BinaryBuffer::new(encoding_context.get_ref(), encoded_flex_uints.as_slice()); for _ in 0..unsigned_values.len() { let (flex_uint, remaining) = input.read_flex_uint().unwrap(); input = remaining; @@ -145,7 +148,8 @@ mod benchmark { b.iter(|| { let encoding_context = EncodingContext::empty(); let mut decoded_length: usize = 0; - let mut input = BinaryBuffer::new(encoding_context.get_ref(), encoded_flex_ints.as_slice()); + let mut input = + BinaryBuffer::new(encoding_context.get_ref(), encoded_flex_ints.as_slice()); for _ in 0..unsigned_values.len() { let (flex_int, remaining) = input.read_flex_int().unwrap(); input = remaining; @@ -164,7 +168,8 @@ mod benchmark { VarUInt::write_u64(&mut encoded_values_buffer, *value)?; } let mut decoded_values = Vec::new(); - let mut input = BinaryBuffer::new(encoding_context.get_ref(), encoded_values_buffer.as_slice()); + let mut input = + BinaryBuffer::new(encoding_context.get_ref(), encoded_values_buffer.as_slice()); for _ in 0..unsigned_values.len() { let (var_uint, remaining) = input.read_var_uint()?; input = remaining; @@ -181,7 +186,8 @@ mod benchmark { VarInt::write_i64(&mut encoded_values_buffer, *value)?; } let mut decoded_values = Vec::new(); - let mut input = BinaryBuffer::new(encoding_context.get_ref(), encoded_values_buffer.as_slice()); + let mut input = + BinaryBuffer::new(encoding_context.get_ref(), encoded_values_buffer.as_slice()); for _ in 0..signed_values.len() { let (var_int, remaining) = input.read_var_int()?; input = remaining; @@ -198,7 +204,8 @@ mod benchmark { FlexUInt::write(&mut encoded_values_buffer, *value)?; } let mut decoded_values = Vec::new(); - let mut input = BinaryBuffer::new(encoding_context.get_ref(), encoded_values_buffer.as_slice()); + let mut input = + BinaryBuffer::new(encoding_context.get_ref(), encoded_values_buffer.as_slice()); for _ in 0..unsigned_values.len() { let (flex_uint, remaining) = input.read_flex_uint()?; input = remaining; @@ -215,7 +222,8 @@ mod benchmark { FlexInt::write_i64(&mut encoded_values_buffer, *value)?; } let mut decoded_values = Vec::new(); - let mut input = BinaryBuffer::new(encoding_context.get_ref(), encoded_values_buffer.as_slice()); + let mut input = + BinaryBuffer::new(encoding_context.get_ref(), encoded_values_buffer.as_slice()); for _ in 0..signed_values.len() { let (flex_int, remaining) = input.read_flex_int()?; input = remaining; diff --git a/benches/write_many_structs.rs b/benches/write_many_structs.rs index 49499ade..a1131988 100644 --- a/benches/write_many_structs.rs +++ b/benches/write_many_structs.rs @@ -10,9 +10,9 @@ mod benchmark { #[cfg(feature = "experimental")] mod benchmark { - use std::hint::black_box; use criterion::Criterion; use ion_rs::{v1_0, v1_1, IonResult, RawSymbolRef, SequenceWriter, StructWriter, ValueWriter}; + use std::hint::black_box; fn write_struct_with_string_values(value_writer: impl ValueWriter) -> IonResult<()> { let mut struct_ = value_writer.struct_writer()?; diff --git a/src/lazy/binary/raw/v1_1/binary_buffer.rs b/src/lazy/binary/raw/v1_1/binary_buffer.rs index 9d6d2c57..a657da70 100644 --- a/src/lazy/binary/raw/v1_1/binary_buffer.rs +++ b/src/lazy/binary/raw/v1_1/binary_buffer.rs @@ -258,13 +258,20 @@ impl<'a> BinaryBuffer<'a> { Ok((value, remaining_input)) } - pub fn read_fixed_uint_as_lazy_value(self, encoding: BinaryValueEncoding) -> ParseResult<'a, LazyRawBinaryValue_1_1<'a>> { + pub fn read_fixed_uint_as_lazy_value( + self, + encoding: BinaryValueEncoding, + ) -> ParseResult<'a, LazyRawBinaryValue_1_1<'a>> { let size_in_bytes = match encoding { BinaryValueEncoding::UInt8 => 1, BinaryValueEncoding::UInt16 => 2, BinaryValueEncoding::UInt32 => 4, BinaryValueEncoding::UInt64 => 8, - _ => return IonResult::illegal_operation(format!("invalid binary encoding for fixed uint: {encoding:?}")), + _ => { + return IonResult::illegal_operation(format!( + "invalid binary encoding for fixed uint: {encoding:?}" + )) + } }; if self.len() < size_in_bytes { diff --git a/src/lazy/binary/raw/v1_1/e_expression.rs b/src/lazy/binary/raw/v1_1/e_expression.rs index 6ce6d788..9a99a5a0 100644 --- a/src/lazy/binary/raw/v1_1/e_expression.rs +++ b/src/lazy/binary/raw/v1_1/e_expression.rs @@ -328,11 +328,10 @@ impl<'top> Iterator for BinaryEExpArgsInputIter<'top> { remaining, ) } - enc@ ParameterEncoding::UInt8 | - enc@ ParameterEncoding::UInt16 | - enc@ ParameterEncoding::UInt32 | - enc@ ParameterEncoding::UInt64 - => { + enc @ ParameterEncoding::UInt8 + | enc @ ParameterEncoding::UInt16 + | enc @ ParameterEncoding::UInt32 + | enc @ ParameterEncoding::UInt64 => { let binary_enc = try_or_some_err!(enc.try_into()); let (fixed_uint_lazy_value, remaining) = try_or_some_err! { self.remaining_args_buffer.read_fixed_uint_as_lazy_value(binary_enc) diff --git a/src/lazy/binary/raw/value.rs b/src/lazy/binary/raw/value.rs index 8c1d2f18..0b1069d9 100644 --- a/src/lazy/binary/raw/value.rs +++ b/src/lazy/binary/raw/value.rs @@ -555,8 +555,8 @@ impl<'top> LazyRawBinaryValue_1_0<'top> { 1 => true, invalid => { return IonResult::decoding_error(format!( - "found a boolean value with an illegal representation (must be 0 or 1): {invalid}", - )) + "found a boolean value with an illegal representation (must be 0 or 1): {invalid}", + )) } }; Ok(RawValueRef::Bool(value)) diff --git a/src/lazy/encoder/binary/v1_1/container_writers.rs b/src/lazy/encoder/binary/v1_1/container_writers.rs index 89407fa8..0e01e1cf 100644 --- a/src/lazy/encoder/binary/v1_1/container_writers.rs +++ b/src/lazy/encoder/binary/v1_1/container_writers.rs @@ -1,7 +1,9 @@ use bumpalo::collections::Vec as BumpVec; use bumpalo::Bump as BumpAllocator; -use crate::lazy::encoder::binary::v1_1::value_writer::{BinaryEExpParameterValueWriter_1_1, BinaryValueWriter_1_1}; +use crate::lazy::encoder::binary::v1_1::value_writer::{ + BinaryEExpParameterValueWriter_1_1, BinaryValueWriter_1_1, +}; use crate::lazy::encoder::binary::v1_1::{flex_sym::FlexSym, flex_uint::FlexUInt}; use crate::lazy::encoder::value_writer::internal::{ EExpWriterInternal, FieldEncoder, MakeValueWriter, @@ -520,7 +522,9 @@ impl<'top> EExpWriter for BinaryEExpWriter_1_1<'_, 'top> { } fn expr_group_writer(&mut self) -> IonResult> { - let param = self.signature_iter.expect_next_parameter() + let param = self + .signature_iter + .expect_next_parameter() .and_then(|p| p.expect_variadic())?; let writer = BinaryExprGroupWriter::new( diff --git a/src/lazy/encoder/binary/v1_1/fixed_uint.rs b/src/lazy/encoder/binary/v1_1/fixed_uint.rs index 9924e853..9a606952 100644 --- a/src/lazy/encoder/binary/v1_1/fixed_uint.rs +++ b/src/lazy/encoder/binary/v1_1/fixed_uint.rs @@ -1,7 +1,7 @@ use std::io::Write; -use num_traits::{PrimInt, Unsigned}; use ice_code::ice as cold_path; +use num_traits::{PrimInt, Unsigned}; use crate::decimal::coefficient::Coefficient; use crate::lazy::encoder::binary::v1_1::fixed_int::{ @@ -68,15 +68,21 @@ impl FixedUInt { } #[inline] - pub(crate) fn write_as_uint(output: &mut impl Write, value: impl Into) -> IonResult<()> { + pub(crate) fn write_as_uint( + output: &mut impl Write, + value: impl Into, + ) -> IonResult<()> { let size_in_bytes = std::mem::size_of::(); let value: u128 = value.into().data; let encoded_bytes = value.to_le_bytes(); - let max_value: u128 = num_traits::cast::cast(I::max_value()) - .ok_or(IonError::encoding_error("Unable to represent bounds for value as 128bit value"))?; + let max_value: u128 = num_traits::cast::cast(I::max_value()).ok_or( + IonError::encoding_error("Unable to represent bounds for value as 128bit value"), + )?; if !(0..=max_value).contains(&value) { - return IonResult::encoding_error(format!("provided unsigned integer value does not fit within {size_in_bytes} byte(s)")); + return IonResult::encoding_error(format!( + "provided unsigned integer value does not fit within {size_in_bytes} byte(s)" + )); } output.write_all(&encoded_bytes[..size_in_bytes])?; diff --git a/src/lazy/encoder/binary/v1_1/value_writer.rs b/src/lazy/encoder/binary/v1_1/value_writer.rs index 443b8a77..8fd8a72d 100644 --- a/src/lazy/encoder/binary/v1_1/value_writer.rs +++ b/src/lazy/encoder/binary/v1_1/value_writer.rs @@ -1011,7 +1011,7 @@ impl<'value, 'top> BinaryEExpParameterValueWriter_1_1<'value, 'top> { macros: &'a MacroTable, parameter: Option<&'a Parameter>, ) -> BinaryEExpParameterValueWriter_1_1<'a, 'b> { - BinaryEExpParameterValueWriter_1_1{ + BinaryEExpParameterValueWriter_1_1 { allocator, buffer, value_writer_config, @@ -1041,8 +1041,8 @@ impl<'value, 'top> ValueWriter for BinaryEExpParameterValueWriter_1_1<'value, 't // parameter if the parameter is tagless. fn write_symbol(self, value: impl AsRawSymbolRef) -> IonResult<()> { - use crate::IonError; use crate::lazy::expanded::template::ParameterEncoding; + use crate::IonError; // TODO: Support tagless types. let _param = self @@ -1061,9 +1061,9 @@ impl<'value, 'top> ValueWriter for BinaryEExpParameterValueWriter_1_1<'value, 't } fn write_i64(self, value: i64) -> IonResult<()> { + use crate::lazy::expanded::template::ParameterEncoding as PE; use crate::IonError; use crate::UInt; - use crate::lazy::expanded::template::ParameterEncoding as PE; #[inline(never)] fn error_context(name: &str, err: impl std::error::Error) -> IonError { @@ -1101,9 +1101,9 @@ impl<'value, 'top> ValueWriter for BinaryEExpParameterValueWriter_1_1<'value, 't ); value_writer.write_i64(value) } - encoding => IonResult::encoding_error( - format!("value does not satisfy encoding type {encoding}") - ), + encoding => IonResult::encoding_error(format!( + "value does not satisfy encoding type {encoding}" + )), }; result.map_err(|err| error_context(param.name(), err)) @@ -1111,8 +1111,8 @@ impl<'value, 'top> ValueWriter for BinaryEExpParameterValueWriter_1_1<'value, 't fn write_int(self, value: &Int) -> IonResult<()> { use crate::lazy::expanded::template::ParameterEncoding as PE; - use crate::UInt; use crate::IonError; + use crate::UInt; #[inline(never)] fn error_context(name: &str, err: impl std::error::Error) -> IonError { @@ -1150,17 +1150,17 @@ impl<'value, 'top> ValueWriter for BinaryEExpParameterValueWriter_1_1<'value, 't ); value_writer.write_int(value) } - encoding => IonResult::encoding_error( - format!("value does not satisfy encoding type {encoding}") - ), + encoding => IonResult::encoding_error(format!( + "value does not satisfy encoding type {encoding}" + )), }; result.map_err(|err| error_context(param.name(), err)) } fn write_f32(self, value: f32) -> IonResult<()> { - use crate::IonError; use crate::lazy::expanded::template::ParameterEncoding; + use crate::IonError; // TODO: Support tagless types. let _param = self @@ -1179,8 +1179,8 @@ impl<'value, 'top> ValueWriter for BinaryEExpParameterValueWriter_1_1<'value, 't } fn write_f64(self, value: f64) -> IonResult<()> { - use crate::IonError; use crate::lazy::expanded::template::ParameterEncoding; + use crate::IonError; // TODO: Support tagless types. let _param = self @@ -1199,8 +1199,8 @@ impl<'value, 'top> ValueWriter for BinaryEExpParameterValueWriter_1_1<'value, 't } fn list_writer(self) -> IonResult { - use crate::IonError; use crate::lazy::expanded::template::ParameterEncoding; + use crate::IonError; let _param = self .parameter @@ -1219,8 +1219,8 @@ impl<'value, 'top> ValueWriter for BinaryEExpParameterValueWriter_1_1<'value, 't } fn sexp_writer(self) -> IonResult { - use crate::IonError; use crate::lazy::expanded::template::ParameterEncoding; + use crate::IonError; let _param = self .parameter @@ -1239,8 +1239,8 @@ impl<'value, 'top> ValueWriter for BinaryEExpParameterValueWriter_1_1<'value, 't } fn struct_writer(self) -> IonResult { - use crate::IonError; use crate::lazy::expanded::template::ParameterEncoding; + use crate::IonError; let _param = self .parameter @@ -1259,11 +1259,11 @@ impl<'value, 'top> ValueWriter for BinaryEExpParameterValueWriter_1_1<'value, 't } fn eexp_writer<'a>(self, macro_id: impl MacroIdLike<'a>) -> IonResult - where - Self: 'a + where + Self: 'a, { - use crate::IonError; use crate::lazy::expanded::template::ParameterEncoding; + use crate::IonError; let _param = self .parameter @@ -1296,11 +1296,11 @@ impl<'top> AnnotatableWriter for BinaryEExpParameterValueWriter_1_1<'_, 'top> { Self: 'a, { Ok(BinaryAnnotatedValueWriter_1_1::new( - self.allocator, - self.buffer, - annotations.into_annotations_vec(), - self.value_writer_config, - self.macros, + self.allocator, + self.buffer, + annotations.into_annotations_vec(), + self.value_writer_config, + self.macros, )) } } @@ -3266,9 +3266,7 @@ mod tests { encoding_test( |writer: &mut LazyRawBinaryWriter_1_1<&mut Vec>| { let mut args = writer.eexp_writer(7)?; // sum - args - .write_i64(5)? - .write_i64(6)?; + args.write_i64(5)?.write_i64(6)?; args.close() }, &[ @@ -3284,11 +3282,8 @@ mod tests { fn write_system_macro_invocation() -> IonResult<()> { encoding_test( |writer: &mut LazyRawBinaryWriter_1_1<&mut Vec>| { - let mut args = - writer.eexp_writer(MacroIdRef::SystemAddress(system_macros::SUM))?; - args - .write_i64(5)? - .write_i64(6)?; + let mut args = writer.eexp_writer(MacroIdRef::SystemAddress(system_macros::SUM))?; + args.write_i64(5)?.write_i64(6)?; args.close() }, &[ diff --git a/src/lazy/encoder/writer.rs b/src/lazy/encoder/writer.rs index 65c994cf..87103168 100644 --- a/src/lazy/encoder/writer.rs +++ b/src/lazy/encoder/writer.rs @@ -473,10 +473,7 @@ impl ApplicationValueWriter<'_, BinaryValueWriter_1_1<'_, '_>> { self } - pub fn with_field_name_encoding( - mut self, - field_name_encoding: FieldNameEncoding, - ) -> Self { + pub fn with_field_name_encoding(mut self, field_name_encoding: FieldNameEncoding) -> Self { self.value_writer_config = self .value_writer_config .with_field_name_encoding(field_name_encoding); @@ -1034,7 +1031,8 @@ impl EExpWriter for ApplicationEExpWriter<'_, V> { } fn expr_group_writer(&mut self) -> IonResult> { - let _param = self.expect_next_parameter() + let _param = self + .expect_next_parameter() .and_then(|p| p.expect_variadic())?; // TODO: Pass `Parameter` to group writer so it can do its own validation self.raw_eexp_writer.expr_group_writer() @@ -1452,6 +1450,7 @@ mod tests { #[test] fn tagless_uint8_encoding() -> IonResult<()> { let macro_source = "(macro foo (uint8::x) (%x))"; + #[rustfmt::skip] let expected: &[u8] = &[ 0xE0, 0x01, 0x01, 0xEA, // IVM 0xE7, 0xF9, 0x24, 0x69, 0x6F, 0x6E, // $ion:: @@ -1518,8 +1517,12 @@ mod tests { #[case::uint16("(macro foo (uint16::x) (%x))", 5, "5")] #[case::uint32("(macro foo (uint32::x) (%x))", 5, "5")] #[case::uint64("(macro foo (uint64::x) (%x))", 5, "5")] - fn tagless_uint_encoding(#[case] macro_source: &str, #[case] input: i64, #[case] expected: &str) -> IonResult<()> { - use crate::{Int, Element}; + fn tagless_uint_encoding( + #[case] macro_source: &str, + #[case] input: i64, + #[case] expected: &str, + ) -> IonResult<()> { + use crate::{Element, Int}; // write_int @@ -1556,7 +1559,10 @@ mod tests { #[case::uint16("(macro foo (uint16::x) (%x))", 5u16)] #[case::uint32("(macro foo (uint32::x) (%x))", 5u32)] #[case::uint64("(macro foo (uint64::x) (%x))", 5u64)] - fn tagless_uint_encoding_write_int_fails(#[case] macro_source: &str, #[case] input: T) -> IonResult<()> { + fn tagless_uint_encoding_write_int_fails( + #[case] macro_source: &str, + #[case] input: T, + ) -> IonResult<()> { let max_int = T::max_value(); let max_int_plus_one = num_traits::cast::cast::<_, i128>(max_int).unwrap() + 1i128; let neg_input = -num_traits::cast::cast::<_, i128>(input).unwrap(); @@ -1581,7 +1587,10 @@ mod tests { #[case::uint8("(macro foo (uint8::x) (%x))", 5u8)] #[case::uint16("(macro foo (uint16::x) (%x))", 5u16)] #[case::uint32("(macro foo (uint32::x) (%x))", 5u32)] - fn tagless_uint_encoding_write_i64_fails(#[case] macro_source: &str, #[case] input: T) -> IonResult<()> { + fn tagless_uint_encoding_write_i64_fails( + #[case] macro_source: &str, + #[case] input: T, + ) -> IonResult<()> { let max_int = T::max_value(); let max_int_plus_one = num_traits::cast::cast::<_, i128>(max_int).unwrap() + 1i128; let neg_input = -num_traits::cast::cast::<_, i128>(input).unwrap(); diff --git a/src/lazy/expanded/e_expression.rs b/src/lazy/expanded/e_expression.rs index 8c1becc5..d052e623 100644 --- a/src/lazy/expanded/e_expression.rs +++ b/src/lazy/expanded/e_expression.rs @@ -8,11 +8,11 @@ use crate::element::iterators::SymbolsIterator; use crate::lazy::decoder::{Decoder, RawValueExpr}; use crate::lazy::expanded::compiler::{ExpansionAnalysis, ExpansionSingleton}; use crate::lazy::expanded::macro_evaluator::{ - AnnotateExpansion, ConditionalExpansion, DeltaExpansion, EExpressionArgGroup, ExprGroupExpansion, - FlattenExpansion, IsExhaustedIterator, MacroExpansion, MacroExpansionKind, MacroExpr, - MacroExprArgsIterator, MakeDecimalExpansion, MakeFieldExpansion, MakeStructExpansion, - MakeTextExpansion, MakeTimestampExpansion, RawEExpression, RepeatExpansion, SumExpansion, TemplateExpansion, - ValueExpr, + AnnotateExpansion, ConditionalExpansion, DeltaExpansion, EExpressionArgGroup, + ExprGroupExpansion, FlattenExpansion, IsExhaustedIterator, MacroExpansion, MacroExpansionKind, + MacroExpr, MacroExprArgsIterator, MakeDecimalExpansion, MakeFieldExpansion, + MakeStructExpansion, MakeTextExpansion, MakeTimestampExpansion, RawEExpression, + RepeatExpansion, SumExpansion, TemplateExpansion, ValueExpr, }; use crate::lazy::expanded::macro_table::{MacroKind, MacroRef}; use crate::lazy::expanded::template::TemplateMacroRef; @@ -162,14 +162,10 @@ impl<'top, D: Decoder> EExpression<'top, D> { MacroKind::Delta => MacroExpansionKind::Delta(DeltaExpansion::new( self.context(), environment, - arguments + arguments, )), - MacroKind::Repeat => { - MacroExpansionKind::Repeat(RepeatExpansion::new(arguments)) - } - MacroKind::Sum => { - MacroExpansionKind::Sum(SumExpansion::new(arguments)) - } + MacroKind::Repeat => MacroExpansionKind::Repeat(RepeatExpansion::new(arguments)), + MacroKind::Sum => MacroExpansionKind::Sum(SumExpansion::new(arguments)), }; Ok(MacroExpansion::new( self.context(), diff --git a/src/lazy/expanded/macro_evaluator.rs b/src/lazy/expanded/macro_evaluator.rs index 097606ec..73074a73 100644 --- a/src/lazy/expanded/macro_evaluator.rs +++ b/src/lazy/expanded/macro_evaluator.rs @@ -34,12 +34,14 @@ use crate::lazy::str_ref::StrRef; use crate::lazy::text::raw::v1_1::arg_group::EExpArg; use crate::lazy::text::raw::v1_1::reader::{MacroIdLike, MacroIdRef}; use crate::result::IonFailure; +use crate::types::{ + HasDay, HasFractionalSeconds, HasHour, HasMinute, HasMonth, HasOffset, HasSeconds, HasYear, + Timestamp, TimestampBuilder, +}; use crate::{ - Decimal, ExpandedValueRef, ExpandedValueSource, Int, IonError, IonResult, - LazyExpandedField, LazyExpandedFieldName, LazyExpandedStruct, LazyStruct, - LazyValue, Span, SymbolRef, ValueRef + Decimal, ExpandedValueRef, ExpandedValueSource, Int, IonError, IonResult, LazyExpandedField, + LazyExpandedFieldName, LazyExpandedStruct, LazyStruct, LazyValue, Span, SymbolRef, ValueRef, }; -use crate::types::{HasDay, HasFractionalSeconds, HasHour, HasMinute, HasMonth, HasOffset, HasSeconds, HasYear, Timestamp, TimestampBuilder}; pub trait IsExhaustedIterator<'top, D: Decoder>: Copy + Clone + Debug + Iterator>> @@ -590,11 +592,15 @@ impl<'top, D: Decoder> MacroExpansion<'top, D> { match &mut self.kind { Template(template_expansion) => template_expansion.next(context, environment), ExprGroup(expr_group_expansion) => expr_group_expansion.next(context, environment), - MakeDecimal(make_decimal_expansion) => make_decimal_expansion.next(context, environment), + MakeDecimal(make_decimal_expansion) => { + make_decimal_expansion.next(context, environment) + } MakeString(expansion) | MakeSymbol(expansion) => expansion.make_text_value(context), MakeField(make_field_expansion) => make_field_expansion.next(context, environment), MakeStruct(make_struct_expansion) => make_struct_expansion.next(context, environment), - MakeTimestamp(make_timestamp_expansion) => make_timestamp_expansion.next(context, environment), + MakeTimestamp(make_timestamp_expansion) => { + make_timestamp_expansion.next(context, environment) + } Annotate(annotate_expansion) => annotate_expansion.next(context, environment), Flatten(flatten_expansion) => flatten_expansion.next(), Conditional(cardinality_test_expansion) => cardinality_test_expansion.next(environment), @@ -1196,24 +1202,20 @@ macro_rules! sysmacro_arg_info { // functionality to expand e-exp and validate integer types. Can be expanded for more types as // needed. struct SystemMacroArgument<'top, A: AsRef, D: Decoder>(A, ValueExpr<'top, D>); -impl <'top, A: AsRef, D: Decoder> SystemMacroArgument<'top, A, D> { +impl<'top, A: AsRef, D: Decoder> SystemMacroArgument<'top, A, D> { /// Expands the current [`ValueExpr`] for the argument and verifies that it expands to 0 or 1 /// value. Returns the value as a ValueRef. fn try_get_valueref(&self, env: Environment<'top, D>) -> IonResult>> { - let argument_name= self.0.as_ref(); + let argument_name = self.0.as_ref(); let arg = match self.1 { - ValueExpr::ValueLiteral(value_literal) => { - Some(value_literal.read_resolved()?) - } + ValueExpr::ValueLiteral(value_literal) => Some(value_literal.read_resolved()?), ValueExpr::MacroInvocation(invocation) => { let mut evaluator = MacroEvaluator::new_with_environment(env); evaluator.push(invocation.expand()?); let int_arg = match evaluator.next()? { None => None, - Some(value) => { - Some(value.read_resolved()?) - } + Some(value) => Some(value.read_resolved()?), }; if !evaluator.is_empty() && evaluator.next()?.is_some() { @@ -1228,13 +1230,12 @@ impl <'top, A: AsRef, D: Decoder> SystemMacroArgument<'top, A, D> { /// Given a [`ValueExpr`], this function will expand it into its underlying value; An /// error is return if the value does not expand to exactly one Int. fn get_integer(&self, env: Environment<'top, D>) -> IonResult { - let argument_name= self.0.as_ref(); + let argument_name = self.0.as_ref(); let value_ref = self.try_get_valueref(env)?; value_ref .ok_or_else(|| IonError::decoding_error(format!("expected integer value for '{argument_name}' parameter but the provided argument contained no value.")))? .expect_int() } - } // ===== Implementation of the `make_decimal` macro === @@ -1259,13 +1260,28 @@ impl<'top, D: Decoder> MakeDecimalExpansion<'top, D> { } // Arguments should be: (coefficient exponent) // Both coefficient and exponent should evaluate to a single integer value. - let coeff_expr = self.arguments.next().ok_or(IonError::decoding_error("`make_decimal` takes 2 integer arguments; found 0 arguments"))?; - let coefficient = SystemMacroArgument("Coefficient", coeff_expr?).get_integer(environment).map_err(error_context)?; + let coeff_expr = self.arguments.next().ok_or(IonError::decoding_error( + "`make_decimal` takes 2 integer arguments; found 0 arguments", + ))?; + let coefficient = SystemMacroArgument("Coefficient", coeff_expr?) + .get_integer(environment) + .map_err(error_context)?; - let expo_expr = self.arguments.next().ok_or(IonError::decoding_error("`make_decimal` takes 2 integer arguments; found only 1 argument"))?; - let exponent = SystemMacroArgument("Exponent", expo_expr?).get_integer(environment).map_err(error_context)?; + let expo_expr = self.arguments.next().ok_or(IonError::decoding_error( + "`make_decimal` takes 2 integer arguments; found only 1 argument", + ))?; + let exponent = SystemMacroArgument("Exponent", expo_expr?) + .get_integer(environment) + .map_err(error_context)?; - let decimal = Decimal::new(coefficient, exponent.as_i64().ok_or_else(|| IonError::decoding_error("Exponent does not fit within the range supported by this implementation."))?); + let decimal = Decimal::new( + coefficient, + exponent.as_i64().ok_or_else(|| { + IonError::decoding_error( + "Exponent does not fit within the range supported by this implementation.", + ) + })?, + ); let value_ref = context .allocator() @@ -1273,7 +1289,7 @@ impl<'top, D: Decoder> MakeDecimalExpansion<'top, D> { let lazy_expanded_value = LazyExpandedValue::from_constructed(context, &[], value_ref); Ok(MacroExpansionStep::FinalStep(Some( - ValueExpr::ValueLiteral(lazy_expanded_value) + ValueExpr::ValueLiteral(lazy_expanded_value), ))) } } @@ -1299,8 +1315,11 @@ enum TimestampBuilderWrapper { sysmacro_arg_info! { enum MakeTimestampArgs { Month = 0, Day = 1, Hour = 2, Minute = 3, Second = 4, Offset = 5, } } impl TimestampBuilderWrapper { - - fn process<'top, D: Decoder>(&mut self, env: Environment<'top, D>, arg: &SystemMacroArgument<'top, MakeTimestampArgs, D>) -> IonResult<()> { + fn process<'top, D: Decoder>( + &mut self, + env: Environment<'top, D>, + arg: &SystemMacroArgument<'top, MakeTimestampArgs, D>, + ) -> IonResult<()> { use TimestampBuilderWrapper::*; match self { WithYear(_) => self.process_with_year(env, arg), @@ -1336,7 +1355,9 @@ impl TimestampBuilderWrapper { WithSecond(builder) => builder.build(), WithFractionalSeconds(builder) => builder.build(), WithOffset(builder) => builder.build(), - _ => IonResult::decoding_error("attempt to build timestamp while in unconstructed state"), + _ => { + IonResult::decoding_error("attempt to build timestamp while in unconstructed state") + } } } @@ -1348,7 +1369,11 @@ impl TimestampBuilderWrapper { } /// Process the next provided argument after we've added the year to the timestamp. - fn process_with_year<'top, D: Decoder>(&mut self, env: Environment<'top, D>, arg: &SystemMacroArgument<'top, MakeTimestampArgs, D>) -> IonResult<()> { + fn process_with_year<'top, D: Decoder>( + &mut self, + env: Environment<'top, D>, + arg: &SystemMacroArgument<'top, MakeTimestampArgs, D>, + ) -> IonResult<()> { // We have a year, only option for a value is the month. let parameter = arg.0.as_ref(); @@ -1359,15 +1384,20 @@ impl TimestampBuilderWrapper { // We have a value, if it is anything other than Month it is invalid. if arg.0 != MakeTimestampArgs::Month { - return IonResult::decoding_error(format!("value provided for '{parameter}', but no month specified.")); + return IonResult::decoding_error(format!( + "value provided for '{parameter}', but no month specified." + )); } - let month_i64= value_ref - .expect_int()? - .as_u32() - .ok_or_else(|| IonError::decoding_error("value provided for 'Month' does not fit within a 32bit unsigned integer"))?; + let month_i64 = value_ref.expect_int()?.as_u32().ok_or_else(|| { + IonError::decoding_error( + "value provided for 'Month' does not fit within a 32bit unsigned integer", + ) + })?; - let TimestampBuilderWrapper::WithYear(builder) = self.take() else { unreachable!() }; + let TimestampBuilderWrapper::WithYear(builder) = self.take() else { + unreachable!() + }; let new_builder = builder.with_month(month_i64); *self = new_builder.into(); @@ -1375,18 +1405,24 @@ impl TimestampBuilderWrapper { } /// Process the next provided argument, after we have added the month to the timestamp. - fn process_with_month<'top, D: Decoder>(&mut self, env: Environment<'top, D>, arg: &SystemMacroArgument<'top, MakeTimestampArgs, D>) -> IonResult<()> { + fn process_with_month<'top, D: Decoder>( + &mut self, + env: Environment<'top, D>, + arg: &SystemMacroArgument<'top, MakeTimestampArgs, D>, + ) -> IonResult<()> { // If we have a new value, it has to be a day, nothing else is valid. let parameter = arg.0.as_ref(); // Check to see if we actually have a value. let Some(value_ref) = arg.try_get_valueref(env)? else { - return Ok(()) + return Ok(()); }; // We have a value, if it is anything other than Day then it is invalid. if arg.0 != MakeTimestampArgs::Day { - return IonResult::decoding_error(format!("value provided for '{parameter}', but no day specified.")); + return IonResult::decoding_error(format!( + "value provided for '{parameter}', but no day specified." + )); } let day= value_ref @@ -1394,7 +1430,9 @@ impl TimestampBuilderWrapper { .as_u32() .ok_or_else(|| IonError::decoding_error("value provided for 'Day' parameter cannot be represented as a unsigned 32bit value."))?; - let TimestampBuilderWrapper::WithMonth(builder) = self.take() else { unreachable!() }; + let TimestampBuilderWrapper::WithMonth(builder) = self.take() else { + unreachable!() + }; let new_builder = builder.with_day(day); *self = new_builder.into(); @@ -1402,26 +1440,35 @@ impl TimestampBuilderWrapper { } /// Process the next provided argument, after we have added the day to the timestamp. - fn process_with_day<'top, D: Decoder>(&mut self, env: Environment<'top, D>, arg: &SystemMacroArgument<'top, MakeTimestampArgs, D>) -> IonResult<()> { + fn process_with_day<'top, D: Decoder>( + &mut self, + env: Environment<'top, D>, + arg: &SystemMacroArgument<'top, MakeTimestampArgs, D>, + ) -> IonResult<()> { // We have a day, and a new value.. the only valid option is hour. let parameter = arg.0.as_ref(); // Check to see if we actually have a value. let Some(value_ref) = arg.try_get_valueref(env)? else { - return Ok(()) + return Ok(()); }; // We have a value, if it is anything other than Hour then it is invalid. if arg.0 != MakeTimestampArgs::Hour { - return IonResult::decoding_error(format!("value provided for '{parameter}', but no hour specified.")); + return IonResult::decoding_error(format!( + "value provided for '{parameter}', but no hour specified." + )); } - let hour = value_ref - .expect_int()? - .as_u32() - .ok_or_else(|| IonError::decoding_error("value provided for 'Hour' cannot be represented as an unsigned 32bit value"))?; + let hour = value_ref.expect_int()?.as_u32().ok_or_else(|| { + IonError::decoding_error( + "value provided for 'Hour' cannot be represented as an unsigned 32bit value", + ) + })?; - let TimestampBuilderWrapper::WithDay(builder) = self.take() else { unreachable!() }; + let TimestampBuilderWrapper::WithDay(builder) = self.take() else { + unreachable!() + }; let new_builder = builder.with_hour(hour); *self = new_builder.into(); @@ -1429,7 +1476,11 @@ impl TimestampBuilderWrapper { } /// Process the next provided argument after we have added the hour to the timestamp. - fn process_with_hour<'top, D: Decoder>(&mut self, env: Environment<'top, D>, arg: &SystemMacroArgument<'top, MakeTimestampArgs, D>) -> IonResult<()> { + fn process_with_hour<'top, D: Decoder>( + &mut self, + env: Environment<'top, D>, + arg: &SystemMacroArgument<'top, MakeTimestampArgs, D>, + ) -> IonResult<()> { // We have an hour, the only valid argument is Minute. let parameter_name = arg.0.as_ref(); @@ -1439,15 +1490,20 @@ impl TimestampBuilderWrapper { }; if arg.0 != MakeTimestampArgs::Minute { - return IonResult::decoding_error(format!("value provided for '{parameter_name}', but no minute specified.")); + return IonResult::decoding_error(format!( + "value provided for '{parameter_name}', but no minute specified." + )); } - let minute = value_ref - .expect_int()? - .as_u32() - .ok_or_else(|| IonError::decoding_error("value provided for 'Minute' cannot be represented as an unsigned 32bit value"))?; + let minute = value_ref.expect_int()?.as_u32().ok_or_else(|| { + IonError::decoding_error( + "value provided for 'Minute' cannot be represented as an unsigned 32bit value", + ) + })?; - let TimestampBuilderWrapper::WithHour(builder) = self.take() else { unreachable!() }; + let TimestampBuilderWrapper::WithHour(builder) = self.take() else { + unreachable!() + }; let new_builder = builder.with_minute(minute); *self = new_builder.into(); @@ -1455,7 +1511,11 @@ impl TimestampBuilderWrapper { } /// Process the next provided argument after we have added the minute to the timestamp. - fn process_with_minute<'top, D: Decoder>(&mut self, env: Environment<'top, D>, arg: &SystemMacroArgument<'top, MakeTimestampArgs, D>) -> IonResult<()> { + fn process_with_minute<'top, D: Decoder>( + &mut self, + env: Environment<'top, D>, + arg: &SystemMacroArgument<'top, MakeTimestampArgs, D>, + ) -> IonResult<()> { // We have a minute, we have 2 options for args now: Seconds, and Offset. let parameter_name = arg.0.as_ref(); @@ -1469,7 +1529,9 @@ impl TimestampBuilderWrapper { } else if arg.0 == MakeTimestampArgs::Offset { self.process_offset(value_ref) } else { - IonResult::decoding_error(format!("value provided for '{parameter_name}', but no value for 'second' specified.")) + IonResult::decoding_error(format!( + "value provided for '{parameter_name}', but no value for 'second' specified." + )) } } @@ -1523,10 +1585,11 @@ impl TimestampBuilderWrapper { /// Process the provided ValueRef as the offset parameter for the timestamp. fn process_offset<'top, D: Decoder>(&mut self, value: ValueRef<'top, D>) -> IonResult<()> { - let offset = value - .expect_int()? - .as_i64() - .ok_or_else(|| IonError::decoding_error("value provided for 'Offset' is not representable by a 64bit integer"))?; + let offset = value.expect_int()?.as_i64().ok_or_else(|| { + IonError::decoding_error( + "value provided for 'Offset' is not representable by a 64bit integer", + ) + })?; let new_builder = match self.take() { Self::WithMinute(builder) => builder.with_offset(offset as i32), @@ -1557,15 +1620,12 @@ impl_froms_timestampbuilders!( HasSeconds => WithSecond, HasFractionalSeconds => WithFractionalSeconds, HasOffset => WithOffset ); - - #[derive(Copy, Clone, Debug)] pub struct MakeTimestampExpansion<'top, D: Decoder> { arguments: MacroExprArgsIterator<'top, D>, } impl<'top, D: Decoder> MakeTimestampExpansion<'top, D> { - pub fn new(arguments: MacroExprArgsIterator<'top, D>) -> Self { Self { arguments } } @@ -1586,9 +1646,9 @@ impl<'top, D: Decoder> MakeTimestampExpansion<'top, D> { // Year is required, so we have to ensure that it is available. Our arguments iterator will // always have an item for each defined parameter, even if it is not present at the callsite. // But we still check here, JIC that ever changes. - let year_expr = self.arguments - .next() - .ok_or(IonError::decoding_error("`make_timestamp` takes 1 to 7 arguments; found 0 arguments"))?; + let year_expr = self.arguments.next().ok_or(IonError::decoding_error( + "`make_timestamp` takes 1 to 7 arguments; found 0 arguments", + ))?; let year = SystemMacroArgument("year", year_expr?) .get_integer(environment) .map_err(error_context)?; @@ -1602,7 +1662,7 @@ impl<'top, D: Decoder> MakeTimestampExpansion<'top, D> { // Now that we know that Year is provided, we can evaluate all of the arguments. // TimestampBuilderWrapper handles the tracking of state, and which arguments need to be // present and which are optional. - let args= [ + let args = [ SystemMacroArgument(MakeTimestampArgs::Month, self.arguments.next().unwrap()?), SystemMacroArgument(MakeTimestampArgs::Day, self.arguments.next().unwrap()?), SystemMacroArgument(MakeTimestampArgs::Hour, self.arguments.next().unwrap()?), @@ -1612,8 +1672,7 @@ impl<'top, D: Decoder> MakeTimestampExpansion<'top, D> { ]; let mut builder = TimestampBuilderWrapper::WithYear(Timestamp::with_year(year_i64 as u32)); - args - .iter() + args.iter() .try_for_each(|arg| builder.process(environment, arg)) // .try_fold(TimestampBuilderWrapper::WithYear(Timestamp::with_year(year_i64 as u32)), |builder, arg| { // builder.process(environment, arg) @@ -1628,7 +1687,7 @@ impl<'top, D: Decoder> MakeTimestampExpansion<'top, D> { let lazy_expanded_value = LazyExpandedValue::from_constructed(context, &[], value_ref); Ok(MacroExpansionStep::FinalStep(Some( - ValueExpr::ValueLiteral(lazy_expanded_value) + ValueExpr::ValueLiteral(lazy_expanded_value), ))) } } @@ -1807,38 +1866,31 @@ pub struct SumExpansion<'top, D: Decoder> { arguments: MacroExprArgsIterator<'top, D>, } -impl <'top, D: Decoder> SumExpansion<'top, D> { - pub fn new( - arguments: MacroExprArgsIterator<'top, D>, - ) -> Self { - - Self { - arguments, - } +impl<'top, D: Decoder> SumExpansion<'top, D> { + pub fn new(arguments: MacroExprArgsIterator<'top, D>) -> Self { + Self { arguments } } /// Given a [`ValueExpr`], this function will expand it into its underlying value; An /// error is returned if the value does not expand to exactly one Int. fn get_integer(&self, env: Environment<'top, D>, value: ValueExpr<'top, D>) -> IonResult { match value { - ValueExpr::ValueLiteral(value_literal) => { - value_literal - .read_resolved()? - .expect_int() - } + ValueExpr::ValueLiteral(value_literal) => value_literal.read_resolved()?.expect_int(), ValueExpr::MacroInvocation(invocation) => { let mut evaluator = MacroEvaluator::new_with_environment(env); evaluator.push(invocation.expand()?); let int_arg = match evaluator.next()? { - None => IonResult::decoding_error("`sum` takes two integers as arguments; empty value found"), - Some(value) => value - .read_resolved()? - .expect_int(), + None => IonResult::decoding_error( + "`sum` takes two integers as arguments; empty value found", + ), + Some(value) => value.read_resolved()?.expect_int(), }; // Ensure that we don't have any other values in the argument's stream. if !evaluator.is_empty() && evaluator.next()?.is_some() { - return IonResult::decoding_error("`sum` takes two integers as arguments; multiple values found"); + return IonResult::decoding_error( + "`sum` takes two integers as arguments; multiple values found", + ); } int_arg @@ -1849,7 +1901,7 @@ impl <'top, D: Decoder> SumExpansion<'top, D> { fn next( &mut self, context: EncodingContextRef<'top>, - env: Environment<'top, D> + env: Environment<'top, D>, ) -> IonResult> { let mut sum = Int::new(0); // Walk each of our arguments.. @@ -1859,13 +1911,11 @@ impl <'top, D: Decoder> SumExpansion<'top, D> { sum = sum + i; } - let value_ref = context - .allocator() - .alloc_with(|| ValueRef::Int(sum)); + let value_ref = context.allocator().alloc_with(|| ValueRef::Int(sum)); let lazy_expanded_value = LazyExpandedValue::from_constructed(context, &[], value_ref); Ok(MacroExpansionStep::FinalStep(Some( - ValueExpr::ValueLiteral(lazy_expanded_value) + ValueExpr::ValueLiteral(lazy_expanded_value), ))) } } @@ -1879,9 +1929,7 @@ pub struct RepeatExpansion<'top, D: Decoder> { } impl<'top, D: Decoder> RepeatExpansion<'top, D> { - pub fn new( - arguments: MacroExprArgsIterator<'top, D>, - ) -> Self { + pub fn new(arguments: MacroExprArgsIterator<'top, D>) -> Self { Self { arguments, repeat_iterations: None, @@ -1891,15 +1939,19 @@ impl<'top, D: Decoder> RepeatExpansion<'top, D> { // Extracts the first argument from `arguments` and verifies that it is a single integer value // >= 0 that can be used as the repeat count. Any other value will return an error. - fn get_number_to_repeat(&mut self, arguments: &mut MacroExprArgsIterator<'top, D>, environment: Environment<'top, D>) -> IonResult { - let count_expr = arguments - .next() - .unwrap_or(IonResult::decoding_error("`repeat` takes 2 or more parameters"))?; + fn get_number_to_repeat( + &mut self, + arguments: &mut MacroExprArgsIterator<'top, D>, + environment: Environment<'top, D>, + ) -> IonResult { + let count_expr = arguments.next().unwrap_or(IonResult::decoding_error( + "`repeat` takes 2 or more parameters", + ))?; let repeat_count = match count_expr { - ValueExpr::ValueLiteral(value_literal) => value_literal - .read_resolved()? - .expect_int()?, + ValueExpr::ValueLiteral(value_literal) => { + value_literal.read_resolved()?.expect_int()? + } ValueExpr::MacroInvocation(invocation) => { let mut evaluator = MacroEvaluator::new_with_environment(environment); @@ -1938,7 +1990,7 @@ impl<'top, D: Decoder> RepeatExpansion<'top, D> { if self.repeat_iterations.is_none() { let mut arguments = self.arguments; self.repeat_iterations = Some(self.get_number_to_repeat(&mut arguments, environment)?); - self.content= match arguments.next() { + self.content = match arguments.next() { None => None, Some(Err(e)) => return Err(e), Some(Ok(expr)) => Some(expr), @@ -1947,7 +1999,7 @@ impl<'top, D: Decoder> RepeatExpansion<'top, D> { // Check if we've reached our desired number of iterations, or if we have empty content. if Some(0) == self.repeat_iterations || self.content.is_none() { - return Ok(MacroExpansionStep::FinalStep(None)) // End early. + return Ok(MacroExpansionStep::FinalStep(None)); // End early. } if let Some(ref mut repeat_iterations) = self.repeat_iterations { @@ -2102,7 +2154,10 @@ impl<'top, D: Decoder> DeltaExpansion<'top, D> { } } - pub fn next(&mut self, context: EncodingContextRef<'top>) -> IonResult> { + pub fn next( + &mut self, + context: EncodingContextRef<'top>, + ) -> IonResult> { // If we haven't evaluated any of the deltas yet, we need to grab our expression group and // load it into the evaluator. if self.current_base.is_none() { @@ -2136,8 +2191,7 @@ impl<'top, D: Decoder> DeltaExpansion<'top, D> { let value_ref = context .allocator() .alloc_with(|| ValueRef::Int(self.current_base.unwrap())); - let lazy_expanded_value = - LazyExpandedValue::from_constructed(context, &[], value_ref); + let lazy_expanded_value = LazyExpandedValue::from_constructed(context, &[], value_ref); Ok(MacroExpansionStep::Step(ValueExpr::ValueLiteral( lazy_expanded_value, @@ -3174,12 +3228,9 @@ mod tests { #[test] fn uint8_parameters() -> IonResult<()> { - let template_definition = - "(macro int_pair (uint8::x uint8::y) (.values (%x) (%y)))"; + let template_definition = "(macro int_pair (uint8::x uint8::y) (.values (%x) (%y)))"; let macro_id = MacroTable::FIRST_USER_MACRO_ID as u8; - let tests: &[(&[u8], (u64, u64))] = &[ - (&[macro_id, 0x00, 0x00], (0, 0)), - ]; + let tests: &[(&[u8], (u64, u64))] = &[(&[macro_id, 0x00, 0x00], (0, 0))]; for (stream, (num1, num2)) in tests.iter().copied() { let mut reader = Reader::new(v1_1::Binary, stream)?; @@ -3761,14 +3812,14 @@ mod tests { #[test] fn make_decimal_eexp() -> IonResult<()> { stream_eq( - r#" + r#" (:make_decimal 1 1) (:make_decimal -2 2) (:make_decimal (:values 3) 3) (:make_decimal (:values 4) (:values 4)) (:make_decimal 199 -2) "#, - r#" + r#" 1d1 -2d2 3d3 @@ -3827,7 +3878,7 @@ mod tests { #[test] fn make_timestamp_eexp() -> IonResult<()> { stream_eq( - r#" + r#" (:make_timestamp 2025) (:make_timestamp 2025 5) (:make_timestamp 2025 5 2) @@ -3840,7 +3891,7 @@ mod tests { (:make_timestamp 2025 5 2 1 3 5d1) (:make_timestamp 2025 5 2 1 3 5 8) "#, - r#" + r#" 2025T 2025-05T 2025-05-02T @@ -3856,6 +3907,7 @@ mod tests { ) } + #[rustfmt::skip] #[rstest] #[case("(:make_timestamp)", "no year specified")] #[case("(:make_timestamp 2025 (:none) 2)", "month empty, day provided")] @@ -3889,7 +3941,6 @@ mod tests { .read_all_elements() .expect_err("Unexpected success"); - // Test non-integer in second parameter let source = "(:sum 1 foo)"; let mut actual_reader = Reader::new(v1_1::Text, source)?; @@ -4000,7 +4051,7 @@ mod tests { let source = "(:repeat foo a)"; let mut actual_reader = Reader::new(v1_1::Text, source)?; - let result= actual_reader.read_all_elements(); + let result = actual_reader.read_all_elements(); if let Err(IonError::Decoding(_)) = result { Ok(()) @@ -4009,7 +4060,6 @@ mod tests { } } - #[test] fn e_expressions_inside_a_list() -> IonResult<()> { stream_eq( diff --git a/src/lazy/expanded/template.rs b/src/lazy/expanded/template.rs index 875f83b5..3996eed0 100644 --- a/src/lazy/expanded/template.rs +++ b/src/lazy/expanded/template.rs @@ -1,18 +1,23 @@ -use crate::lazy::binary::raw::v1_1::{value::BinaryValueEncoding, binary_buffer::ArgGroupingBitmap}; +use crate::lazy::binary::raw::v1_1::{ + binary_buffer::ArgGroupingBitmap, value::BinaryValueEncoding, +}; use crate::lazy::decoder::Decoder; use crate::lazy::expanded::compiler::ExpansionAnalysis; use crate::lazy::expanded::macro_evaluator::{ AnnotateExpansion, ConditionalExpansion, DeltaExpansion, ExprGroupExpansion, FlattenExpansion, - MakeDecimalExpansion, MacroEvaluator, MacroExpansion, MacroExpansionKind, MacroExpr, - MacroExprArgsIterator, MakeFieldExpansion, MakeStructExpansion, MakeTextExpansion, MakeTimestampExpansion, - RepeatExpansion, SumExpansion, TemplateExpansion, ValueExpr, + MacroEvaluator, MacroExpansion, MacroExpansionKind, MacroExpr, MacroExprArgsIterator, + MakeDecimalExpansion, MakeFieldExpansion, MakeStructExpansion, MakeTextExpansion, + MakeTimestampExpansion, RepeatExpansion, SumExpansion, TemplateExpansion, ValueExpr, }; use crate::lazy::expanded::macro_table::{MacroDef, MacroKind, MacroRef}; use crate::lazy::expanded::r#struct::FieldExpr; use crate::lazy::expanded::sequence::Environment; use crate::lazy::expanded::{EncodingContextRef, LazyExpandedValue, TemplateVariableReference}; use crate::result::IonFailure; -use crate::{try_or_some_err, Bytes, Decimal, Int, IonError, IonResult, IonType, LazyExpandedFieldName, Str, Symbol, SymbolRef, Timestamp, Value}; +use crate::{ + try_or_some_err, Bytes, Decimal, Int, IonError, IonResult, IonType, LazyExpandedFieldName, Str, + Symbol, SymbolRef, Timestamp, Value, +}; use bumpalo::collections::Vec as BumpVec; use compact_str::CompactString; use rustc_hash::FxHashMap; @@ -235,8 +240,9 @@ impl TryFrom<&ParameterEncoding> for BinaryValueEncoding { fn try_from(value: &ParameterEncoding) -> Result { match value { - ParameterEncoding::MacroShaped(_) => - Err(IonError::illegal_operation("attempt to convert macro-shape parameter encoding to binary value encoding")), + ParameterEncoding::MacroShaped(_) => Err(IonError::illegal_operation( + "attempt to convert macro-shape parameter encoding to binary value encoding", + )), ParameterEncoding::FlexUInt => Ok(BinaryValueEncoding::FlexUInt), ParameterEncoding::Tagged => Ok(BinaryValueEncoding::Tagged), ParameterEncoding::UInt8 => Ok(BinaryValueEncoding::UInt8), @@ -338,14 +344,17 @@ impl MacroSignature { #[derive(Copy, Clone, Debug)] pub(crate) struct SignatureIterator<'a> { index: usize, - macro_def: MacroRef<'a> + macro_def: MacroRef<'a>, } impl<'a> SignatureIterator<'a> { pub fn new(macro_def: MacroRef<'a>) -> Self { - Self { index: 0, macro_def } + Self { + index: 0, + macro_def, + } } - + pub fn parent_macro(&self) -> MacroRef<'_> { self.macro_def } @@ -355,9 +364,7 @@ impl<'a> SignatureIterator<'a> { } pub fn current_parameter(&self) -> Option<&'a Parameter> { - self.signature() - .parameters() - .get(self.index) + self.signature().parameters().get(self.index) } pub fn expect_next_parameter(&mut self) -> IonResult<&Parameter> { @@ -662,8 +669,7 @@ impl<'top, D: Decoder> Iterator for TemplateSequenceIterator<'top, D> { // If the macro is guaranteed to expand to exactly one value, we can evaluate it // in place. let new_expansion = try_or_some_err!(invocation.expand()); - if invocation.is_singleton() - { + if invocation.is_singleton() { Some(new_expansion.expand_singleton()) } else { // Otherwise, add it to the evaluator's stack and return to the top of the loop. @@ -1273,7 +1279,11 @@ impl<'top, D: Decoder> TemplateExprGroup<'top, D> { impl Debug for TemplateExprGroup<'_, D> { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { - write!(f, "(.. /*expr group for param={}*/", self.parameter().name())?; + write!( + f, + "(.. /*expr group for param={}*/", + self.parameter().name() + )?; for expr in self.arg_expressions() { write!(f, "\n {expr:?}")?; } @@ -1435,12 +1445,8 @@ impl<'top, D: Decoder> TemplateMacroInvocation<'top, D> { self.environment, arguments, )), - MacroKind::Repeat => { - MacroExpansionKind::Repeat(RepeatExpansion::new(arguments)) - } - MacroKind::Sum => { - MacroExpansionKind::Sum(SumExpansion::new(arguments)) - } + MacroKind::Repeat => MacroExpansionKind::Repeat(RepeatExpansion::new(arguments)), + MacroKind::Sum => MacroExpansionKind::Sum(SumExpansion::new(arguments)), }; Ok(MacroExpansion::new( self.context(), diff --git a/src/lazy/reader.rs b/src/lazy/reader.rs index 8b3f951d..cec87e0d 100644 --- a/src/lazy/reader.rs +++ b/src/lazy/reader.rs @@ -107,7 +107,7 @@ impl Reader { self.next()? .ok_or_else(|| IonError::decoding_error("expected another top-level value")) } - + #[allow(dead_code)] pub fn symbol_table(&self) -> &SymbolTable { self.system_reader.symbol_table() diff --git a/src/lazy/struct.rs b/src/lazy/struct.rs index 5d8692eb..3d5edb1e 100644 --- a/src/lazy/struct.rs +++ b/src/lazy/struct.rs @@ -221,9 +221,8 @@ impl<'top, D: Decoder> LazyStruct<'top, D> { ///# fn main() -> IonResult<()> { Ok(()) } /// ``` pub fn get_expected(&self, name: &str) -> IonResult> { - self.get(name)?.ok_or_else(move || { - IonError::decoding_error(format!("missing required field {name}")) - }) + self.get(name)? + .ok_or_else(move || IonError::decoding_error(format!("missing required field {name}"))) } /// Returns an iterator over the annotations on this value. If this value has no annotations, diff --git a/src/serde/de.rs b/src/serde/de.rs index f328aa1c..bbad1d56 100644 --- a/src/serde/de.rs +++ b/src/serde/de.rs @@ -50,9 +50,9 @@ where pub struct ValueDeserializer<'a, 'de> { pub(crate) value: &'a LazyValue<'de, AnyEncoding>, is_human_readable: bool, - variant_nesting_depth: usize, // Holds the number of nested variants we are for tracking - // variant names in annotations. 0 indicates we're not in a - // variant. + variant_nesting_depth: usize, // Holds the number of nested variants we are for tracking + // variant names in annotations. 0 indicates we're not in a + // variant. } impl<'a, 'de> ValueDeserializer<'a, 'de> { @@ -433,11 +433,15 @@ impl<'de> de::Deserializer<'de> for ValueDeserializer<'_, 'de> { { // Make sure we've started reading an enum. if self.variant_nesting_depth == 0 { - return IonResult::decoding_error("unexpected serde state; was not expecting to read an identifier"); + return IonResult::decoding_error( + "unexpected serde state; was not expecting to read an identifier", + ); } let mut annotations = self.value.annotations(); - let our_annotation = annotations.nth(self.variant_nesting_depth - 1).transpose()?; + let our_annotation = annotations + .nth(self.variant_nesting_depth - 1) + .transpose()?; match our_annotation { None => { let symbol = self.value.read()?.expect_symbol()?; @@ -544,7 +548,10 @@ struct VariantAccess<'a, 'de> { impl<'a, 'de> VariantAccess<'a, 'de> { fn new(de: ValueDeserializer<'a, 'de>) -> Self { - let de = ValueDeserializer { variant_nesting_depth: de.variant_nesting_depth + 1, ..de }; + let de = ValueDeserializer { + variant_nesting_depth: de.variant_nesting_depth + 1, + ..de + }; VariantAccess { de } } diff --git a/src/serde/mod.rs b/src/serde/mod.rs index 3f73eb6a..ce6435ae 100644 --- a/src/serde/mod.rs +++ b/src/serde/mod.rs @@ -209,9 +209,9 @@ mod tests { use crate::{Decimal, Element, Timestamp}; use chrono::{DateTime, FixedOffset, Utc}; + use rstest::*; use serde::{Deserialize, Serialize}; use serde_with::serde_as; - use rstest::*; #[rstest] #[case::i8(to_binary(&-1_i8).unwrap(), &[0xE0, 0x01, 0x00, 0xEA, 0x31, 0x01])] @@ -256,6 +256,7 @@ mod tests { #[serde(with = "serde_bytes")] binary: Vec, } + #[rustfmt::skip] let expected = &[ 0xE0, 0x01, 0x00, 0xEA, // IVM 0xEE, 0x8F, 0x81, 0x83, 0xDC, // $ion_symbol_table:: { @@ -264,7 +265,9 @@ mod tests { 0xD7, 0x8A, 0xA5, 0x68, 0x65, 0x6C, 0x6C, 0x6F, // {binary: {{ aGVsbG8= }} ]; - let test = Test { binary: b"hello".to_vec() }; // aGVsbG8= + let test = Test { + binary: b"hello".to_vec(), + }; // aGVsbG8= let ion_data = to_binary(&test).unwrap(); assert_eq!(&ion_data[..], expected); let de: Test = from_ion(ion_data).expect("unable to parse test"); @@ -420,6 +423,7 @@ mod tests { Second(u32), } + #[rustfmt::skip] let expected_binary = [ 0xE0, 0x01, 0x00, 0xEA, // IVM 0xEE, 0x96, 0x81, 0x83, // $ion_symbol_table:: diff --git a/src/serde/ser.rs b/src/serde/ser.rs index 00a243af..eafe8375 100644 --- a/src/serde/ser.rs +++ b/src/serde/ser.rs @@ -77,7 +77,7 @@ impl ValueSerializer<'_, V> { Self { value_writer, is_human_readable, - annotations: vec!(), + annotations: vec![], lifetime: PhantomData, } } @@ -108,42 +108,58 @@ impl<'a, V: ValueWriter + 'a> ser::Serializer for ValueSerializer<'a, V> { /// Serialize all integer types using the `Integer` intermediary type. fn serialize_i8(self, v: i8) -> Result { - self.value_writer.with_annotations(self.annotations)?.write(v as i64) + self.value_writer + .with_annotations(self.annotations)? + .write(v as i64) } /// Serialize all integer types using the `Integer` intermediary type. fn serialize_u8(self, v: u8) -> Result { - self.value_writer.with_annotations(self.annotations)?.write(v as i64) + self.value_writer + .with_annotations(self.annotations)? + .write(v as i64) } /// Serialize all integer types using the `Integer` intermediary type. fn serialize_i16(self, v: i16) -> Result { - self.value_writer.with_annotations(self.annotations)?.write(v) + self.value_writer + .with_annotations(self.annotations)? + .write(v) } /// Serialize all integer types using the `Integer` intermediary type. fn serialize_u16(self, v: u16) -> Result { - self.value_writer.with_annotations(self.annotations)?.write(v) + self.value_writer + .with_annotations(self.annotations)? + .write(v) } /// Serialize all integer types using the `Integer` intermediary type. fn serialize_i32(self, v: i32) -> Result { - self.value_writer.with_annotations(self.annotations)?.write(v) + self.value_writer + .with_annotations(self.annotations)? + .write(v) } /// Serialize all integer types using the `Integer` intermediary type. fn serialize_u32(self, v: u32) -> Result { - self.value_writer.with_annotations(self.annotations)?.write(v) + self.value_writer + .with_annotations(self.annotations)? + .write(v) } /// Serialize all integer types using the `Integer` intermediary type. fn serialize_i64(self, v: i64) -> Result { - self.value_writer.with_annotations(self.annotations)?.write(v) + self.value_writer + .with_annotations(self.annotations)? + .write(v) } /// Serialize all integer types using the `Integer` intermediary type. fn serialize_u64(self, v: u64) -> Result { - self.value_writer.with_annotations(self.annotations)?.write(v) + self.value_writer + .with_annotations(self.annotations)? + .write(v) } fn serialize_f32(self, v: f32) -> Result { @@ -151,24 +167,34 @@ impl<'a, V: ValueWriter + 'a> ser::Serializer for ValueSerializer<'a, V> { } fn serialize_f64(self, v: f64) -> Result { - self.value_writer.with_annotations(self.annotations)?.write(v) + self.value_writer + .with_annotations(self.annotations)? + .write(v) } fn serialize_char(self, v: char) -> Result { // TODO: This could be optimized. - self.value_writer.with_annotations(self.annotations)?.write(v.to_string()) + self.value_writer + .with_annotations(self.annotations)? + .write(v.to_string()) } fn serialize_str(self, v: &str) -> Result { - self.value_writer.with_annotations(self.annotations)?.write(v) + self.value_writer + .with_annotations(self.annotations)? + .write(v) } fn serialize_bytes(self, v: &[u8]) -> Result { - self.value_writer.with_annotations(self.annotations)?.write(v) + self.value_writer + .with_annotations(self.annotations)? + .write(v) } fn serialize_none(self) -> Result { - self.value_writer.with_annotations(self.annotations)?.write(Null(IonType::Null)) + self.value_writer + .with_annotations(self.annotations)? + .write(Null(IonType::Null)) } fn serialize_some(self, value: &T) -> Result @@ -183,7 +209,9 @@ impl<'a, V: ValueWriter + 'a> ser::Serializer for ValueSerializer<'a, V> { } fn serialize_unit_struct(self, name: &'static str) -> Result { - self.value_writer.with_annotations(self.annotations)?.write(name.as_symbol_ref()) + self.value_writer + .with_annotations(self.annotations)? + .write(name.as_symbol_ref()) } fn serialize_unit_variant( @@ -192,7 +220,9 @@ impl<'a, V: ValueWriter + 'a> ser::Serializer for ValueSerializer<'a, V> { _variant_index: u32, variant: &'static str, ) -> Result { - self.value_writer.with_annotations(self.annotations)?.write(variant.as_symbol_ref()) + self.value_writer + .with_annotations(self.annotations)? + .write(variant.as_symbol_ref()) } fn serialize_newtype_struct( @@ -213,7 +243,9 @@ impl<'a, V: ValueWriter + 'a> ser::Serializer for ValueSerializer<'a, V> { // we are using TUNNELED_TIMESTAMP_TYPE_NAME flag here which indicates a timestamp value // The assert statement above that compares the sizes of the Timestamp and value types let timestamp = unsafe { std::mem::transmute_copy::<&T, &Timestamp>(&value) }; - self.value_writer.with_annotations(self.annotations)?.write_timestamp(timestamp) + self.value_writer + .with_annotations(self.annotations)? + .write_timestamp(timestamp) } else if name == TUNNELED_DECIMAL_TYPE_NAME { // # Safety // compiler doesn't understand that the generic T here is actually Decimal here since @@ -249,7 +281,7 @@ impl<'a, V: ValueWriter + 'a> ser::Serializer for ValueSerializer<'a, V> { } fn serialize_tuple(self, _len: usize) -> Result { - let writer= self.value_writer.with_annotations(self.annotations)?; + let writer = self.value_writer.with_annotations(self.annotations)?; Ok(SeqWriter { seq_writer: writer.list_writer()?, is_human_readable: self.is_human_readable, @@ -261,12 +293,15 @@ impl<'a, V: ValueWriter + 'a> ser::Serializer for ValueSerializer<'a, V> { name: &'static str, _len: usize, ) -> Result { - let ValueSerializer { value_writer, is_human_readable, mut annotations, .. } = self; + let ValueSerializer { + value_writer, + is_human_readable, + mut annotations, + .. + } = self; annotations.push(name); Ok(SeqWriter { - seq_writer: value_writer - .with_annotations(annotations)? - .list_writer()?, + seq_writer: value_writer.with_annotations(annotations)?.list_writer()?, is_human_readable, }) } @@ -278,12 +313,15 @@ impl<'a, V: ValueWriter + 'a> ser::Serializer for ValueSerializer<'a, V> { variant: &'static str, _len: usize, ) -> Result { - let ValueSerializer { value_writer, is_human_readable, mut annotations, .. } = self; + let ValueSerializer { + value_writer, + is_human_readable, + mut annotations, + .. + } = self; annotations.push(variant); Ok(SeqWriter { - seq_writer: value_writer - .with_annotations(annotations)? - .list_writer()?, + seq_writer: value_writer.with_annotations(annotations)?.list_writer()?, is_human_readable, }) } @@ -313,7 +351,12 @@ impl<'a, V: ValueWriter + 'a> ser::Serializer for ValueSerializer<'a, V> { variant: &'static str, _len: usize, ) -> Result { - let ValueSerializer { value_writer, is_human_readable, mut annotations, .. } = self; + let ValueSerializer { + value_writer, + is_human_readable, + mut annotations, + .. + } = self; annotations.push(variant); Ok(MapWriter { map_writer: value_writer diff --git a/src/types/decimal/mod.rs b/src/types/decimal/mod.rs index df870127..32db71d2 100644 --- a/src/types/decimal/mod.rs +++ b/src/types/decimal/mod.rs @@ -256,7 +256,10 @@ impl Decimal { // end. let mut coeff = self.coefficient().as_int().unwrap_or(Int::ZERO); coeff.data /= 10i128.pow(self.exponent.unsigned_abs() as u32); - Decimal::new(Coefficient::from_sign_and_value(self.coefficient_sign, coeff), 0) + Decimal::new( + Coefficient::from_sign_and_value(self.coefficient_sign, coeff), + 0, + ) } } @@ -264,11 +267,17 @@ impl Decimal { /// zero maintaining the sign of the original coefficient. pub fn fract(&self) -> Decimal { if self.exponent >= 0 { - Decimal::new(Coefficient::from_sign_and_value(self.coefficient_sign, 0), 0) + Decimal::new( + Coefficient::from_sign_and_value(self.coefficient_sign, 0), + 0, + ) } else { let mut coeff = self.coefficient().as_int().unwrap_or(Int::ZERO); coeff.data %= 10i128.pow(self.exponent.unsigned_abs() as u32); - Decimal::new(Coefficient::from_sign_and_value(self.coefficient_sign, coeff), self.exponent) + Decimal::new( + Coefficient::from_sign_and_value(self.coefficient_sign, coeff), + self.exponent, + ) } } } @@ -358,7 +367,7 @@ impl Sub for Decimal { // and we can do integer arithmetic. let mut lhs_int = self.coefficient().as_int().unwrap_or(Int::ZERO); let mut rhs_int = rhs.coefficient().as_int().unwrap_or(Int::ZERO); - let exp = if self.exponent > rhs.exponent { + let exp = if self.exponent > rhs.exponent { lhs_int.data *= 10i128.pow((self.exponent - rhs.exponent) as u32); rhs.exponent } else { @@ -962,7 +971,7 @@ mod decimal_tests { #[case(Decimal::NEGATIVE_ZERO, Decimal::ZERO, Sign::Negative)] #[case(Decimal::ZERO, Decimal::ZERO, Sign::Positive)] #[case(Decimal::ZERO, Decimal::NEGATIVE_ZERO, Sign::Positive)] - fn decimal_sub_signzero(#[case] lhs: Decimal, #[case] rhs: Decimal, #[case]sign: Sign) { + fn decimal_sub_signzero(#[case] lhs: Decimal, #[case] rhs: Decimal, #[case] sign: Sign) { let val = lhs - rhs; assert_eq!(val.coefficient().sign(), sign); } @@ -987,5 +996,4 @@ mod decimal_tests { fn decimal_fract(#[case] value: Decimal, #[case] expected: Decimal) { assert_eq!(value.fract(), expected); } - } diff --git a/src/types/mod.rs b/src/types/mod.rs index f068d0a0..ea1ca969 100644 --- a/src/types/mod.rs +++ b/src/types/mod.rs @@ -29,7 +29,10 @@ pub use r#struct::Struct; pub use sexp::SExp; pub use string::Str; pub use symbol::Symbol; -pub use timestamp::{HasDay, HasFractionalSeconds, HasHour, HasMinute, HasMonth, HasOffset, HasSeconds, HasYear, Mantissa, Timestamp, TimestampBuilder, TimestampPrecision}; +pub use timestamp::{ + HasDay, HasFractionalSeconds, HasHour, HasMinute, HasMonth, HasOffset, HasSeconds, HasYear, + Mantissa, Timestamp, TimestampBuilder, TimestampPrecision, +}; use crate::ion_data::{IonDataHash, IonDataOrd}; use std::cmp::Ordering; diff --git a/tests/conformance_dsl/model.rs b/tests/conformance_dsl/model.rs index 0e1b68e1..e9ac8780 100644 --- a/tests/conformance_dsl/model.rs +++ b/tests/conformance_dsl/model.rs @@ -46,7 +46,9 @@ impl TryFrom<&Element> for SymbolToken { fn try_from(other: &Element) -> InnerResult { match other.ion_type() { - IonType::Symbol => Ok(SymbolToken::Text(other.as_symbol().unwrap().text().unwrap_or("").to_string())), + IonType::Symbol => Ok(SymbolToken::Text( + other.as_symbol().unwrap().text().unwrap_or("").to_string(), + )), IonType::String => Ok(SymbolToken::Text(other.as_string().unwrap().to_owned())), IonType::Int => Ok(SymbolToken::Address(other.as_usize().unwrap())), IonType::SExp => { @@ -307,14 +309,9 @@ impl TryFrom<&Sequence> for ModelValue { let value = elems .get(1) .ok_or(ConformanceErrorKind::ExpectedModelValue) - .and_then(ModelValue::try_from) - ; - let annots: Result, _> = elems - .iter() - .skip(2) - .map(SymbolToken::try_from) - .collect() - ; + .and_then(ModelValue::try_from); + let annots: Result, _> = + elems.iter().skip(2).map(SymbolToken::try_from).collect(); Ok(ModelValue::Annot(Box::new(value?), annots?)) } _ => unreachable!(), @@ -446,7 +443,7 @@ pub(crate) fn compare_values( let other_annots = other_annots?; if other_annots.len() != annots.len() { - return Ok(false) + return Ok(false); } let annots_match = other_annots @@ -454,11 +451,11 @@ pub(crate) fn compare_values( .zip(annots.iter()) .fold(true, |acc, (a, e)| acc && (a == &e.as_symbol_ref())); if !annots_match { - return Ok(false) + return Ok(false); } if !compare_values(ctx, value, other)? { - return Ok(false) + return Ok(false); } Ok(true) @@ -743,17 +740,38 @@ mod tests { annots: &'static [&'static str], } let tests: &[TestCase] = &[ - TestCase{ source: "(annot true a)", value: ModelValue::Bool(true), annots: &["a"] }, - TestCase{ source: "(annot false a b c)", value: ModelValue::Bool(false), annots: &["a", "b", "c"] }, - TestCase{ source: "(annot (Bool true) a b c)", value: ModelValue::Bool(true), annots: &["a", "b", "c"] }, - TestCase{ source: "(annot (Int 5) a)", value: ModelValue::Int(5.into()), annots: &["a"] }, + TestCase { + source: "(annot true a)", + value: ModelValue::Bool(true), + annots: &["a"], + }, + TestCase { + source: "(annot false a b c)", + value: ModelValue::Bool(false), + annots: &["a", "b", "c"], + }, + TestCase { + source: "(annot (Bool true) a b c)", + value: ModelValue::Bool(true), + annots: &["a", "b", "c"], + }, + TestCase { + source: "(annot (Int 5) a)", + value: ModelValue::Int(5.into()), + annots: &["a"], + }, ]; for test in tests { println!("Testing: {}", test.source); let element = Element::read_one(test.source).expect("unable to read ion clause"); - let model_value = ModelValue::try_from(&element).expect("unable to convert elements to model value"); - let expected_annots: Vec = test.annots.iter().map(|a| SymbolToken::Text(a.to_string())).collect(); + let model_value = + ModelValue::try_from(&element).expect("unable to convert elements to model value"); + let expected_annots: Vec = test + .annots + .iter() + .map(|a| SymbolToken::Text(a.to_string())) + .collect(); if let ModelValue::Annot(value, annots) = model_value { assert_eq!(Box::leak(value), &test.value); assert_eq!(annots, expected_annots); diff --git a/tests/conformance_tests.rs b/tests/conformance_tests.rs index d19fcf7e..a91a9e13 100644 --- a/tests/conformance_tests.rs +++ b/tests/conformance_tests.rs @@ -176,8 +176,6 @@ mod ion_tests { test.run().expect("test failed"); } - println!( - "SUMMARY: {file_name} : Total Tests {total_tests} : Skipped {total_skipped}", - ); + println!("SUMMARY: {file_name} : Total Tests {total_tests} : Skipped {total_skipped}",); } } diff --git a/tests/ion_hash_tests.rs b/tests/ion_hash_tests.rs index 16e75577..f98769ea 100644 --- a/tests/ion_hash_tests.rs +++ b/tests/ion_hash_tests.rs @@ -226,9 +226,7 @@ fn test_case( if expected_string != actual_string { Err(IonHashTestError::TestFailed { test_case_name, - message: Some(format!( - "expected: {expected_string}\nwas: {actual_string}", - )), + message: Some(format!("expected: {expected_string}\nwas: {actual_string}",)), }) } else { Ok(())