From ab997dc29a4ea2ba29bbcb11c882593c9cd25798 Mon Sep 17 00:00:00 2001 From: Zack Slayton Date: Wed, 15 Mar 2023 11:43:27 -0400 Subject: [PATCH 01/14] Adds ElementReader trait --- src/binary/constants.rs | 6 +- src/binary/mod.rs | 2 +- src/ion_hash/mod.rs | 2 +- src/lib.rs | 2 +- src/reader.rs | 14 ++ src/value/builders.rs | 42 +++--- src/value/element_stream_reader.rs | 5 +- src/value/mod.rs | 3 +- src/value/native_reader.rs | 145 ------------------- src/value/native_writer.rs | 10 +- src/value/owned.rs | 46 +++--- src/value/reader.rs | 219 ++++++++++++++++++++++------- src/value/writer.rs | 2 +- tests/element_test_vectors.rs | 158 ++++++++++----------- tests/ion_hash_tests.rs | 8 +- 15 files changed, 327 insertions(+), 337 deletions(-) delete mode 100644 src/value/native_reader.rs diff --git a/src/binary/constants.rs b/src/binary/constants.rs index 4ef91474..cff8bd2e 100644 --- a/src/binary/constants.rs +++ b/src/binary/constants.rs @@ -1,10 +1,10 @@ /// Constants for Ion v1.0 -pub(crate) mod v1_0 { +pub mod v1_0 { /// Ion Version Marker byte sequence - pub(crate) const IVM: [u8; 4] = [0xE0, 0x01, 0x00, 0xEA]; + pub const IVM: [u8; 4] = [0xE0, 0x01, 0x00, 0xEA]; /// Constants for interpreting the length (`L`) code of binary values - pub(crate) mod length_codes { + pub mod length_codes { pub const NULL: u8 = 15; pub const VAR_UINT: u8 = 14; } diff --git a/src/binary/mod.rs b/src/binary/mod.rs index f865dc84..b988f8c3 100644 --- a/src/binary/mod.rs +++ b/src/binary/mod.rs @@ -4,7 +4,7 @@ //! data stream. pub mod binary_writer; -pub(crate) mod constants; +pub mod constants; pub mod decimal; mod header; pub mod int; diff --git a/src/ion_hash/mod.rs b/src/ion_hash/mod.rs index ee68fac3..33e3fbfc 100644 --- a/src/ion_hash/mod.rs +++ b/src/ion_hash/mod.rs @@ -10,7 +10,7 @@ //! //! # fn main() -> IonResult<()> { //! let loader = reader::element_reader(); -//! let elem = loader.iterate_over(b"\"hello world\"")?.next().unwrap()?; +//! let elem = loader.elements(b"\"hello world\"")?.next().unwrap()?; //! let digest = ion_hash::sha256(&elem); //! println!("{:?}", digest); //! # Ok(()) diff --git a/src/lib.rs b/src/lib.rs index 4e496d08..e1c8d951 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -18,7 +18,7 @@ pub mod constants; pub mod ion_eq; mod raw_symbol_token; mod raw_symbol_token_ref; -mod reader; +pub mod reader; mod shared_symbol_table; mod stream_reader; mod symbol; diff --git a/src/reader.rs b/src/reader.rs index aa92d16a..86915098 100644 --- a/src/reader.rs +++ b/src/reader.rs @@ -122,6 +122,8 @@ pub struct UserReader { } impl UserReader { + // This is `pub` for use in the integration tests (which cannot access `pub(crate)`), + // but we want users to rely on `ReaderBuilder` when possible. pub(crate) fn new(raw_reader: R) -> UserReader { UserReader { raw_reader, @@ -130,6 +132,18 @@ impl UserReader { } } +// This module exists to allow our integration tests to directly construct a `UserReader` +// with not-yet-supported settings. We want users to use `ReaderBuilder` instead; eventually, +// `ReaderBuilder` will also work for the integration tests and we can remove this. +#[doc(hidden)] +pub mod integration_testing { + use crate::{RawReader, Reader, UserReader}; + + pub fn new_reader<'a, R: 'a + RawReader>(raw_reader: R) -> Reader<'a> { + UserReader::new(Box::new(raw_reader)) + } +} + /// Stream components that an application-level [Reader] implementation may encounter. #[derive(Eq, PartialEq, Debug)] pub enum StreamItem { diff --git a/src/value/builders.rs b/src/value/builders.rs index c66cad8d..4896c3cf 100644 --- a/src/value/builders.rs +++ b/src/value/builders.rs @@ -11,7 +11,7 @@ use crate::Symbol; /// .push("foo") /// .build() /// .into(); -/// let expected = Element::parse(r#"[1, true, "foo"]"#).unwrap(); +/// let expected = Element::read_one(r#"[1, true, "foo"]"#).unwrap(); /// assert_eq!(actual, expected); /// ``` pub struct ListBuilder { @@ -64,7 +64,7 @@ impl ListBuilder { /// .push("foo") /// .build() /// .into(); -/// let expected = Element::parse(r#"(1 true "foo")"#).unwrap(); +/// let expected = Element::read_one(r#"(1 true "foo")"#).unwrap(); /// assert_eq!(actual, expected); /// ``` pub struct SExpBuilder { @@ -117,7 +117,7 @@ impl SExpBuilder { /// "b": true, /// "c": "foo" /// }.into(); -/// let expected = Element::parse(r#"{a: 1, b: true, c: "foo"}"#).unwrap(); +/// let expected = Element::read_one(r#"{a: 1, b: true, c: "foo"}"#).unwrap(); /// assert_eq!(actual, expected); /// ``` /// @@ -136,7 +136,7 @@ impl SExpBuilder { /// .build() /// .into(); // Convert from `Struct` to `Element` /// -/// let expected = Element::parse(r#"{foo: 1, baz: 3, quux: 4}"#).unwrap(); +/// let expected = Element::read_one(r#"{foo: 1, baz: 3, quux: 4}"#).unwrap(); /// assert_eq!(expected, modified_struct); /// ``` pub struct StructBuilder { @@ -191,7 +191,7 @@ impl StructBuilder { /// .with_fields(struct2.fields()) /// .build(); /// - /// let expected = Element::parse("{foo: 1, bar: 2, baz: 3, a: 4, b: 5, c: 6}").unwrap(); + /// let expected = Element::read_one("{foo: 1, bar: 2, baz: 3, a: 4, b: 5, c: 6}").unwrap(); /// ``` /// pub fn with_fields(mut self, fields: I) -> Self @@ -263,7 +263,7 @@ impl From for Element { /// ion_list![1.5f64, -8.25f64] /// ].into(); /// // Construct an Element from serialized Ion data -/// let expected = Element::parse(r#"["foo", 7, false, [1.5e0, -8.25e0]]"#).unwrap(); +/// let expected = Element::read_one(r#"["foo", 7, false, [1.5e0, -8.25e0]]"#).unwrap(); /// // Compare the two Elements /// assert_eq!(expected, actual); /// ``` @@ -287,7 +287,7 @@ impl From for Element { /// Element::symbol("world") /// ].into(); /// // Construct an Element from serialized Ion data -/// let expected = Element::parse(r#"["foo", true, bar::10, {{"hello"}}, world]"#).unwrap(); +/// let expected = Element::read_one(r#"["foo", true, bar::10, {{"hello"}}, world]"#).unwrap(); /// // Compare the two Elements /// assert_eq!(expected, actual); /// ``` @@ -309,7 +309,7 @@ macro_rules! ion_list { /// // Construct an s-expression Element from Rust values /// let actual: Element = ion_sexp!("foo" 7 false ion_sexp!(1.5f64 8.25f64)).into(); /// // Construct an Element from serialized Ion data -/// let expected = Element::parse(r#"("foo" 7 false (1.5e0 8.25e0))"#).unwrap(); +/// let expected = Element::read_one(r#"("foo" 7 false (1.5e0 8.25e0))"#).unwrap(); /// // Compare the two Elements /// assert_eq!(expected, actual); /// ``` @@ -333,7 +333,7 @@ macro_rules! ion_list { /// Element::symbol("world") /// ).into(); /// // Construct an Element from serialized Ion data -/// let expected = Element::parse(r#"("foo" true bar::10 {{"hello"}} world)"#).unwrap(); +/// let expected = Element::read_one(r#"("foo" true bar::10 {{"hello"}} world)"#).unwrap(); /// // Compare the two Elements /// assert_eq!(expected, actual); /// ``` @@ -369,7 +369,7 @@ macro_rules! ion_sexp { /// {format!("{}_{}", prefix, suffix)}: IonType::Null /// }.into(); /// // Construct an Element from serialized Ion data -/// let expected = Element::parse(r#"{w: "foo", x: 7, y: false, z: {a: 1.5e0, b: -8.25e0}, abc_def: null}"#).unwrap(); +/// let expected = Element::read_one(r#"{w: "foo", x: 7, y: false, z: {a: 1.5e0, b: -8.25e0}, abc_def: null}"#).unwrap(); /// // Compare the two Elements /// assert_eq!(expected, actual); /// ``` @@ -401,14 +401,14 @@ mod tests { .push(Symbol::owned("bar")) .build() .into(); - let expected = Element::parse(r#"[1, true, "foo", bar]"#).unwrap(); + let expected = Element::read_one(r#"[1, true, "foo", bar]"#).unwrap(); assert_eq!(actual, expected); } #[test] fn make_list_with_macro() { let actual: Element = ion_list![1, true, "foo", Symbol::owned("bar")].into(); - let expected = Element::parse(r#"[1, true, "foo", bar]"#).unwrap(); + let expected = Element::read_one(r#"[1, true, "foo", bar]"#).unwrap(); assert_eq!(actual, expected); } @@ -423,7 +423,7 @@ mod tests { .push(Symbol::owned("bar")) .build() .into(); - let expected = Element::parse("[1, bar]").unwrap(); + let expected = Element::read_one("[1, bar]").unwrap(); assert_eq!(actual, expected); } @@ -436,7 +436,7 @@ mod tests { .push(88) .build() .into(); - let expected_list = Element::parse(r#"[1, "foo", bar, 88]"#).unwrap(); + let expected_list = Element::read_one(r#"[1, "foo", bar, 88]"#).unwrap(); assert_eq!(new_list, expected_list); } @@ -449,7 +449,7 @@ mod tests { .push(Symbol::owned("bar")) .build() .into(); - let expected = Element::parse(r#"(1 true "foo" bar)"#).unwrap(); + let expected = Element::read_one(r#"(1 true "foo" bar)"#).unwrap(); assert_eq!(actual, expected); } @@ -462,7 +462,7 @@ mod tests { .push(88) .build() .into(); - let expected_sexp = Element::parse(r#"(1 "foo" bar 88)"#).unwrap(); + let expected_sexp = Element::read_one(r#"(1 "foo" bar 88)"#).unwrap(); assert_eq!(new_sexp, expected_sexp); } @@ -477,14 +477,14 @@ mod tests { .push(Symbol::owned("bar")) .build() .into(); - let expected = Element::parse("(1 bar)").unwrap(); + let expected = Element::read_one("(1 bar)").unwrap(); assert_eq!(actual, expected); } #[test] fn make_sexp_with_macro() { let actual: Element = ion_sexp!(1 true "foo" Symbol::owned("bar")).into(); - let expected = Element::parse(r#"(1 true "foo" bar)"#).unwrap(); + let expected = Element::read_one(r#"(1 true "foo" bar)"#).unwrap(); assert_eq!(actual, expected); } @@ -497,7 +497,7 @@ mod tests { .with_field("d", Symbol::owned("bar")) .build() .into(); - let expected = Element::parse(r#"{a: 1, b: true, c: "foo", d: bar}"#).unwrap(); + let expected = Element::read_one(r#"{a: 1, b: true, c: "foo", d: bar}"#).unwrap(); assert_eq!(actual, expected); } @@ -510,7 +510,7 @@ mod tests { "d": Symbol::owned("bar") } .into(); - let expected = Element::parse(r#"{a: 1, b: true, c: "foo", d: bar}"#).unwrap(); + let expected = Element::read_one(r#"{a: 1, b: true, c: "foo", d: bar}"#).unwrap(); assert_eq!(actual, expected); } @@ -528,7 +528,7 @@ mod tests { .remove_field("d") .build() .into(); - let expected = Element::parse(r#"{a: 1, c: "foo", d: baz}"#).unwrap(); + let expected = Element::read_one(r#"{a: 1, c: "foo", d: baz}"#).unwrap(); assert_eq!(actual, expected); } } diff --git a/src/value/element_stream_reader.rs b/src/value/element_stream_reader.rs index 81860e02..1417bdca 100644 --- a/src/value/element_stream_reader.rs +++ b/src/value/element_stream_reader.rs @@ -387,13 +387,10 @@ mod reader_tests { use crate::types::decimal::Decimal; use crate::types::timestamp::Timestamp; use crate::value::owned::Value; - use crate::value::reader::{element_reader, ElementReader as NonStreamElementReader}; use crate::IonType; fn load_element(text: &str) -> Element { - element_reader() - .read_one(text.as_bytes()) - .expect("parsing failed unexpectedly") + Element::read_one(text.as_bytes()).expect("parsing failed unexpectedly") } fn next_type(reader: &mut ElementStreamReader, ion_type: IonType, is_null: bool) { diff --git a/src/value/mod.rs b/src/value/mod.rs index 3c1dc78d..880eb17a 100644 --- a/src/value/mod.rs +++ b/src/value/mod.rs @@ -15,7 +15,6 @@ pub mod builders; mod element_stream_reader; mod iterators; -pub mod native_reader; pub mod native_writer; pub mod owned; pub mod reader; @@ -543,7 +542,7 @@ mod tests { assert(&input_case.elem); } - // assert that a value element as-is is equal to itself + // assert that an element as-is is equal to itself // Creating an alias here bypasses clippy's objection to comparing any literal to itself. let itself = &input_case.elem; assert_eq!(&input_case.elem, itself); diff --git a/src/value/native_reader.rs b/src/value/native_reader.rs deleted file mode 100644 index 7db39ba0..00000000 --- a/src/value/native_reader.rs +++ /dev/null @@ -1,145 +0,0 @@ -use crate::binary::constants::v1_0::IVM; -use crate::binary::non_blocking::raw_binary_reader::RawBinaryBufferReader; -use crate::raw_reader::RawReader; -use crate::reader::ReaderBuilder; -use crate::result::IonResult; -use crate::text::non_blocking::raw_text_reader::RawTextReader; -use crate::value::owned; -use crate::value::owned::{Element, Struct, Value}; -use crate::value::reader::ElementReader; -use crate::{IonReader, IonType, StreamItem, UserReader}; - -struct NativeElementIterator { - reader: UserReader, -} - -impl Iterator for NativeElementIterator { - type Item = IonResult; - - fn next(&mut self) -> Option { - self.materialize_next().transpose() - } -} - -impl NativeElementIterator { - /// Advances the reader to the next value in the stream and uses [Self::materialize_current] - /// to materialize it. - fn materialize_next(&mut self) -> IonResult> { - // Advance the reader to the next value - let _ = self.reader.next()?; - self.materialize_current() - } - - /// Recursively materialize the reader's current Ion value and returns it as `Ok(Some(element))`. - /// If there are no more values at this level, returns `Ok(None)`. - /// If an error occurs while materializing the value, returns an `Err`. - /// Calling this method advances the reader and consumes the current value. - fn materialize_current(&mut self) -> IonResult> { - // Collect this item's annotations into a Vec. We have to do this before materializing the - // value itself because materializing a collection requires advancing the reader further. - let mut annotations = Vec::new(); - // Current API limitations require `self.reader.annotations()` to heap allocate its - // iterator even if there aren't annotations. `self.reader.has_annotations()` is trivial - // and allows us to skip the heap allocation in the common case. - if self.reader.has_annotations() { - for annotation in self.reader.annotations() { - annotations.push(annotation?); - } - } - - let value = match self.reader.current() { - // No more values at this level of the stream - StreamItem::Nothing => return Ok(None), - // This is a typed null - StreamItem::Null(ion_type) => Value::Null(ion_type), - // This is a non-null value - StreamItem::Value(ion_type) => { - use IonType::*; - match ion_type { - Null => unreachable!("non-null value had IonType::Null"), - Boolean => Value::Boolean(self.reader.read_bool()?), - Integer => Value::Integer(self.reader.read_integer()?), - Float => Value::Float(self.reader.read_f64()?), - Decimal => Value::Decimal(self.reader.read_decimal()?), - Timestamp => Value::Timestamp(self.reader.read_timestamp()?), - Symbol => Value::Symbol(self.reader.read_symbol()?), - String => Value::String(self.reader.read_string()?), - Clob => Value::Clob(self.reader.read_clob()?), - Blob => Value::Blob(self.reader.read_blob()?), - // It's a collection; recursively materialize all of this value's children - List => Value::List(owned::List::new(self.materialize_sequence()?)), - SExpression => Value::SExp(owned::SExp::new(self.materialize_sequence()?)), - Struct => Value::Struct(self.materialize_struct()?), - } - } - }; - Ok(Some(Element::new(annotations, value))) - } - - /// Steps into the current sequence and materializes each of its children to construct - /// an [OwnedSequence]. When all of the the children have been materialized, steps out. - /// The reader MUST be positioned over a list or s-expression when this is called. - fn materialize_sequence(&mut self) -> IonResult> { - let mut child_elements = Vec::new(); - self.reader.step_in()?; - while let Some(element) = self.materialize_next()? { - child_elements.push(element); - } - self.reader.step_out()?; - Ok(child_elements) - } - - /// Steps into the current struct and materializes each of its fields to construct - /// an [OwnedStruct]. When all of the the fields have been materialized, steps out. - /// The reader MUST be positioned over a struct when this is called. - fn materialize_struct(&mut self) -> IonResult { - let mut child_elements = Vec::new(); - self.reader.step_in()?; - while let StreamItem::Value(_) | StreamItem::Null(_) = self.reader.next()? { - let field_name = self.reader.field_name()?; - let value = self - .materialize_current()? - .expect("materialize_current() returned None for user data"); - child_elements.push((field_name, value)); - } - self.reader.step_out()?; - Ok(Struct::from_iter(child_elements.into_iter())) - } -} - -/// Provides an implementation of [ElementReader] that is backed by a native Rust [Reader](crate::reader::Reader). -pub struct NativeElementReader; - -impl ElementReader for NativeElementReader { - fn iterate_over<'a, 'b>( - &'a self, - data: &'b [u8], - ) -> IonResult> + 'b>> { - let reader = ReaderBuilder::new().build(data)?; - let iterator = NativeElementIterator { reader }; - Ok(Box::new(iterator)) - } -} - -pub struct NonBlockingNativeElementReader; - -impl ElementReader for NonBlockingNativeElementReader { - fn iterate_over<'a, 'b>( - &'a self, - data: &'b [u8], - ) -> IonResult> + 'b>> { - // If the data is binary, create a non-blocking binary reader. - if data.starts_with(&IVM) { - let raw_reader = RawBinaryBufferReader::new(data); - let reader = UserReader::new(raw_reader); - let iterator = NativeElementIterator { reader }; - return Ok(Box::new(iterator)); - } - - let mut raw_reader = RawTextReader::new(data); - raw_reader.stream_complete(); - let reader = UserReader::new(raw_reader); - let iterator = NativeElementIterator { reader }; - Ok(Box::new(iterator)) - } -} diff --git a/src/value/native_writer.rs b/src/value/native_writer.rs index f1ee5bc0..b81c3b23 100644 --- a/src/value/native_writer.rs +++ b/src/value/native_writer.rs @@ -26,7 +26,7 @@ impl NativeElementWriter { NativeElementWriter { writer } } - /// Recursively writes the given `element` and its child elements (if any) to the underlying + /// Recursively writes the given `value` and its child elements (if any) to the underlying /// writer. fn write_element(&mut self, field_name: Option<&str>, element: &Element) -> IonResult<()> { if let Some(field_name) = field_name { @@ -48,7 +48,7 @@ impl NativeElementWriter { } match element.ion_type() { - IonType::Null => unreachable!("element has IonType::Null but is_null() was false"), + IonType::Null => unreachable!("value has IonType::Null but is_null() was false"), IonType::Boolean => self.writer.write_bool(element.as_boolean().unwrap()), IonType::Integer => self.writer.write_integer(element.as_integer().unwrap()), IonType::Float => self.writer.write_f64(element.as_float().unwrap()), @@ -83,7 +83,7 @@ mod tests { use crate::ion_eq::IonEq; use crate::text::text_writer::TextWriterBuilder; use crate::value::native_writer::NativeElementWriter; - use crate::value::reader::{native_element_reader, ElementReader}; + use crate::value::owned::Element; use crate::value::writer::ElementWriter; use crate::IonResult; use nom::AsBytes; @@ -97,10 +97,10 @@ mod tests { let ion = r#" null true 0 1e0 2.0 2022T foo "bar" (foo bar baz) [foo, bar, baz] {foo: true, bar: false} "#; - let expected_elements = native_element_reader().read_all(ion.as_bytes())?; + let expected_elements = Element::read_all(ion.as_bytes())?; element_writer.write_all(&expected_elements)?; let _ = element_writer.finish()?; - let actual_elements = native_element_reader().read_all(buffer.as_bytes())?; + let actual_elements: Vec = Element::read_all(buffer.as_bytes())?; assert!(expected_elements.ion_eq(&actual_elements)); Ok(()) } diff --git a/src/value/owned.rs b/src/value/owned.rs index 97767bbf..e78144d1 100644 --- a/src/value/owned.rs +++ b/src/value/owned.rs @@ -1,12 +1,11 @@ // Copyright Amazon.com, Inc. or its affiliates. use crate::ion_eq::IonEq; -use crate::result::decoding_error; use crate::text::text_formatter::IonValueFormatter; use crate::types::decimal::Decimal; use crate::types::integer::Integer; use crate::types::timestamp::Timestamp; -use crate::{IonResult, IonType, Symbol}; +use crate::{IonResult, IonType, ReaderBuilder, Symbol}; use num_bigint::BigInt; use std::collections::HashMap; use std::fmt::{Display, Formatter}; @@ -17,7 +16,6 @@ use crate::value::builders::{ListBuilder, SExpBuilder, StructBuilder}; use crate::value::iterators::{ ElementsIterator, FieldIterator, FieldValuesIterator, IndexVec, SymbolsIterator, }; -use crate::value::native_reader::NativeElementReader; use crate::value::reader::ElementReader; impl Element { @@ -752,22 +750,34 @@ impl Element { } } - /// Reads a single Ion [`Element`] from the provided data source. If the data source has invalid - /// data or does not contain at exactly one Ion value, returns `Err`. - pub fn parse>(data: A) -> IonResult { + /// Reads a single Ion [`Element`] from the provided data source. + /// + /// If the data source is empty, returns `Ok(None)`. + /// If the data source has at least one value, returns `Ok(Some(Element))`. + /// If the data source has invalid data, returns `Err`. + pub fn read_first>(data: A) -> IonResult> { let bytes: &[u8] = data.as_ref(); // Create an iterator over the Elements in the data - let mut iter = NativeElementReader.iterate_over(bytes).unwrap(); - // Materialize the first Element - let element = iter - .next() - .unwrap_or_else(|| decoding_error("input did not contain any Ion values"))?; - // Make sure there aren't any other Elements - if iter.next().is_some() { - return decoding_error("stream contained more than one value"); - } - // Return the first (and verified only) Element - Ok(element) + let mut reader = ReaderBuilder::default().build(bytes)?; + reader.read_next_element() + } + + /// Reads a single Ion [`Element`] from the provided data source. If the input has invalid + /// data or does not contain at exactly one Ion value, returns `Err(IonError)`. + pub fn read_one>(data: A) -> IonResult { + let bytes: &[u8] = data.as_ref(); + // Create an iterator over the Elements in the data + let mut reader = ReaderBuilder::default().build(bytes)?; + reader.read_one_element() + } + + /// Reads all available [`Element`]s from the provided data source. + /// + /// If the input has valid data, returns `Ok(Vec)`. + /// If the input has invalid data, returns `Err(IonError)`. + pub fn read_all>(data: A) -> IonResult> { + let bytes: &[u8] = data.as_ref(); + ReaderBuilder::default().build(bytes)?.elements().collect() } } @@ -797,7 +807,7 @@ mod value_tests { E1: Into, E2: Into, { - // assert that both element construction methods create the same element + // assert that both value construction methods create the same element assert_eq!(e1.into(), e2.into()); } diff --git a/src/value/reader.rs b/src/value/reader.rs index 07242b2f..043f3203 100644 --- a/src/value/reader.rs +++ b/src/value/reader.rs @@ -4,66 +4,191 @@ //! as slices or files. use crate::result::{decoding_error, IonResult}; -use crate::value::native_reader::NativeElementReader; -use crate::value::owned::Element; - -// TODO add/refactor trait/implementation for borrowing over some context -// we could make it generic with generic associated types or just have a lifetime -// scoped implementation +use crate::value::owned; +use crate::value::owned::{Element, Struct, Value}; +use crate::{IonReader, StreamItem, Symbol}; /// Reads Ion data into [`Element`] instances. +/// +/// This trait is automatically implemented by all Ion reader implementations that operate +/// at the highest layer of abstraction, sometimes called the 'user' layer. pub trait ElementReader { - /// Parses Ion over a given slice of data and yields each top-level value as - /// an [`Element`] instance. + type ElementIterator<'a>: Iterator> + where + Self: 'a; + + /// Recursively materializes the next Ion value, returning it as an `Ok(Element)`. + /// If there is no more data left to be read, returns `Ok(None)`. + /// If an error occurs while the data is being read, returns `Err(IonError)`. + fn read_next_element(&mut self) -> IonResult>; + + /// Returns an iterator over the [Element]s in the data stream. + fn elements(&mut self) -> Self::ElementIterator<'_>; + + /// Like [Self::read_next_element], this method reads the next Ion value in the input stream, + /// returning it as an `Ok(Element)`. However, it also requires that the stream contain exactly + /// one value. /// - /// The [`Iterator`] will generally return `Some(Ok([`Element`]))` but on a failure of - /// parsing it will return a `Some(Err([IonError]))` and then a `None` to signal no more - /// elements. + /// If the stream's data is valid and it contains one value, returns `Ok(Element)`. + /// If the stream's data is invalid or the stream does not contain exactly one value, + /// returns `Err(IonError)`. + fn read_one_element(&mut self) -> IonResult { + let mut iter = self.elements(); + let only_element = match iter.next() { + Some(Ok(element)) => element, + Some(Err(e)) => return Err(e), + None => return decoding_error("expected 1 value, found 0"), + }; + // See if there is a second, unexpected value. + match iter.next() { + Some(Ok(element)) => { + return decoding_error(format!( + "found more than one value; second value: {}", + element + )) + } + Some(Err(e)) => return decoding_error(format!("error after expected value: {}", e)), + None => {} + }; + Ok(only_element) + } + + /// Reads all of the values in the input stream, materializing each into an [Element] and + /// returning the complete sequence as a `Vec`. /// - /// This will return an [`IonError`](crate::result::IonError) if the parser could not - /// be initialized over the given slice. - fn iterate_over<'a, 'b>( - &'a self, - data: &'b [u8], - ) -> IonResult> + 'b>>; + /// If an error occurs while reading, returns `Err(IonError)`. + fn read_all_elements(&mut self) -> IonResult> { + self.elements().collect() + } +} + +impl ElementReader for R +where + R: IonReader, +{ + type ElementIterator<'a> = ElementIterator<'a, R> where R: 'a; - /// Parses given Ion over a given slice into an [`Vec`] returning an - /// [`IonError`](crate::result::IonError) if any error occurs during the parse. - #[inline] - fn read_all(&self, data: &[u8]) -> IonResult> { - self.iterate_over(data)?.collect() + fn read_next_element(&mut self) -> IonResult> { + ElementLoader::for_reader(self).materialize_next() } - /// Parses Ion over a given slice into a single [`Element`] instance. - /// Returns [`IonError`](crate::result::IonError) if any error occurs during the parse - /// or there is more than one top-level [`Element`] in the data. - #[inline] - fn read_one(&self, data: &[u8]) -> IonResult { - let mut iter = self.iterate_over(data)?; - match iter.next() { - Some(Ok(elem)) => { - // make sure there is nothing else - match iter.next() { - None => Ok(elem), - Some(Ok(_)) => { - decoding_error("Expected a single element, but there was more than one") - } - Some(other) => other, - } - } - Some(other) => other, - None => decoding_error("Expected a single element, data was empty"), + fn elements(&mut self) -> ElementIterator { + ElementIterator { reader: self } + } +} + +/// Holds a reference to a given [ElementReader] implementation and yields one [Element] at a time +/// until the stream is exhausted or invalid data is encountered. +pub struct ElementIterator<'a, R: ElementReader> { + reader: &'a mut R, +} + +impl<'a, R: ElementReader> Iterator for ElementIterator<'a, R> { + type Item = IonResult; + + fn next(&mut self) -> Option { + match self.reader.read_next_element() { + Ok(Some(element)) => Some(Ok(element)), + Ok(None) => None, + Err(error) => Some(Err(error)), } } } -/// Returns an implementation defined [`ElementReader`] instance. -pub fn element_reader() -> impl ElementReader { - native_element_reader() +/// Helper type; wraps an [ElementReader] and recursively materializes the next value in the +/// reader's input, reporting any errors that might occur along the way. +struct ElementLoader<'a, R> { + reader: &'a mut R, } -pub fn native_element_reader() -> NativeElementReader { - NativeElementReader {} +impl<'a, R: IonReader> ElementLoader<'a, R> { + pub(crate) fn for_reader(reader: &mut R) -> ElementLoader { + ElementLoader { reader } + } + + /// Advances the reader to the next value in the stream and uses [Self::materialize_current] + /// to materialize it. + pub(crate) fn materialize_next(&mut self) -> IonResult> { + // Advance the reader to the next value + let _ = self.reader.next()?; + self.materialize_current() + } + + /// Recursively materialize the reader's current Ion value and returns it as `Ok(Some(value))`. + /// If there are no more values at this level, returns `Ok(None)`. + /// If an error occurs while materializing the value, returns an `Err`. + /// Calling this method advances the reader and consumes the current value. + fn materialize_current(&mut self) -> IonResult> { + // Collect this item's annotations into a Vec. We have to do this before materializing the + // value itself because materializing a collection requires advancing the reader further. + let mut annotations = Vec::new(); + // Current API limitations require `self.reader.annotations()` to heap allocate its + // iterator even if there aren't annotations. `self.reader.has_annotations()` is trivial + // and allows us to skip the heap allocation in the common case. + if self.reader.has_annotations() { + for annotation in self.reader.annotations() { + annotations.push(annotation?); + } + } + + let value = match self.reader.current() { + // No more values at this level of the stream + StreamItem::Nothing => return Ok(None), + // This is a typed null + StreamItem::Null(ion_type) => Value::Null(ion_type), + // This is a non-null value + StreamItem::Value(ion_type) => { + use crate::IonType::*; + match ion_type { + Null => unreachable!("non-null value had IonType::Null"), + Boolean => Value::Boolean(self.reader.read_bool()?), + Integer => Value::Integer(self.reader.read_integer()?), + Float => Value::Float(self.reader.read_f64()?), + Decimal => Value::Decimal(self.reader.read_decimal()?), + Timestamp => Value::Timestamp(self.reader.read_timestamp()?), + Symbol => Value::Symbol(self.reader.read_symbol()?), + String => Value::String(self.reader.read_string()?), + Clob => Value::Clob(self.reader.read_clob()?), + Blob => Value::Blob(self.reader.read_blob()?), + // It's a collection; recursively materialize all of this value's children + List => Value::List(owned::List::new(self.materialize_sequence()?)), + SExpression => Value::SExp(owned::SExp::new(self.materialize_sequence()?)), + Struct => Value::Struct(self.materialize_struct()?), + } + } + }; + Ok(Some(Element::new(annotations, value))) + } + + /// Steps into the current sequence and materializes each of its children to construct + /// an [Vec]. When all of the the children have been materialized, steps out. + /// The reader MUST be positioned over a list or s-expression when this is called. + fn materialize_sequence(&mut self) -> IonResult> { + let mut child_elements = Vec::new(); + self.reader.step_in()?; + while let Some(element) = self.materialize_next()? { + child_elements.push(element); + } + self.reader.step_out()?; + Ok(child_elements) + } + + /// Steps into the current struct and materializes each of its fields to construct + /// an [OwnedStruct]. When all of the the fields have been materialized, steps out. + /// The reader MUST be positioned over a struct when this is called. + fn materialize_struct(&mut self) -> IonResult { + let mut child_elements = Vec::new(); + self.reader.step_in()?; + while let StreamItem::Value(_) | StreamItem::Null(_) = self.reader.next()? { + let field_name = self.reader.field_name()?; + let value = self + .materialize_current()? + .expect("materialize_current() returned None for user data"); + child_elements.push((field_name, value)); + } + self.reader.step_out()?; + Ok(Struct::from_iter(child_elements.into_iter())) + } } #[cfg(test)] @@ -261,7 +386,7 @@ mod reader_tests { ] )] fn read_and_compare(#[case] input: &[u8], #[case] expected: Vec) -> IonResult<()> { - let actual = element_reader().read_all(input)?; + let actual = Element::read_all(input)?; assert!(expected.ion_eq(&actual)); Ok(()) } diff --git a/src/value/writer.rs b/src/value/writer.rs index da4bd495..2aaab8e4 100644 --- a/src/value/writer.rs +++ b/src/value/writer.rs @@ -21,7 +21,7 @@ pub trait ElementWriter { /// Serializes a collection of [`Element`] as a series of top-level values. /// - /// This will return [`Err`] if writing any element causes a failure. + /// This will return [`Err`] if writing any value causes a failure. fn write_all<'a, I: IntoIterator>( &'a mut self, elements: I, diff --git a/tests/element_test_vectors.rs b/tests/element_test_vectors.rs index 6ece96e1..d2824434 100644 --- a/tests/element_test_vectors.rs +++ b/tests/element_test_vectors.rs @@ -6,7 +6,7 @@ use ion_rs::value::native_writer::NativeElementWriter; use ion_rs::value::owned::{Element, IonSequence}; use ion_rs::value::reader::ElementReader; use ion_rs::value::writer::{ElementWriter, Format, TextKind}; -use ion_rs::{BinaryWriterBuilder, TextWriterBuilder}; +use ion_rs::{BinaryWriterBuilder, Reader, TextWriterBuilder}; use std::fs::read; use std::path::MAIN_SEPARATOR as PATH_SEPARATOR; @@ -37,7 +37,7 @@ type SkipList = &'static [&'static str]; // Once all of the tests are passing, we should work to unify their APIs. trait RoundTrip { /// Encodes `elements` to a buffer in the specified Ion `format` and then reads them back into - /// a `Vec` using the provided reader. + /// a `Vec` using the provided reader. fn roundtrip( elements: &[Element], format: Format, @@ -45,61 +45,48 @@ trait RoundTrip { ) -> IonResult>; } -/// These unit structs implement the [RoundTrip] trait and can be passed throughout the -/// integration tests to dictate which readers/writers should be used in each test. -struct NativeElementWriterApi; - -impl RoundTrip for NativeElementWriterApi { - fn roundtrip( - elements: &[Element], - format: Format, - reader: R, - ) -> IonResult> { - // Unlike the C writer, the Rust writer can write into a growing Vec. - // No need for an aggressive preallocation. - let mut buffer = Vec::with_capacity(2048); - match format { - Format::Text(kind) => { - let writer = match kind { - TextKind::Compact => TextWriterBuilder::new().build(&mut buffer), - TextKind::Lines => TextWriterBuilder::lines().build(&mut buffer), - TextKind::Pretty => TextWriterBuilder::pretty().build(&mut buffer), - }?; - let mut writer = NativeElementWriter::new(writer); - writer.write_all(elements)?; - let _ = writer.finish()?; - } - Format::Binary => { - let binary_writer = BinaryWriterBuilder::new().build(&mut buffer)?; - let mut writer = NativeElementWriter::new(binary_writer); - writer.write_all(elements)?; - let _ = writer.finish()?; - } - }; - - reader.read_all(buffer.as_slice()) - } +/// Serializes all of the given [Element]s to a `Vec` according to the +/// specified [Format]. +fn serialize(format: Format, elements: &[Element]) -> IonResult> { + let mut buffer = Vec::with_capacity(2048); + match format { + Format::Text(kind) => { + let writer = match kind { + TextKind::Compact => TextWriterBuilder::new().build(&mut buffer), + TextKind::Lines => TextWriterBuilder::lines().build(&mut buffer), + TextKind::Pretty => TextWriterBuilder::pretty().build(&mut buffer), + }?; + let mut writer = NativeElementWriter::new(writer); + writer.write_all(elements)?; + let _ = writer.finish()?; + } + Format::Binary => { + let binary_writer = BinaryWriterBuilder::new().build(&mut buffer)?; + let mut writer = NativeElementWriter::new(binary_writer); + writer.write_all(elements)?; + let _ = writer.finish()?; + } + }; + Ok(buffer) } trait ElementApi { - type ReaderApi: ElementReader; - type RoundTripper: RoundTrip; - fn global_skip_list() -> SkipList; fn read_one_equivs_skip_list() -> SkipList; fn round_trip_skip_list() -> SkipList; fn equivs_skip_list() -> SkipList; fn non_equivs_skip_list() -> SkipList; - fn make_reader() -> Self::ReaderApi; + fn make_reader(data: &[u8]) -> IonResult>; /// Asserts the given elements can be round-tripped and equivalent, then returns the new elements. fn assert_round_trip( source_elements: &Vec, format: Format, ) -> IonResult> { - let new_elements = - Self::RoundTripper::roundtrip(source_elements, format, Self::make_reader())?; + let bytes = serialize(format, source_elements)?; + let mut reader = Self::make_reader(&bytes)?; + let new_elements: Vec = reader.read_all_elements()?; assert!( source_elements.ion_eq(&new_elements), "Roundtrip via {:?} failed: {}", @@ -129,7 +116,7 @@ trait ElementApi { format1: Format, format2: Format, ) -> IonResult<()> { - let source_elements = Self::read_file(&Self::make_reader(), file_name)?; + let source_elements = Self::read_file(file_name)?; if contains_path(Self::round_trip_skip_list(), file_name) { return Ok(()); } @@ -171,18 +158,17 @@ trait ElementApi { /// This will parse each string as a [`Vec`] of [`Element`] and apply the `group_assert` function /// for every pair of the parsed data including the identity case (a parsed document is /// compared against itself). - fn read_group_embedded( - reader: &R, - raw_group: &dyn IonSequence, - group_assert: &F, - ) -> IonResult<()> + fn read_group_embedded(raw_group: &dyn IonSequence, group_assert: &F) -> IonResult<()> where - R: ElementReader, F: Fn(&Vec, &Vec), { let group_res: IonResult> = raw_group .iter() - .map(|elem| reader.read_all(elem.as_text().unwrap().as_bytes())) + .map(|elem| { + Self::make_reader(elem.as_text().unwrap().as_bytes())? + .elements() + .collect() + }) .collect(); let group = group_res?; for this in group.iter() { @@ -212,18 +198,13 @@ trait ElementApi { /// /// This would have two groups, one with direct values that will be compared and another /// with embedded Ion text that will be parsed and compared. - fn read_group( - reader: Self::ReaderApi, - file_name: &str, - value_assert: F1, - group_assert: F2, - ) -> IonResult<()> + fn read_group(file_name: &str, value_assert: F1, group_assert: F2) -> IonResult<()> where // group index, value 1 index, value 1, value 2 index, value 2 F1: Fn(usize, usize, &Element, usize, &Element), F2: Fn(&Vec, &Vec), { - let group_lists = Self::read_file(&reader, file_name)?; + let group_lists = Self::read_file(file_name)?; for (group_index, group_list) in group_lists.iter().enumerate() { // every grouping set is a list/sexp // look for the embedded annotation to parse/test as the underlying value @@ -232,7 +213,7 @@ trait ElementApi { .any(|annotation| annotation.text() == Some("embedded_documents")); match (group_list.as_sequence(), is_embedded) { (Some(group), true) => { - Self::read_group_embedded(&reader, group, &group_assert)?; + Self::read_group_embedded(group, &group_assert)?; } (Some(group), false) => { for (this_index, this) in group.iter().enumerate() { @@ -249,13 +230,15 @@ trait ElementApi { Ok(()) } - fn read_file(reader: &Self::ReaderApi, file_name: &str) -> IonResult> { - // TODO have a better API that doesn't require buffering into memory everything... + fn read_file(file_name: &str) -> IonResult> { let data = read(file_name)?; - let result = reader.read_all(&data); + let mut reader = Self::make_reader(&data)?; + let result: IonResult> = reader.read_all_elements(); // do some simple single value reading tests - let single_result = reader.read_one(&data); + let mut reader = Self::make_reader(&data)?; + let single_result: IonResult = reader.read_one_element(); + match &result { Ok(elems) => { if elems.len() == 1 { @@ -266,12 +249,12 @@ trait ElementApi { assert!(elems[0].ion_eq(&elem)) } } - Err(e) => panic!("Expected element {elems:?}, got {e:?}"), + Err(e) => panic!("Expected value {elems:?}, got {e:?}"), } } else { match single_result { Ok(elem) => { - panic!("Did not expect element for duplicates: {elems:?}, {elem:?}") + panic!("Did not expect value for duplicates: {elems:?}, {elem}") } Err(e) => match e { IonError::DecodingError { description: _ } => (), @@ -327,7 +310,7 @@ macro_rules! good_round_trip { fn bad(_element_api: E, file_name: &str) { E::assert_file(E::global_skip_list(), file_name, || { - match E::read_file(&E::make_reader(), file_name) { + match E::read_file(file_name) { Ok(items) => panic!("Expected error, got: {items:?}"), Err(_) => Ok(()), } @@ -338,7 +321,6 @@ fn equivs(_element_api: E, file_name: &str) { let skip_list = concat(E::global_skip_list(), E::equivs_skip_list()); E::assert_file(&skip_list[..], file_name, || { E::read_group( - E::make_reader(), file_name, |group_index, this_index, this, that_index, that| { assert!( @@ -355,7 +337,6 @@ fn non_equivs(_element_api: E, file_name: &str) { let skip_list = concat(E::global_skip_list(), E::non_equivs_skip_list()); E::assert_file(&skip_list[..], file_name, || { E::read_group( - E::make_reader(), file_name, |group_index, this_index, this, that_index, that| { if std::ptr::eq(this, that) { @@ -391,8 +372,7 @@ fn non_equivs(_element_api: E, file_name: &str) { mod impl_display_for_element_tests { use super::*; use ion_rs::value::native_writer::NativeElementWriter; - use ion_rs::value::reader::element_reader; - use ion_rs::TextWriterBuilder; + use ion_rs::{ReaderBuilder, TextWriterBuilder}; use std::fs::read; const TO_STRING_SKIP_LIST: &[&str] = &[ @@ -422,11 +402,13 @@ mod impl_display_for_element_tests { } let data = read(file_name).unwrap(); - let result = element_reader().read_all(&data).unwrap_or_else(|_| { - panic!("Expected to be able to read Ion values for contents of file {file_name}") + let mut reader = ReaderBuilder::default().build(data.as_slice()).unwrap(); + let result: IonResult> = reader.read_all_elements(); + let elements = result.unwrap_or_else(|e| { + panic!("Expected to be able to read Ion values for contents of file {file_name}: {e:?}") }); - for element in result { + for element in elements { let mut buffer = Vec::with_capacity(2048); let mut writer = NativeElementWriter::new(TextWriterBuilder::new().build(&mut buffer).unwrap()); @@ -443,14 +425,11 @@ mod impl_display_for_element_tests { #[cfg(test)] mod native_element_tests { use super::*; - use ion_rs::value::native_reader::NativeElementReader; + use ion_rs::{Reader, ReaderBuilder}; struct NativeElementApi; impl ElementApi for NativeElementApi { - type ReaderApi = NativeElementReader; - type RoundTripper = NativeElementWriterApi; - fn global_skip_list() -> SkipList { &[ // The binary reader does not check whether nested values are longer than their @@ -520,8 +499,8 @@ mod native_element_tests { &[] } - fn make_reader() -> Self::ReaderApi { - NativeElementReader + fn make_reader(data: &[u8]) -> IonResult> { + ReaderBuilder::default().build(data) } } @@ -564,14 +543,13 @@ mod native_element_tests { mod non_blocking_native_element_tests { use super::*; - use ion_rs::value::native_reader::NonBlockingNativeElementReader; + use ion_rs::binary::non_blocking::raw_binary_reader::RawBinaryBufferReader; + use ion_rs::text::non_blocking::raw_text_reader::RawTextReader; + use ion_rs::{RawReader, Reader}; struct NonBlockingNativeElementApi; impl ElementApi for NonBlockingNativeElementApi { - type ReaderApi = NonBlockingNativeElementReader; - type RoundTripper = NativeElementWriterApi; - fn global_skip_list() -> SkipList { &[ // The binary reader does not check whether nested values are longer than their @@ -645,8 +623,20 @@ mod non_blocking_native_element_tests { &[] } - fn make_reader() -> Self::ReaderApi { - NonBlockingNativeElementReader + fn make_reader(data: &[u8]) -> IonResult> { + use ion_rs::binary::constants::v1_0::IVM; + use ion_rs::reader::integration_testing::new_reader; + // If the data is binary, create a non-blocking binary reader. + if data.starts_with(&IVM) { + let mut raw_reader = RawBinaryBufferReader::new(data); + raw_reader.stream_complete(); + Ok(new_reader(raw_reader)) + } else { + // Otherwise, create a non-blocking text reader + let mut raw_reader = RawTextReader::new(data); + raw_reader.stream_complete(); + Ok(new_reader(raw_reader)) + } } } diff --git a/tests/ion_hash_tests.rs b/tests/ion_hash_tests.rs index 17ce93bd..cea5e4fc 100644 --- a/tests/ion_hash_tests.rs +++ b/tests/ion_hash_tests.rs @@ -7,7 +7,7 @@ use ion_rs::ion_hash::IonHasher; use ion_rs::result::{illegal_operation, IonResult}; use ion_rs::types::integer::IntAccess; use ion_rs::value::owned::{Element, Struct}; -use ion_rs::value::reader::{element_reader, ElementReader}; +use ion_rs::value::reader::ElementReader; use ion_rs::value::writer::ElementWriter; use ion_rs::value::*; use ion_rs::IonWriter; @@ -123,7 +123,7 @@ fn ion_hash_tests() -> IonHashTestResult<()> { fn test_file(file_name: &str) -> IonHashTestResult<()> { let data = read(file_name).map_err(|source| ion_rs::IonError::IoError { source })?; - let elems = element_reader().read_all(&data)?; + let elems = Element::read_all(&data)?; test_all(elems) } @@ -156,11 +156,11 @@ fn test_all(elems: Vec) -> IonHashTestResult<()> { let mut bytes = vec![0xE0, 0x01, 0x00, 0xEA]; bytes.extend(value); - let loaded = element_reader().read_all(&bytes)?; + let loaded = Element::read_all(&bytes)?; let elem = loaded .into_iter() .next() - .expect("10n test case should have a single element (there were none)"); + .expect("10n test case should have a single value (there were none)"); test_case(annotated_test_name, &elem, expect) } _ => { From 6f581785f3e8419bc3f086982c2498a15a9570f9 Mon Sep 17 00:00:00 2001 From: Zack Slayton Date: Wed, 15 Mar 2023 16:50:17 -0400 Subject: [PATCH 02/14] Manual fixes for missed renames --- src/ion_hash/mod.rs | 5 ++--- src/value/owned.rs | 2 +- tests/ion_hash_tests.rs | 3 +-- 3 files changed, 4 insertions(+), 6 deletions(-) diff --git a/src/ion_hash/mod.rs b/src/ion_hash/mod.rs index 33e3fbfc..6960fe83 100644 --- a/src/ion_hash/mod.rs +++ b/src/ion_hash/mod.rs @@ -4,13 +4,12 @@ //! //! ## Examples //! ```rust -//! use ion_rs::value::reader::{self, ElementReader}; +//! use ion_rs::value::owned::Element; //! use ion_rs::result::IonResult; //! use ion_rs::ion_hash; //! //! # fn main() -> IonResult<()> { -//! let loader = reader::element_reader(); -//! let elem = loader.elements(b"\"hello world\"")?.next().unwrap()?; +//! let elem = Element::read_one(b"\"hello world\"")?; //! let digest = ion_hash::sha256(&elem); //! println!("{:?}", digest); //! # Ok(()) diff --git a/src/value/owned.rs b/src/value/owned.rs index e78144d1..74b90792 100644 --- a/src/value/owned.rs +++ b/src/value/owned.rs @@ -799,7 +799,7 @@ mod value_tests { ), case::struct_( ion_struct!{"greetings": "hello"}, - Element::parse(r#"{greetings: "hello"}"#).unwrap() + Element::read_one(r#"{greetings: "hello"}"#).unwrap() ), )] fn owned_element_accessors(e1: E1, e2: E2) diff --git a/tests/ion_hash_tests.rs b/tests/ion_hash_tests.rs index cea5e4fc..f1d5a0db 100644 --- a/tests/ion_hash_tests.rs +++ b/tests/ion_hash_tests.rs @@ -7,7 +7,6 @@ use ion_rs::ion_hash::IonHasher; use ion_rs::result::{illegal_operation, IonResult}; use ion_rs::types::integer::IntAccess; use ion_rs::value::owned::{Element, Struct}; -use ion_rs::value::reader::ElementReader; use ion_rs::value::writer::ElementWriter; use ion_rs::value::*; use ion_rs::IonWriter; @@ -351,7 +350,7 @@ mod unknown_symbol_text_tests { #[test] fn test_unknown_annotation_text() { - let mut element = element_reader().read_one("{}".as_bytes()).unwrap(); + let mut element = Element::read_one("{}".as_bytes()).unwrap(); element = element.with_annotations(vec![Symbol::unknown_text()]); let digest = IdentityDigest::hash_element(&element).unwrap(); From 6ea5b68f595ebfd26528bb0baf9a9382c3ae01ac Mon Sep 17 00:00:00 2001 From: Zack Slayton Date: Wed, 15 Mar 2023 17:21:19 -0400 Subject: [PATCH 03/14] Removed old comment --- src/reader.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/reader.rs b/src/reader.rs index 86915098..05e5e72d 100644 --- a/src/reader.rs +++ b/src/reader.rs @@ -122,8 +122,6 @@ pub struct UserReader { } impl UserReader { - // This is `pub` for use in the integration tests (which cannot access `pub(crate)`), - // but we want users to rely on `ReaderBuilder` when possible. pub(crate) fn new(raw_reader: R) -> UserReader { UserReader { raw_reader, From 4760f6f59a64b0e51d7b87a023342ec9ebe1ae1e Mon Sep 17 00:00:00 2001 From: Zack Slayton Date: Wed, 15 Mar 2023 17:25:11 -0400 Subject: [PATCH 04/14] links to GitHub issue 484 --- src/binary/constants.rs | 3 +++ src/lib.rs | 2 ++ src/reader.rs | 1 + 3 files changed, 6 insertions(+) diff --git a/src/binary/constants.rs b/src/binary/constants.rs index cff8bd2e..a9e7cef7 100644 --- a/src/binary/constants.rs +++ b/src/binary/constants.rs @@ -1,3 +1,6 @@ +// This module and its contents are visible as a workaround for: +// https://github.com/amazon-ion/ion-rust/issues/484 + /// Constants for Ion v1.0 pub mod v1_0 { /// Ion Version Marker byte sequence diff --git a/src/lib.rs b/src/lib.rs index e1c8d951..e8b5606e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -14,10 +14,12 @@ pub mod value; pub mod ion_hash; mod catalog; +// Public as a workaround for: https://github.com/amazon-ion/ion-rust/issues/484 pub mod constants; pub mod ion_eq; mod raw_symbol_token; mod raw_symbol_token_ref; +// Public as a workaround for: https://github.com/amazon-ion/ion-rust/issues/484 pub mod reader; mod shared_symbol_table; mod stream_reader; diff --git a/src/reader.rs b/src/reader.rs index 05e5e72d..9bd7e808 100644 --- a/src/reader.rs +++ b/src/reader.rs @@ -133,6 +133,7 @@ impl UserReader { // This module exists to allow our integration tests to directly construct a `UserReader` // with not-yet-supported settings. We want users to use `ReaderBuilder` instead; eventually, // `ReaderBuilder` will also work for the integration tests and we can remove this. +// See: https://github.com/amazon-ion/ion-rust/issues/484 #[doc(hidden)] pub mod integration_testing { use crate::{RawReader, Reader, UserReader}; From 2fbde84f1379dd1fd15ddee7df1acb7d76ae2a97 Mon Sep 17 00:00:00 2001 From: Zack Slayton Date: Wed, 15 Mar 2023 17:27:07 -0400 Subject: [PATCH 05/14] one more link to GitHub issue 484 --- src/binary/mod.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/binary/mod.rs b/src/binary/mod.rs index b988f8c3..fd6b2b70 100644 --- a/src/binary/mod.rs +++ b/src/binary/mod.rs @@ -3,7 +3,9 @@ //! This module provides the necessary structures and logic to read values from a binary Ion //! data stream. +// Public as a workaround for: https://github.com/amazon-ion/ion-rust/issues/484 pub mod binary_writer; + pub mod constants; pub mod decimal; mod header; From dbec27116f66545a47a421a1be5be735057734f4 Mon Sep 17 00:00:00 2001 From: Zack Slayton Date: Wed, 15 Mar 2023 17:30:38 -0400 Subject: [PATCH 06/14] formatting --- src/binary/mod.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/binary/mod.rs b/src/binary/mod.rs index fd6b2b70..748f9ce7 100644 --- a/src/binary/mod.rs +++ b/src/binary/mod.rs @@ -4,9 +4,9 @@ //! data stream. // Public as a workaround for: https://github.com/amazon-ion/ion-rust/issues/484 -pub mod binary_writer; - pub mod constants; + +pub mod binary_writer; pub mod decimal; mod header; pub mod int; From 8f5eefe72bab4979049a68c848a53848309d4d72 Mon Sep 17 00:00:00 2001 From: Zack Slayton Date: Wed, 15 Mar 2023 17:53:20 -0400 Subject: [PATCH 07/14] undoing IDE renames --- src/value/native_writer.rs | 4 ++-- src/value/owned.rs | 2 +- src/value/writer.rs | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/value/native_writer.rs b/src/value/native_writer.rs index b81c3b23..c69a9685 100644 --- a/src/value/native_writer.rs +++ b/src/value/native_writer.rs @@ -26,7 +26,7 @@ impl NativeElementWriter { NativeElementWriter { writer } } - /// Recursively writes the given `value` and its child elements (if any) to the underlying + /// Recursively writes the given `element` and its child elements (if any) to the underlying /// writer. fn write_element(&mut self, field_name: Option<&str>, element: &Element) -> IonResult<()> { if let Some(field_name) = field_name { @@ -48,7 +48,7 @@ impl NativeElementWriter { } match element.ion_type() { - IonType::Null => unreachable!("value has IonType::Null but is_null() was false"), + IonType::Null => unreachable!("element has IonType::Null but is_null() was false"), IonType::Boolean => self.writer.write_bool(element.as_boolean().unwrap()), IonType::Integer => self.writer.write_integer(element.as_integer().unwrap()), IonType::Float => self.writer.write_f64(element.as_float().unwrap()), diff --git a/src/value/owned.rs b/src/value/owned.rs index d885a62f..3bc46a9b 100644 --- a/src/value/owned.rs +++ b/src/value/owned.rs @@ -817,7 +817,7 @@ mod value_tests { E1: Into, E2: Into, { - // assert that both value construction methods create the same element + // assert that both element construction methods create the same element assert_eq!(e1.into(), e2.into()); } diff --git a/src/value/writer.rs b/src/value/writer.rs index 2aaab8e4..da4bd495 100644 --- a/src/value/writer.rs +++ b/src/value/writer.rs @@ -21,7 +21,7 @@ pub trait ElementWriter { /// Serializes a collection of [`Element`] as a series of top-level values. /// - /// This will return [`Err`] if writing any value causes a failure. + /// This will return [`Err`] if writing any element causes a failure. fn write_all<'a, I: IntoIterator>( &'a mut self, elements: I, From 5543e8b1129246f31300a361dbb920087d99647e Mon Sep 17 00:00:00 2001 From: Zack Slayton Date: Thu, 16 Mar 2023 07:59:48 -0400 Subject: [PATCH 08/14] Renamed crate::value to crate::element --- src/{value => element}/builders.rs | 26 +++++++++---------- .../element_stream_reader.rs | 6 ++--- src/{value => element}/iterators.rs | 2 +- src/{value => element}/mod.rs | 2 +- src/{value => element}/native_writer.rs | 10 +++---- src/{value => element}/owned.rs | 10 +++---- src/{value => element}/reader.rs | 10 +++---- src/{value => element}/writer.rs | 2 +- src/ion_hash/element_hasher.rs | 2 +- src/ion_hash/mod.rs | 4 +-- src/ion_hash/representation.rs | 2 +- src/ion_hash/type_qualifier.rs | 2 +- src/lib.rs | 2 +- src/text/text_formatter.rs | 2 +- src/text/text_writer.rs | 2 +- src/types/integer.rs | 10 +++---- tests/element_test_vectors.rs | 10 +++---- tests/ion_hash_tests.rs | 8 +++--- 18 files changed, 56 insertions(+), 56 deletions(-) rename src/{value => element}/builders.rs (96%) rename src/{value => element}/element_stream_reader.rs (99%) rename src/{value => element}/iterators.rs (98%) rename src/{value => element}/mod.rs (99%) rename src/{value => element}/native_writer.rs (94%) rename src/{value => element}/owned.rs (99%) rename src/{value => element}/reader.rs (98%) rename src/{value => element}/writer.rs (97%) diff --git a/src/value/builders.rs b/src/element/builders.rs similarity index 96% rename from src/value/builders.rs rename to src/element/builders.rs index 4896c3cf..4e6792c2 100644 --- a/src/value/builders.rs +++ b/src/element/builders.rs @@ -1,10 +1,10 @@ -use crate::value::owned::{Element, List, SExp, Struct}; +use crate::element::owned::{Element, List, SExp, Struct}; use crate::Symbol; /// Constructs [List] values incrementally. /// /// ``` -/// use ion_rs::value::owned::Element; +/// use ion_rs::element::owned::Element; /// let actual: Element = Element::list_builder() /// .push(1) /// .push(true) @@ -57,7 +57,7 @@ impl ListBuilder { /// Constructs [SExp] values incrementally. /// /// ``` -/// use ion_rs::value::owned::Element; +/// use ion_rs::element::owned::Element; /// let actual: Element = Element::sexp_builder() /// .push(1) /// .push(true) @@ -111,7 +111,7 @@ impl SExpBuilder { /// /// ``` /// use ion_rs::ion_struct; -/// use ion_rs::value::owned::Element; +/// use ion_rs::element::owned::Element; /// let actual: Element = ion_struct! { /// "a": 1, /// "b": true, @@ -123,7 +123,7 @@ impl SExpBuilder { /// /// ``` /// use ion_rs::ion_struct; -/// use ion_rs::value::owned::{Element, Struct}; +/// use ion_rs::element::owned::{Element, Struct}; /// let base_struct: Struct = ion_struct! { /// "foo": 1, /// "bar": 2, @@ -172,7 +172,7 @@ impl StructBuilder { /// /// ``` /// use ion_rs::ion_struct; - /// use ion_rs::value::owned::{Element, Struct}; + /// use ion_rs::element::owned::{Element, Struct}; /// /// let struct1 = ion_struct! { /// "foo": 1, @@ -254,7 +254,7 @@ impl From for Element { /// /// ``` /// use ion_rs::ion_list; -/// use ion_rs::value::owned::Element; +/// use ion_rs::element::owned::Element; /// // Construct a list Element from Rust values /// let actual: Element = ion_list![ /// "foo", @@ -274,7 +274,7 @@ impl From for Element { /// ``` /// // Construct a list Element from existing Elements /// use ion_rs::ion_list; -/// use ion_rs::value::owned::{Element, IntoAnnotatedElement}; +/// use ion_rs::element::owned::{Element, IntoAnnotatedElement}; /// /// let string_element: Element = "foo".into(); /// let bool_element: Element = true.into(); @@ -305,7 +305,7 @@ macro_rules! ion_list { /// /// ``` /// use ion_rs::ion_sexp; -/// use ion_rs::value::owned::Element; +/// use ion_rs::element::owned::Element; /// // Construct an s-expression Element from Rust values /// let actual: Element = ion_sexp!("foo" 7 false ion_sexp!(1.5f64 8.25f64)).into(); /// // Construct an Element from serialized Ion data @@ -320,7 +320,7 @@ macro_rules! ion_list { /// ``` /// // Construct a s-expression Element from existing Elements /// use ion_rs::ion_sexp; -/// use ion_rs::value::owned::{Element, IntoAnnotatedElement}; +/// use ion_rs::element::owned::{Element, IntoAnnotatedElement}; /// /// let string_element: Element = "foo".into(); /// let bool_element: Element = true.into(); @@ -352,7 +352,7 @@ macro_rules! ion_sexp { /// /// ``` /// use ion_rs::{ion_struct, IonType}; -/// use ion_rs::value::owned::Element; +/// use ion_rs::element::owned::Element; /// let field_name_2 = "x"; /// let prefix = "abc"; /// let suffix = "def"; @@ -387,8 +387,8 @@ pub use ion_struct; #[cfg(test)] mod tests { - use crate::value::builders::{ListBuilder, SExpBuilder, StructBuilder}; - use crate::value::owned::Element; + use crate::element::builders::{ListBuilder, SExpBuilder, StructBuilder}; + use crate::element::owned::Element; use crate::Symbol; use crate::{ion_list, ion_sexp, ion_struct}; diff --git a/src/value/element_stream_reader.rs b/src/element/element_stream_reader.rs similarity index 99% rename from src/value/element_stream_reader.rs rename to src/element/element_stream_reader.rs index 1417bdca..9a51363b 100644 --- a/src/value/element_stream_reader.rs +++ b/src/element/element_stream_reader.rs @@ -1,8 +1,8 @@ use crate::result::{decoding_error, illegal_operation, illegal_operation_raw}; use crate::text::parent_container::ParentContainer; -use crate::value::iterators::SymbolsIterator; -use crate::value::owned::Element; +use crate::element::iterators::SymbolsIterator; +use crate::element::owned::Element; use crate::{ Decimal, Integer, IonError, IonReader, IonResult, IonType, StreamItem, Symbol, Timestamp, }; @@ -382,11 +382,11 @@ mod reader_tests { use rstest::*; use super::*; + use crate::element::owned::Value; use crate::result::IonResult; use crate::stream_reader::IonReader; use crate::types::decimal::Decimal; use crate::types::timestamp::Timestamp; - use crate::value::owned::Value; use crate::IonType; fn load_element(text: &str) -> Element { diff --git a/src/value/iterators.rs b/src/element/iterators.rs similarity index 98% rename from src/value/iterators.rs rename to src/element/iterators.rs index 71def5fe..f79e1717 100644 --- a/src/value/iterators.rs +++ b/src/element/iterators.rs @@ -1,4 +1,4 @@ -use crate::value::owned::Element; +use crate::element::owned::Element; use crate::Symbol; use smallvec::SmallVec; // This macro defines a new iterator type for a given `Iterator => Item` type name pair. diff --git a/src/value/mod.rs b/src/element/mod.rs similarity index 99% rename from src/value/mod.rs rename to src/element/mod.rs index 880eb17a..5f0ac616 100644 --- a/src/value/mod.rs +++ b/src/element/mod.rs @@ -22,8 +22,8 @@ pub mod writer; #[cfg(test)] mod tests { + use crate::element::owned::*; use crate::types::timestamp::Timestamp; - use crate::value::owned::*; use crate::{ion_list, ion_sexp, ion_struct, Decimal, Integer, IonType, Symbol}; use chrono::*; use rstest::*; diff --git a/src/value/native_writer.rs b/src/element/native_writer.rs similarity index 94% rename from src/value/native_writer.rs rename to src/element/native_writer.rs index c69a9685..5f2a112b 100644 --- a/src/value/native_writer.rs +++ b/src/element/native_writer.rs @@ -1,5 +1,5 @@ -use crate::value::owned::Element; -use crate::value::writer::ElementWriter; +use crate::element::owned::Element; +use crate::element::writer::ElementWriter; use crate::{IonResult, IonType, IonWriter, RawSymbolTokenRef}; /// Writes [`Element`] instances to the underlying [`IonWriter`] implementation. @@ -80,11 +80,11 @@ impl NativeElementWriter { #[cfg(test)] mod tests { + use crate::element::native_writer::NativeElementWriter; + use crate::element::owned::Element; + use crate::element::writer::ElementWriter; use crate::ion_eq::IonEq; use crate::text::text_writer::TextWriterBuilder; - use crate::value::native_writer::NativeElementWriter; - use crate::value::owned::Element; - use crate::value::writer::ElementWriter; use crate::IonResult; use nom::AsBytes; diff --git a/src/value/owned.rs b/src/element/owned.rs similarity index 99% rename from src/value/owned.rs rename to src/element/owned.rs index 3bc46a9b..c970da11 100644 --- a/src/value/owned.rs +++ b/src/element/owned.rs @@ -11,12 +11,12 @@ use std::collections::HashMap; use std::fmt::{Display, Formatter}; use std::iter::FromIterator; -use crate::symbol_ref::AsSymbolRef; -use crate::value::builders::{ListBuilder, SExpBuilder, StructBuilder}; -use crate::value::iterators::{ +use crate::element::builders::{ListBuilder, SExpBuilder, StructBuilder}; +use crate::element::iterators::{ ElementsIterator, FieldIterator, FieldValuesIterator, IndexVec, SymbolsIterator, }; -use crate::value::reader::ElementReader; +use crate::element::reader::ElementReader; +use crate::symbol_ref::AsSymbolRef; impl Element { pub fn null(null_type: IonType) -> Element { @@ -575,7 +575,7 @@ impl From for Value { /// /// ``` /// use ion_rs::ion_list; -/// use ion_rs::value::owned::{Element, IntoAnnotatedElement, Value}; +/// use ion_rs::element::owned::{Element, IntoAnnotatedElement, Value}; /// /// // Explicit conversion of a Rust bool (`true`) into a `Value`... /// let boolean_value: Value = true.into(); diff --git a/src/value/reader.rs b/src/element/reader.rs similarity index 98% rename from src/value/reader.rs rename to src/element/reader.rs index 043f3203..b3ee96c0 100644 --- a/src/value/reader.rs +++ b/src/element/reader.rs @@ -3,9 +3,9 @@ //! Provides APIs to read Ion data into [Element] from different sources such //! as slices or files. +use crate::element::owned; +use crate::element::owned::{Element, Struct, Value}; use crate::result::{decoding_error, IonResult}; -use crate::value::owned; -use crate::value::owned::{Element, Struct, Value}; use crate::{IonReader, StreamItem, Symbol}; /// Reads Ion data into [`Element`] instances. @@ -194,12 +194,12 @@ impl<'a, R: IonReader> ElementLoader<'a, R> #[cfg(test)] mod reader_tests { use super::*; + use crate::element::builders::{ion_list, ion_sexp, ion_struct}; + use crate::element::owned::Value::*; + use crate::element::owned::{Element, IntoAnnotatedElement}; use crate::ion_eq::IonEq; use crate::types::integer::Integer; use crate::types::timestamp::Timestamp as TS; - use crate::value::builders::{ion_list, ion_sexp, ion_struct}; - use crate::value::owned::Value::*; - use crate::value::owned::{Element, IntoAnnotatedElement}; use crate::{IonType, Symbol}; use bigdecimal::BigDecimal; use num_bigint::BigInt; diff --git a/src/value/writer.rs b/src/element/writer.rs similarity index 97% rename from src/value/writer.rs rename to src/element/writer.rs index da4bd495..d6b6b429 100644 --- a/src/value/writer.rs +++ b/src/element/writer.rs @@ -5,7 +5,7 @@ use crate::result::IonResult; -use crate::value::owned::Element; +use crate::element::owned::Element; pub use Format::*; pub use TextKind::*; diff --git a/src/ion_hash/element_hasher.rs b/src/ion_hash/element_hasher.rs index dfa1b4f2..fe01ea2c 100644 --- a/src/ion_hash/element_hasher.rs +++ b/src/ion_hash/element_hasher.rs @@ -5,7 +5,7 @@ use std::io; -use crate::value::owned::Element; +use crate::element::owned::Element; use crate::IonResult; use digest::{FixedOutput, Output, Reset, Update}; diff --git a/src/ion_hash/mod.rs b/src/ion_hash/mod.rs index 6960fe83..d61c712b 100644 --- a/src/ion_hash/mod.rs +++ b/src/ion_hash/mod.rs @@ -4,7 +4,7 @@ //! //! ## Examples //! ```rust -//! use ion_rs::value::owned::Element; +//! use ion_rs::element::owned::Element; //! use ion_rs::result::IonResult; //! use ion_rs::ion_hash; //! @@ -18,7 +18,7 @@ use digest::{self, FixedOutput, Output, Reset, Update}; -use crate::value::owned::Element; +use crate::element::owned::Element; use crate::IonResult; use element_hasher::ElementHasher; diff --git a/src/ion_hash/representation.rs b/src/ion_hash/representation.rs index d945b8cf..dea789cb 100644 --- a/src/ion_hash/representation.rs +++ b/src/ion_hash/representation.rs @@ -7,11 +7,11 @@ //! and not speed. use crate::binary::{self, decimal::DecimalBinaryEncoder, timestamp::TimestampBinaryEncoder}; +use crate::element::owned::{Element, IonSequence, List, SExp, Struct}; use crate::ion_hash::element_hasher::ElementHasher; use crate::ion_hash::type_qualifier::type_qualifier_symbol; use crate::types::decimal::Decimal; use crate::types::integer::Integer; -use crate::value::owned::{Element, IonSequence, List, SExp, Struct}; use crate::{result::IonResult, types::timestamp::Timestamp, IonType, Symbol}; use digest::{FixedOutput, Output, Reset, Update}; diff --git a/src/ion_hash/type_qualifier.rs b/src/ion_hash/type_qualifier.rs index 5504116b..3e7f2834 100644 --- a/src/ion_hash/type_qualifier.rs +++ b/src/ion_hash/type_qualifier.rs @@ -6,7 +6,7 @@ use std::slice; ///! ///! [spec]: https://amazon-ion.github.io/ion-hash/docs/spec.html. use crate::binary::IonTypeCode; -use crate::value::owned::{Element, List, SExp, Struct}; +use crate::element::owned::{Element, List, SExp, Struct}; use crate::{Decimal, Integer, IonType, Symbol, Timestamp}; use num_bigint::Sign; diff --git a/src/lib.rs b/src/lib.rs index e8b5606e..b719ba3f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -5,10 +5,10 @@ pub mod result; pub mod binary; pub mod data_source; +pub mod element; pub mod raw_reader; pub mod text; pub mod types; -pub mod value; #[cfg(feature = "ion-hash")] pub mod ion_hash; diff --git a/src/text/text_formatter.rs b/src/text/text_formatter.rs index b9d00e6e..9ca13ee2 100644 --- a/src/text/text_formatter.rs +++ b/src/text/text_formatter.rs @@ -1,5 +1,5 @@ +use crate::element::owned::{IonSequence, List, SExp, Struct}; use crate::raw_symbol_token_ref::AsRawSymbolTokenRef; -use crate::value::owned::{IonSequence, List, SExp, Struct}; use crate::{Decimal, Integer, IonResult, IonType, RawSymbolTokenRef, Symbol, Timestamp}; pub const STRING_ESCAPE_CODES: &[&str] = &string_escape_code_init(); diff --git a/src/text/text_writer.rs b/src/text/text_writer.rs index b55a25a1..33357d92 100644 --- a/src/text/text_writer.rs +++ b/src/text/text_writer.rs @@ -1,9 +1,9 @@ +use crate::element::writer::TextKind; use crate::raw_symbol_token_ref::{AsRawSymbolTokenRef, RawSymbolTokenRef}; use crate::result::{illegal_operation, IonResult}; use crate::text::raw_text_writer::RawTextWriter; use crate::types::decimal::Decimal; use crate::types::timestamp::Timestamp; -use crate::value::writer::TextKind; use crate::writer::IonWriter; use crate::{Integer, IonType, RawTextWriterBuilder, SymbolTable}; use delegate::delegate; diff --git a/src/types/integer.rs b/src/types/integer.rs index 78345cc7..f9cd83bf 100644 --- a/src/types/integer.rs +++ b/src/types/integer.rs @@ -1,5 +1,5 @@ +use crate::element::owned::Element; use crate::result::{decoding_error, IonError}; -use crate::value::owned::Element; use num_bigint::{BigInt, BigUint, ToBigUint}; use num_traits::{ToPrimitive, Zero}; use std::cmp::Ordering; @@ -12,8 +12,8 @@ pub trait IntAccess { /// /// ## Usage /// ``` - /// # use ion_rs::value::*; - /// # use ion_rs::value::owned::*; + /// # use ion_rs::element::*; + /// # use ion_rs::element::owned::*; /// # use ion_rs::types::integer::*; /// # use num_bigint::*; /// let big_int = Integer::BigInt(BigInt::from(100)); @@ -35,8 +35,8 @@ pub trait IntAccess { /// /// ## Usage /// ``` - /// # use ion_rs::value::*; - /// # use ion_rs::value::owned::*; + /// # use ion_rs::element::*; + /// # use ion_rs::element::owned::*; /// # use ion_rs::types::integer::*; /// # use num_bigint::*; /// # use std::str::FromStr; diff --git a/tests/element_test_vectors.rs b/tests/element_test_vectors.rs index 4847d82f..a4cd1bd9 100644 --- a/tests/element_test_vectors.rs +++ b/tests/element_test_vectors.rs @@ -1,11 +1,11 @@ // Copyright Amazon.com, Inc. or its affiliates. +use ion_rs::element::native_writer::NativeElementWriter; +use ion_rs::element::owned::{Element, IonSequence}; +use ion_rs::element::reader::ElementReader; +use ion_rs::element::writer::{ElementWriter, Format, TextKind}; use ion_rs::ion_eq::IonEq; use ion_rs::result::{decoding_error, IonError, IonResult}; -use ion_rs::value::native_writer::NativeElementWriter; -use ion_rs::value::owned::{Element, IonSequence}; -use ion_rs::value::reader::ElementReader; -use ion_rs::value::writer::{ElementWriter, Format, TextKind}; use ion_rs::{BinaryWriterBuilder, Reader, TextWriterBuilder}; use std::fs::read; @@ -371,7 +371,7 @@ fn non_equivs(_element_api: E, file_name: &str) { #[cfg(test)] mod impl_display_for_element_tests { use super::*; - use ion_rs::value::native_writer::NativeElementWriter; + use ion_rs::element::native_writer::NativeElementWriter; use ion_rs::TextWriterBuilder; use std::fs::read; diff --git a/tests/ion_hash_tests.rs b/tests/ion_hash_tests.rs index 50ee0c66..c0e077f9 100644 --- a/tests/ion_hash_tests.rs +++ b/tests/ion_hash_tests.rs @@ -3,12 +3,12 @@ use digest::consts::U4096; use digest::{FixedOutput, Reset, Update}; +use ion_rs::element::owned::{Element, Struct}; +use ion_rs::element::writer::ElementWriter; +use ion_rs::element::*; use ion_rs::ion_hash::IonHasher; use ion_rs::result::{illegal_operation, IonResult}; use ion_rs::types::integer::IntAccess; -use ion_rs::value::owned::{Element, Struct}; -use ion_rs::value::writer::ElementWriter; -use ion_rs::value::*; use ion_rs::IonWriter; use std::convert::From; use std::fmt::Debug; @@ -260,7 +260,7 @@ fn expected_hash(struct_: &Struct) -> IonResult> { fn test_case_name_from_value(test_input_ion: &Element) -> IonResult { let mut buf = Vec::new(); let text_writer = ion_rs::TextWriterBuilder::new().build(&mut buf)?; - let mut element_writer = ion_rs::value::native_writer::NativeElementWriter::new(text_writer); + let mut element_writer = ion_rs::element::native_writer::NativeElementWriter::new(text_writer); element_writer.write(test_input_ion)?; let mut text_writer = element_writer.finish()?; text_writer.flush()?; From 4ff980f874d373236095feb064521687ccb2d4fa Mon Sep 17 00:00:00 2001 From: Zack Slayton Date: Thu, 16 Mar 2023 08:00:33 -0400 Subject: [PATCH 09/14] Rename IonType::SExpression to IonType::SExp --- examples/read_all_values.rs | 2 +- src/binary/non_blocking/raw_binary_reader.rs | 6 +++--- src/binary/non_blocking/type_descriptor.rs | 2 +- src/binary/raw_binary_reader.rs | 6 +++--- src/binary/raw_binary_writer.rs | 12 ++++++------ src/binary/type_code.rs | 2 +- src/element/element_stream_reader.rs | 6 +++--- src/element/mod.rs | 2 +- src/element/native_writer.rs | 2 +- src/element/owned.rs | 6 +++--- src/element/reader.rs | 2 +- src/ion_hash/representation.rs | 2 +- src/ion_hash/type_qualifier.rs | 2 +- src/text/non_blocking/raw_text_reader.rs | 14 +++++++------- src/text/parsers/null.rs | 4 ++-- src/text/raw_text_reader.rs | 10 +++++----- src/text/raw_text_writer.rs | 8 ++++---- src/text/text_formatter.rs | 2 +- src/text/text_value.rs | 2 +- src/types/mod.rs | 6 +++--- src/writer.rs | 2 +- tests/good_test_vectors.rs | 2 +- 22 files changed, 51 insertions(+), 51 deletions(-) diff --git a/examples/read_all_values.rs b/examples/read_all_values.rs index ad3503b4..71a21f3e 100644 --- a/examples/read_all_values.rs +++ b/examples/read_all_values.rs @@ -60,7 +60,7 @@ fn read_all_values(reader: &mut R) -> IonResult { Value(ion_type) => { count += 1; match ion_type { - Struct | List | SExpression => reader.step_in()?, + Struct | List | SExp => reader.step_in()?, String => { reader.map_string(|_s| ())?; } diff --git a/src/binary/non_blocking/raw_binary_reader.rs b/src/binary/non_blocking/raw_binary_reader.rs index b9d31c23..699871d1 100644 --- a/src/binary/non_blocking/raw_binary_reader.rs +++ b/src/binary/non_blocking/raw_binary_reader.rs @@ -272,7 +272,7 @@ impl ContainerType { pub fn ion_type(&self) -> IonType { match self { ContainerType::List => IonType::List, - ContainerType::SExpression => IonType::SExpression, + ContainerType::SExpression => IonType::SExp, ContainerType::Struct => IonType::Struct, } } @@ -885,7 +885,7 @@ impl> IonReader for RawBinaryBufferReader { let container_type = match value.header.ion_type { IonType::List => ContainerType::List, - IonType::SExpression => ContainerType::SExpression, + IonType::SExp => ContainerType::SExpression, IonType::Struct => ContainerType::Struct, _other => { return illegal_operation( @@ -1759,7 +1759,7 @@ mod tests { let item = reader.next()?; assert_eq!(item, RawStreamItem::VersionMarker(1, 0)); let item = reader.next()?; - assert_eq!(item, RawStreamItem::Value(IonType::SExpression)); + assert_eq!(item, RawStreamItem::Value(IonType::SExp)); reader.step_in()?; expect_value(reader.next(), IonType::Struct); reader.step_in()?; diff --git a/src/binary/non_blocking/type_descriptor.rs b/src/binary/non_blocking/type_descriptor.rs index a0d357af..6bf9650f 100644 --- a/src/binary/non_blocking/type_descriptor.rs +++ b/src/binary/non_blocking/type_descriptor.rs @@ -75,7 +75,7 @@ impl TypeDescriptor { Clob => Some(IonType::Clob), Blob => Some(IonType::Blob), List => Some(IonType::List), - SExpression => Some(IonType::SExpression), + SExpression => Some(IonType::SExp), Struct => Some(IonType::Struct), AnnotationOrIvm => None, Reserved => None, diff --git a/src/binary/raw_binary_reader.rs b/src/binary/raw_binary_reader.rs index d946c4a4..130aa0ae 100644 --- a/src/binary/raw_binary_reader.rs +++ b/src/binary/raw_binary_reader.rs @@ -697,7 +697,7 @@ impl IonReader for RawBinaryReader { use std::mem; self.cursor.is_in_struct = match self.cursor.value.ion_type { Struct => true, - List | SExpression => false, + List | SExp => false, _ => panic!("You cannot step into a(n) {:?}", self.cursor.value.ion_type), }; self.cursor.parents.push(EncodedValue::default()); @@ -1500,7 +1500,7 @@ mod tests { #[test] fn test_read_s_expression_empty() -> IonResult<()> { let mut cursor = ion_cursor_for(&[0xC0]); - assert_eq!(cursor.next()?, Value(IonType::SExpression)); + assert_eq!(cursor.next()?, Value(IonType::SExp)); cursor.step_in()?; assert_eq!(cursor.next()?, Nothing); cursor.step_out()?; @@ -1510,7 +1510,7 @@ mod tests { #[test] fn test_read_s_expression_123() -> IonResult<()> { let mut cursor = ion_cursor_for(&[0xC6, 0x21, 0x01, 0x21, 0x02, 0x21, 0x03]); - assert_eq!(cursor.next()?, Value(IonType::SExpression)); + assert_eq!(cursor.next()?, Value(IonType::SExp)); let mut sexp = vec![]; cursor.step_in()?; while let Value(IonType::Integer) = cursor.next()? { diff --git a/src/binary/raw_binary_writer.rs b/src/binary/raw_binary_writer.rs index dbcf3139..1813ae84 100644 --- a/src/binary/raw_binary_writer.rs +++ b/src/binary/raw_binary_writer.rs @@ -557,7 +557,7 @@ impl IonWriter for RawBinaryWriter { IonType::Clob => 0x9F, IonType::Blob => 0xAF, IonType::List => 0xBF, - IonType::SExpression => 0xCF, + IonType::SExp => 0xCF, IonType::Struct => 0xDF, }; enc_buffer.push(byte); @@ -729,7 +729,7 @@ impl IonWriter for RawBinaryWriter { use IonType::*; let container_type = match ion_type { List => ContainerType::List, - SExpression => ContainerType::SExpression, + SExp => ContainerType::SExpression, Struct => ContainerType::Struct, _ => return illegal_operation("Cannot step into a scalar Ion type."), }; @@ -787,7 +787,7 @@ impl IonWriter for RawBinaryWriter { ContainerType::TopLevel => None, ContainerType::Struct => Some(IonType::Struct), ContainerType::List => Some(IonType::List), - ContainerType::SExpression => Some(IonType::SExpression), + ContainerType::SExpression => Some(IonType::SExp), } } @@ -980,7 +980,7 @@ mod writer_tests { IonType::Clob, IonType::Blob, IonType::List, - IonType::SExpression, + IonType::SExp, IonType::Struct, ]; @@ -1184,7 +1184,7 @@ mod writer_tests { } fn expect_s_expression(reader: &mut TestReader) { - expect_container(reader, IonType::SExpression); + expect_container(reader, IonType::SExp); } fn expect_struct(reader: &mut TestReader) { @@ -1315,7 +1315,7 @@ mod writer_tests { // foo::(true) writer.set_annotations([10]); - writer.step_in(IonType::SExpression)?; + writer.step_in(IonType::SExp)?; writer.write_bool(true)?; writer.step_out()?; diff --git a/src/binary/type_code.rs b/src/binary/type_code.rs index 781780a1..ad7ebf89 100644 --- a/src/binary/type_code.rs +++ b/src/binary/type_code.rs @@ -52,7 +52,7 @@ impl TryFrom for IonType { Clob => IonType::Clob, Blob => IonType::Blob, List => IonType::List, - SExpression => IonType::SExpression, + SExpression => IonType::SExp, Struct => IonType::Struct, _ => { return decoding_error(format!( diff --git a/src/element/element_stream_reader.rs b/src/element/element_stream_reader.rs index 9a51363b..591d4591 100644 --- a/src/element/element_stream_reader.rs +++ b/src/element/element_stream_reader.rs @@ -108,7 +108,7 @@ impl ElementStreamReader { fn container_values(value: Element) -> Box, Element)>> { match value.ion_type() { - IonType::List | IonType::SExpression => Box::new( + IonType::List | IonType::SExp => Box::new( value .as_sequence() .unwrap() @@ -452,7 +452,7 @@ mod reader_tests { next_type(reader, IonType::Struct, false); reader.step_in()?; next_type(reader, IonType::Integer, false); - next_type(reader, IonType::SExpression, false); + next_type(reader, IonType::SExp, false); reader.step_in()?; next_type(reader, IonType::Boolean, false); next_type(reader, IonType::Boolean, false); @@ -591,7 +591,7 @@ mod reader_tests { "#, ); let mut reader = ElementStreamReader::new(pretty_ion); - assert_eq!(reader.next()?, StreamItem::Value(IonType::SExpression)); + assert_eq!(reader.next()?, StreamItem::Value(IonType::SExp)); reader.step_in()?; assert_eq!(reader.next()?, StreamItem::Value(IonType::Struct)); diff --git a/src/element/mod.rs b/src/element/mod.rs index 5f0ac616..38f1e1f3 100644 --- a/src/element/mod.rs +++ b/src/element/mod.rs @@ -447,7 +447,7 @@ mod tests { fn sexp_case() -> Case { Case { elem: ion_sexp!(true false).into(), - ion_type: IonType::SExpression, + ion_type: IonType::SExp, ops: vec![AsSExp, AsSequence], op_assert: Box::new(|e: &Element| { let actual = e.as_sexp().unwrap(); diff --git a/src/element/native_writer.rs b/src/element/native_writer.rs index 5f2a112b..785e6ee3 100644 --- a/src/element/native_writer.rs +++ b/src/element/native_writer.rs @@ -60,7 +60,7 @@ impl NativeElementWriter { IonType::String => self.writer.write_string(element.as_text().unwrap()), IonType::Clob => self.writer.write_clob(element.as_lob().unwrap()), IonType::Blob => self.writer.write_blob(element.as_lob().unwrap()), - IonType::List | IonType::SExpression => { + IonType::List | IonType::SExp => { self.writer.step_in(element.ion_type())?; for value in element.as_sequence().unwrap().iter() { self.write(value)?; diff --git a/src/element/owned.rs b/src/element/owned.rs index c970da11..349fa3ff 100644 --- a/src/element/owned.rs +++ b/src/element/owned.rs @@ -615,7 +615,7 @@ impl Element { Boolean(_) => IonType::Boolean, Blob(_) => IonType::Blob, Clob(_) => IonType::Clob, - SExp(_) => IonType::SExpression, + SExp(_) => IonType::SExp, List(_) => IonType::List, Struct(_) => IonType::Struct, } @@ -828,7 +828,7 @@ mod value_tests { fn owned_container_len_test>(#[case] container: I, #[case] length: usize) { let container = container.into(); match container.ion_type() { - IonType::List | IonType::SExpression => { + IonType::List | IonType::SExp => { // check length for given sequence value assert_eq!(container.as_sequence().unwrap().len(), length); } @@ -854,7 +854,7 @@ mod value_tests { ) { let container = container.into(); match container.ion_type() { - IonType::List | IonType::SExpression => { + IonType::List | IonType::SExp => { // check length for given sequence value assert_eq!(container.as_sequence().unwrap().is_empty(), is_empty); } diff --git a/src/element/reader.rs b/src/element/reader.rs index b3ee96c0..94657731 100644 --- a/src/element/reader.rs +++ b/src/element/reader.rs @@ -152,7 +152,7 @@ impl<'a, R: IonReader> ElementLoader<'a, R> Blob => Value::Blob(self.reader.read_blob()?), // It's a collection; recursively materialize all of this value's children List => Value::List(owned::List::new(self.materialize_sequence()?)), - SExpression => Value::SExp(owned::SExp::new(self.materialize_sequence()?)), + SExp => Value::SExp(owned::SExp::new(self.materialize_sequence()?)), Struct => Value::Struct(self.materialize_struct()?), } } diff --git a/src/ion_hash/representation.rs b/src/ion_hash/representation.rs index dea789cb..6134856f 100644 --- a/src/ion_hash/representation.rs +++ b/src/ion_hash/representation.rs @@ -27,7 +27,7 @@ pub(crate) trait RepresentationEncoder { IonType::String => self.write_repr_string(elem.as_string())?, IonType::Clob | IonType::Blob => self.write_repr_blob(elem.as_lob())?, IonType::List => self.write_repr_list(elem.as_list())?, - IonType::SExpression => self.write_repr_sexp(elem.as_sexp())?, + IonType::SExp => self.write_repr_sexp(elem.as_sexp())?, IonType::Struct => self.write_repr_struct(elem.as_struct())?, } diff --git a/src/ion_hash/type_qualifier.rs b/src/ion_hash/type_qualifier.rs index 3e7f2834..2abf8ff6 100644 --- a/src/ion_hash/type_qualifier.rs +++ b/src/ion_hash/type_qualifier.rs @@ -48,7 +48,7 @@ impl TypeQualifier { IonType::Clob => type_qualifier_clob(elem.as_lob()), IonType::Blob => type_qualifier_blob(elem.as_lob()), IonType::List => type_qualifier_list(elem.as_list()), - IonType::SExpression => type_qualifier_sexp(elem.as_sexp()), + IonType::SExp => type_qualifier_sexp(elem.as_sexp()), IonType::Struct => type_qualifier_struct(elem.as_struct()), } } diff --git a/src/text/non_blocking/raw_text_reader.rs b/src/text/non_blocking/raw_text_reader.rs index 27d6ae3c..4ef282d2 100644 --- a/src/text/non_blocking/raw_text_reader.rs +++ b/src/text/non_blocking/raw_text_reader.rs @@ -170,7 +170,7 @@ impl> RawTextReader { // IonType of the parent container. let value = match parent.ion_type() { IonType::List => self.next_list_value(), - IonType::SExpression => self.next_s_expression_value(), + IonType::SExp => self.next_s_expression_value(), IonType::Struct => { self.buffer.checkpoint(); if let Some(field_name) = self.next_struct_field_name()? { @@ -272,7 +272,7 @@ impl> RawTextReader { IonType::List => { self.parse_expected("list delimiter or end", list_delimiter)?; } - IonType::SExpression => { + IonType::SExp => { self.parse_expected("s-expression delimiter or end", s_expression_delimiter)?; } IonType::Struct => { @@ -1077,7 +1077,7 @@ mod reader_tests { assert_eq!(reader.read_i64()?, 1); reader.step_out()?; // This should have skipped over the `2, 3` at the end of the list. - next_type(reader, IonType::SExpression, false); + next_type(reader, IonType::SExp, false); // Don't step into the s-expression. Instead, skip over it. next_type(reader, IonType::Integer, false); assert_eq!(reader.read_i64()?, 6); @@ -1115,7 +1115,7 @@ mod reader_tests { next_type(reader, IonType::Struct, false); reader.step_in()?; next_type(reader, IonType::Integer, false); - next_type(reader, IonType::SExpression, false); + next_type(reader, IonType::SExp, false); reader.step_in()?; next_type(reader, IonType::Boolean, false); next_type(reader, IonType::Boolean, false); @@ -1261,7 +1261,7 @@ mod reader_tests { reader.step_out()?; // Reading an s-expression: ('''foo''') - next_type(reader, IonType::SExpression, false); + next_type(reader, IonType::SExp, false); reader.step_in()?; next_type(reader, IonType::String, false); assert_eq!(reader.read_string()?, String::from("foo")); @@ -1388,7 +1388,7 @@ mod reader_tests { reader.step_out()?; // Reading an s-expression: haumea::makemake::eris::ceres::(++ -- &&&&&) - next_type(reader, IonType::SExpression, false); + next_type(reader, IonType::SExp, false); annotations_eq(reader, ["haumea", "makemake", "eris", "ceres"]); reader.step_in()?; next_type(reader, IonType::Symbol, false); @@ -1419,7 +1419,7 @@ mod reader_tests { ) "#; let mut reader = RawTextReader::new(&pretty_ion[..]); - assert_eq!(reader.next()?, RawStreamItem::Value(IonType::SExpression)); + assert_eq!(reader.next()?, RawStreamItem::Value(IonType::SExp)); reader.step_in()?; assert_eq!(reader.next()?, RawStreamItem::Value(IonType::Struct)); diff --git a/src/text/parsers/null.rs b/src/text/parsers/null.rs index 77da0420..ea5cea54 100644 --- a/src/text/parsers/null.rs +++ b/src/text/parsers/null.rs @@ -44,7 +44,7 @@ fn ion_type_from_text(text: &str) -> Option { "clob" => Clob, "struct" => Struct, "list" => List, - "sexp" => SExpression, + "sexp" => SExp, _ => return None, }; Some(ion_type) @@ -80,7 +80,7 @@ mod null_parsing_tests { parse_equals("null.blob ", Blob); parse_equals("null.clob ", Clob); parse_equals("null.list ", List); - parse_equals("null.sexp ", SExpression); + parse_equals("null.sexp ", SExp); parse_equals("null.struct ", Struct); // Misspelled null diff --git a/src/text/raw_text_reader.rs b/src/text/raw_text_reader.rs index 151387f6..7d3aaeaa 100644 --- a/src/text/raw_text_reader.rs +++ b/src/text/raw_text_reader.rs @@ -266,7 +266,7 @@ mod reader_tests { assert_eq!(reader.read_i64()?, 1); reader.step_out()?; // This should have skipped over the `2, 3` at the end of the list. - next_type(reader, IonType::SExpression, false); + next_type(reader, IonType::SExp, false); // Don't step into the s-expression. Instead, skip over it. next_type(reader, IonType::Integer, false); assert_eq!(reader.read_i64()?, 6); @@ -304,7 +304,7 @@ mod reader_tests { next_type(reader, IonType::Struct, false); reader.step_in()?; next_type(reader, IonType::Integer, false); - next_type(reader, IonType::SExpression, false); + next_type(reader, IonType::SExp, false); reader.step_in()?; next_type(reader, IonType::Boolean, false); next_type(reader, IonType::Boolean, false); @@ -422,7 +422,7 @@ mod reader_tests { reader.step_out()?; // Reading an s-expression: ('''foo''') - next_type(reader, IonType::SExpression, false); + next_type(reader, IonType::SExp, false); reader.step_in()?; next_type(reader, IonType::String, false); assert_eq!(reader.read_string()?, String::from("foo")); @@ -548,7 +548,7 @@ mod reader_tests { reader.step_out()?; // Reading an s-expression: haumea::makemake::eris::ceres::(++ -- &&&&&) - next_type(reader, IonType::SExpression, false); + next_type(reader, IonType::SExp, false); annotations_eq(reader, ["haumea", "makemake", "eris", "ceres"]); reader.step_in()?; next_type(reader, IonType::Symbol, false); @@ -579,7 +579,7 @@ mod reader_tests { ) "#; let mut reader = RawTextReader::new(&pretty_ion[..])?; - assert_eq!(reader.next()?, RawStreamItem::Value(IonType::SExpression)); + assert_eq!(reader.next()?, RawStreamItem::Value(IonType::SExp)); reader.step_in()?; assert_eq!(reader.next()?, RawStreamItem::Value(IonType::Struct)); diff --git a/src/text/raw_text_writer.rs b/src/text/raw_text_writer.rs index fa48839b..979e4b76 100644 --- a/src/text/raw_text_writer.rs +++ b/src/text/raw_text_writer.rs @@ -502,7 +502,7 @@ impl IonWriter for RawTextWriter { Blob => "null.blob", Clob => "null.clob", List => "null.list", - SExpression => "null.sexp", + SExp => "null.sexp", Struct => "null.struct", }; write!(output, "{null_text}")?; @@ -664,7 +664,7 @@ impl IonWriter for RawTextWriter { write!(self.output, "[")?; ContainerType::List } - SExpression => { + SExp => { write!(self.output, "(")?; ContainerType::SExpression } @@ -693,7 +693,7 @@ impl IonWriter for RawTextWriter { match self.parent_level().container_type { ContainerType::TopLevel => None, ContainerType::List => Some(IonType::List), - ContainerType::SExpression => Some(IonType::SExpression), + ContainerType::SExpression => Some(IonType::SExp), ContainerType::Struct => Some(IonType::Struct), } } @@ -1071,7 +1071,7 @@ mod tests { fn write_s_expression() { writer_test( |w| { - w.step_in(IonType::SExpression)?; + w.step_in(IonType::SExp)?; w.write_string("foo")?; w.write_i64(21)?; w.write_symbol("bar")?; diff --git a/src/text/text_formatter.rs b/src/text/text_formatter.rs index 9ca13ee2..e111ceee 100644 --- a/src/text/text_formatter.rs +++ b/src/text/text_formatter.rs @@ -305,7 +305,7 @@ impl<'a, W: std::fmt::Write> IonValueFormatter<'a, W> { Blob => "null.blob", Clob => "null.clob", List => "null.list", - SExpression => "null.sexp", + SExp => "null.sexp", Struct => "null.struct", }; write!(self.output, "{null_text}")?; diff --git a/src/text/text_value.rs b/src/text/text_value.rs index fc1bfe08..8b297741 100644 --- a/src/text/text_value.rs +++ b/src/text/text_value.rs @@ -77,7 +77,7 @@ impl TextValue { TextValue::Blob(_) => IonType::Blob, TextValue::Clob(_) => IonType::Clob, TextValue::ListStart => IonType::List, - TextValue::SExpressionStart => IonType::SExpression, + TextValue::SExpressionStart => IonType::SExp, TextValue::StructStart => IonType::Struct, } } diff --git a/src/types/mod.rs b/src/types/mod.rs index 1c6fcbf8..8d82aacf 100644 --- a/src/types/mod.rs +++ b/src/types/mod.rs @@ -27,7 +27,7 @@ pub enum IonType { Clob, Blob, List, - SExpression, + SExp, Struct, } @@ -48,7 +48,7 @@ impl fmt::Display for IonType { IonType::Clob => "clob", IonType::Blob => "blob", IonType::List => "list", - IonType::SExpression => "sexp", + IonType::SExp => "sexp", IonType::Struct => "struct", } ) @@ -58,7 +58,7 @@ impl fmt::Display for IonType { impl IonType { pub fn is_container(&self) -> bool { use IonType::*; - matches!(self, List | SExpression | Struct) + matches!(self, List | SExp | Struct) } } diff --git a/src/writer.rs b/src/writer.rs index 3c7b7856..138bff45 100644 --- a/src/writer.rs +++ b/src/writer.rs @@ -71,7 +71,7 @@ pub trait IonWriter { /// Starts a new Ion container with the specified type. /// The only valid IonType values are: /// * [IonType::List] - /// * [IonType::SExpression] + /// * [IonType::SExp] /// * [IonType::Struct] /// Passing any other IonType will result in an `Err`. fn step_in(&mut self, container_type: IonType) -> IonResult<()>; diff --git a/tests/good_test_vectors.rs b/tests/good_test_vectors.rs index 8ffc73b2..0e331727 100644 --- a/tests/good_test_vectors.rs +++ b/tests/good_test_vectors.rs @@ -134,7 +134,7 @@ fn read_all_values(reader: &mut Reader) -> IonResult<()> { continue; } match ion_type { - Struct | List | SExpression => { + Struct | List | SExp => { reader.step_in()?; read_all_values(reader)?; reader.step_out()?; From 17f145e26bcceb94e6ab4d22f0229fb6dff87566 Mon Sep 17 00:00:00 2001 From: Zack Slayton Date: Thu, 16 Mar 2023 08:12:35 -0400 Subject: [PATCH 10/14] Rename IonType::Boolean to IonType::Bool --- examples/read_all_values.rs | 2 +- src/binary/non_blocking/binary_buffer.rs | 2 +- src/binary/non_blocking/raw_binary_reader.rs | 4 ++-- src/binary/non_blocking/type_descriptor.rs | 2 +- src/binary/raw_binary_reader.rs | 14 +++++++------- src/binary/raw_binary_writer.rs | 8 ++++---- src/binary/type_code.rs | 2 +- src/element/builders.rs | 6 +++--- src/element/element_stream_reader.rs | 4 ++-- src/element/mod.rs | 2 +- src/element/native_writer.rs | 2 +- src/element/owned.rs | 10 +++++----- src/element/reader.rs | 6 +++--- src/ion_hash/representation.rs | 2 +- src/ion_hash/type_qualifier.rs | 2 +- src/text/non_blocking/raw_text_reader.rs | 8 ++++---- src/text/parent_container.rs | 2 +- src/text/parsers/null.rs | 4 ++-- src/text/parsers/top_level.rs | 4 ++-- src/text/raw_text_reader.rs | 8 ++++---- src/text/raw_text_writer.rs | 2 +- src/text/text_formatter.rs | 2 +- src/text/text_value.rs | 2 +- src/types/mod.rs | 4 ++-- tests/good_test_vectors.rs | 2 +- 25 files changed, 53 insertions(+), 53 deletions(-) diff --git a/examples/read_all_values.rs b/examples/read_all_values.rs index 71a21f3e..4bd211d5 100644 --- a/examples/read_all_values.rs +++ b/examples/read_all_values.rs @@ -79,7 +79,7 @@ fn read_all_values(reader: &mut R) -> IonResult { Timestamp => { let _timestamp = reader.read_timestamp()?; } - Boolean => { + Bool => { let _boolean = reader.read_bool()?; } Blob => { diff --git a/src/binary/non_blocking/binary_buffer.rs b/src/binary/non_blocking/binary_buffer.rs index ff301d83..ead8b2ee 100644 --- a/src/binary/non_blocking/binary_buffer.rs +++ b/src/binary/non_blocking/binary_buffer.rs @@ -399,7 +399,7 @@ impl> BinaryBuffer { let length_code = match header.ion_type { // Null (0x0F) and Boolean (0x10, 0x11) are the only types that don't have/use a `length` // field; the header contains the complete value. - Null | Boolean => 0, + Null | Bool => 0, // If a struct has length = 1, its fields are ordered and the actual length follows. // For the time being, this reader does not have any special handling for this case. // Use `0xE` (14) as the length code instead so the call to `read_length` below diff --git a/src/binary/non_blocking/raw_binary_reader.rs b/src/binary/non_blocking/raw_binary_reader.rs index 699871d1..6849b128 100644 --- a/src/binary/non_blocking/raw_binary_reader.rs +++ b/src/binary/non_blocking/raw_binary_reader.rs @@ -667,7 +667,7 @@ impl> IonReader for RawBinaryBufferReader { } fn read_bool(&mut self) -> IonResult { - let (encoded_value, _) = self.value_and_bytes(IonType::Boolean)?; + let (encoded_value, _) = self.value_and_bytes(IonType::Bool)?; let representation = encoded_value.header.length_code; match representation { @@ -1763,7 +1763,7 @@ mod tests { reader.step_in()?; expect_value(reader.next(), IonType::Struct); reader.step_in()?; - expect_value(reader.next(), IonType::Boolean); + expect_value(reader.next(), IonType::Bool); assert_eq!(reader.field_name()?, RawSymbolToken::SymbolId(4)); let item = reader.next()?; assert_eq!(item, RawStreamItem::Nothing); diff --git a/src/binary/non_blocking/type_descriptor.rs b/src/binary/non_blocking/type_descriptor.rs index 6bf9650f..adfcbf50 100644 --- a/src/binary/non_blocking/type_descriptor.rs +++ b/src/binary/non_blocking/type_descriptor.rs @@ -64,7 +64,7 @@ impl TypeDescriptor { let ion_type = match ion_type_code { NullOrNop if length_code == length_codes::NULL => Some(IonType::Null), NullOrNop => None, - Boolean => Some(IonType::Boolean), + Boolean => Some(IonType::Bool), PositiveInteger => Some(IonType::Integer), NegativeInteger => Some(IonType::Integer), Float => Some(IonType::Float), diff --git a/src/binary/raw_binary_reader.rs b/src/binary/raw_binary_reader.rs index 130aa0ae..e41ba7eb 100644 --- a/src/binary/raw_binary_reader.rs +++ b/src/binary/raw_binary_reader.rs @@ -447,7 +447,7 @@ impl IonReader for RawBinaryReader { } fn read_bool(&mut self) -> IonResult { - read_safety_checks!(self, IonType::Boolean); + read_safety_checks!(self, IonType::Bool); // No reading from the stream occurs -- the header contains all of the information we need. let representation = self.cursor.value.header.length_code; @@ -1258,7 +1258,7 @@ mod tests { #[test] fn test_read_bool_false() -> IonResult<()> { let mut cursor = ion_cursor_for(&[0x10]); - assert_eq!(cursor.next()?, Value(IonType::Boolean)); + assert_eq!(cursor.next()?, Value(IonType::Bool)); assert!(!(cursor.read_bool()?)); Ok(()) } @@ -1266,7 +1266,7 @@ mod tests { #[test] fn test_read_bool_true() -> IonResult<()> { let mut cursor = ion_cursor_for(&[0x11]); - assert_eq!(cursor.next()?, Value(IonType::Boolean)); + assert_eq!(cursor.next()?, Value(IonType::Bool)); assert!(cursor.read_bool()?); Ok(()) } @@ -1678,7 +1678,7 @@ mod tests { cursor.step_out()?; // Step out of struct // Second top-level value - assert_eq!(RawStreamItem::Value(IonType::Boolean), cursor.next()?); + assert_eq!(RawStreamItem::Value(IonType::Bool), cursor.next()?); assert_eq!(cursor.raw_bytes(), Some(&ion_data[12..16])); assert_eq!(cursor.raw_field_id_bytes(), None); assert_eq!(cursor.raw_annotations_bytes(), Some(&ion_data[12..=14])); @@ -1758,7 +1758,7 @@ mod tests { cursor.step_out()?; // false - assert_eq!(RawStreamItem::Value(IonType::Boolean), cursor.next()?); + assert_eq!(RawStreamItem::Value(IonType::Bool), cursor.next()?); assert_eq!(cursor.raw_bytes(), Some(&ion_data[37..=37])); assert_eq!(cursor.raw_field_id_bytes(), None); assert_eq!(cursor.raw_annotations_bytes(), None); @@ -1784,7 +1784,7 @@ mod tests { 0x00, // NOP code, 1 byte NOP. Also NOP at EOF :) ]); - assert_eq!(cursor.next()?, Value(IonType::Boolean)); + assert_eq!(cursor.next()?, Value(IonType::Bool)); assert_eq!(cursor.next()?, Nothing); Ok(()) @@ -1800,7 +1800,7 @@ mod tests { 0x11, // boolean true ]); - assert_eq!(cursor.next()?, Value(IonType::Boolean)); + assert_eq!(cursor.next()?, Value(IonType::Bool)); assert_eq!(cursor.next()?, Nothing); Ok(()) diff --git a/src/binary/raw_binary_writer.rs b/src/binary/raw_binary_writer.rs index 1813ae84..d7d5f6ff 100644 --- a/src/binary/raw_binary_writer.rs +++ b/src/binary/raw_binary_writer.rs @@ -547,7 +547,7 @@ impl IonWriter for RawBinaryWriter { self.write_scalar(|enc_buffer| { let byte: u8 = match ion_type { IonType::Null => 0x0F, - IonType::Boolean => 0x1F, + IonType::Bool => 0x1F, IonType::Integer => 0x2F, IonType::Float => 0x4F, IonType::Decimal => 0x5F, @@ -970,7 +970,7 @@ mod writer_tests { fn binary_writer_nulls() -> IonResult<()> { let ion_types = &[ IonType::Null, - IonType::Boolean, + IonType::Bool, IonType::Integer, IonType::Float, IonType::Decimal, @@ -1004,7 +1004,7 @@ mod writer_tests { fn binary_writer_bools() -> IonResult<()> { binary_writer_scalar_test( &[true, false], - IonType::Boolean, + IonType::Bool, |writer, v| writer.write_bool(*v), |reader| reader.read_bool(), ) @@ -1132,7 +1132,7 @@ mod writer_tests { } fn expect_bool(reader: &mut TestReader, value: bool) { - expect_scalar(reader, IonType::Boolean, |r| r.read_bool(), value); + expect_scalar(reader, IonType::Bool, |r| r.read_bool(), value); } fn expect_integer(reader: &mut TestReader, value: i64) { diff --git a/src/binary/type_code.rs b/src/binary/type_code.rs index ad7ebf89..08c571d3 100644 --- a/src/binary/type_code.rs +++ b/src/binary/type_code.rs @@ -42,7 +42,7 @@ impl TryFrom for IonType { use IonTypeCode::*; let ion_type = match ion_type_code { NullOrNop => IonType::Null, - Boolean => IonType::Boolean, + Boolean => IonType::Bool, PositiveInteger | NegativeInteger => IonType::Integer, Float => IonType::Float, Decimal => IonType::Decimal, diff --git a/src/element/builders.rs b/src/element/builders.rs index 4e6792c2..8f2f7777 100644 --- a/src/element/builders.rs +++ b/src/element/builders.rs @@ -294,7 +294,7 @@ impl From for Element { #[macro_export] macro_rules! ion_list { ($($element:expr),*) => {{ - use $crate::value::owned::List; + use $crate::element::owned::List; List::builder()$(.push($element))*.build() }}; } @@ -340,7 +340,7 @@ macro_rules! ion_list { #[macro_export] macro_rules! ion_sexp { ($($element:expr)*) => {{ - use $crate::value::owned::SExp; + use $crate::element::owned::SExp; SExp::builder()$(.push($element))*.build() }}; } @@ -376,7 +376,7 @@ macro_rules! ion_sexp { #[macro_export] macro_rules! ion_struct { ($($field_name:tt : $element:expr),*) => {{ - use $crate::value::owned::Struct; + use $crate::element::owned::Struct; Struct::builder()$(.with_field($field_name, $element))*.build() }}; } diff --git a/src/element/element_stream_reader.rs b/src/element/element_stream_reader.rs index 591d4591..482380e7 100644 --- a/src/element/element_stream_reader.rs +++ b/src/element/element_stream_reader.rs @@ -454,8 +454,8 @@ mod reader_tests { next_type(reader, IonType::Integer, false); next_type(reader, IonType::SExp, false); reader.step_in()?; - next_type(reader, IonType::Boolean, false); - next_type(reader, IonType::Boolean, false); + next_type(reader, IonType::Bool, false); + next_type(reader, IonType::Bool, false); // The reader is now at the second 'true' in the s-expression nested in 'bar'/'b' reader.step_out()?; reader.step_out()?; diff --git a/src/element/mod.rs b/src/element/mod.rs index 38f1e1f3..6854704f 100644 --- a/src/element/mod.rs +++ b/src/element/mod.rs @@ -305,7 +305,7 @@ mod tests { fn bool_case() -> Case { Case { elem: true.into(), - ion_type: IonType::Boolean, + ion_type: IonType::Bool, ops: vec![AsBool], op_assert: Box::new(|e: &Element| { let expected = Element::from(true); diff --git a/src/element/native_writer.rs b/src/element/native_writer.rs index 785e6ee3..ae759ea0 100644 --- a/src/element/native_writer.rs +++ b/src/element/native_writer.rs @@ -49,7 +49,7 @@ impl NativeElementWriter { match element.ion_type() { IonType::Null => unreachable!("element has IonType::Null but is_null() was false"), - IonType::Boolean => self.writer.write_bool(element.as_boolean().unwrap()), + IonType::Bool => self.writer.write_bool(element.as_boolean().unwrap()), IonType::Integer => self.writer.write_integer(element.as_integer().unwrap()), IonType::Float => self.writer.write_f64(element.as_float().unwrap()), IonType::Decimal => self.writer.write_decimal(element.as_decimal().unwrap()), diff --git a/src/element/owned.rs b/src/element/owned.rs index 349fa3ff..da5a8738 100644 --- a/src/element/owned.rs +++ b/src/element/owned.rs @@ -409,7 +409,7 @@ pub enum Value { Timestamp(Timestamp), String(String), Symbol(Symbol), - Boolean(bool), + Bool(bool), Blob(Vec), Clob(Vec), SExp(SExp), @@ -440,7 +440,7 @@ impl Display for Element { match &self.value { Value::Null(ion_type) => ivf.format_null(*ion_type), - Value::Boolean(bool) => ivf.format_bool(*bool), + Value::Bool(bool) => ivf.format_bool(*bool), Value::Integer(integer) => ivf.format_integer(integer), Value::Float(float) => ivf.format_float(*float), Value::Decimal(decimal) => ivf.format_decimal(decimal), @@ -530,7 +530,7 @@ impl From for Value { impl From for Value { fn from(bool_val: bool) -> Self { - Value::Boolean(bool_val) + Value::Bool(bool_val) } } @@ -612,7 +612,7 @@ impl Element { Timestamp(_) => IonType::Timestamp, String(_) => IonType::String, Symbol(_) => IonType::Symbol, - Boolean(_) => IonType::Boolean, + Bool(_) => IonType::Bool, Blob(_) => IonType::Blob, Clob(_) => IonType::Clob, SExp(_) => IonType::SExp, @@ -695,7 +695,7 @@ impl Element { pub fn as_boolean(&self) -> Option { match &self.value { - Value::Boolean(b) => Some(*b), + Value::Bool(b) => Some(*b), _ => None, } } diff --git a/src/element/reader.rs b/src/element/reader.rs index 94657731..7f077645 100644 --- a/src/element/reader.rs +++ b/src/element/reader.rs @@ -141,7 +141,7 @@ impl<'a, R: IonReader> ElementLoader<'a, R> use crate::IonType::*; match ion_type { Null => unreachable!("non-null value had IonType::Null"), - Boolean => Value::Boolean(self.reader.read_bool()?), + Bool => Value::Bool(self.reader.read_bool()?), Integer => Value::Integer(self.reader.read_integer()?), Float => Value::Float(self.reader.read_f64()?), Decimal => Value::Decimal(self.reader.read_decimal()?), @@ -225,7 +225,7 @@ mod reader_tests { "#, vec![ Null(IonType::Null), - Null(IonType::Boolean), + Null(IonType::Bool), Null(IonType::Integer), Null(IonType::Float), Null(IonType::Decimal), @@ -235,7 +235,7 @@ mod reader_tests { Null(IonType::Clob), Null(IonType::Blob), Null(IonType::List), - Null(IonType::SExpression), + Null(IonType::SExp), Null(IonType::Struct), ].into_iter().map(|v| v.into()).collect(), )] diff --git a/src/ion_hash/representation.rs b/src/ion_hash/representation.rs index 6134856f..b416a5af 100644 --- a/src/ion_hash/representation.rs +++ b/src/ion_hash/representation.rs @@ -18,7 +18,7 @@ use digest::{FixedOutput, Output, Reset, Update}; pub(crate) trait RepresentationEncoder { fn update_with_representation(&mut self, elem: &Element) -> IonResult<()> { match elem.ion_type() { - IonType::Null | IonType::Boolean => {} // these types have no representation + IonType::Null | IonType::Bool => {} // these types have no representation IonType::Integer => self.write_repr_integer(elem.as_integer())?, IonType::Float => self.write_repr_float(elem.as_float())?, IonType::Decimal => self.write_repr_decimal(elem.as_decimal())?, diff --git a/src/ion_hash/type_qualifier.rs b/src/ion_hash/type_qualifier.rs index 2abf8ff6..b0748534 100644 --- a/src/ion_hash/type_qualifier.rs +++ b/src/ion_hash/type_qualifier.rs @@ -38,7 +38,7 @@ impl TypeQualifier { pub(crate) fn from_element(elem: &Element) -> TypeQualifier { match elem.ion_type() { IonType::Null => type_qualifier_null(), - IonType::Boolean => type_qualifier_boolean(elem.as_boolean()), + IonType::Bool => type_qualifier_boolean(elem.as_boolean()), IonType::Integer => type_qualifier_integer(elem.as_integer()), IonType::Float => type_qualifier_float(elem.as_float()), IonType::Decimal => type_qualifier_decimal(elem.as_decimal()), diff --git a/src/text/non_blocking/raw_text_reader.rs b/src/text/non_blocking/raw_text_reader.rs index 4ef282d2..6495c06b 100644 --- a/src/text/non_blocking/raw_text_reader.rs +++ b/src/text/non_blocking/raw_text_reader.rs @@ -1117,8 +1117,8 @@ mod reader_tests { next_type(reader, IonType::Integer, false); next_type(reader, IonType::SExp, false); reader.step_in()?; - next_type(reader, IonType::Boolean, false); - next_type(reader, IonType::Boolean, false); + next_type(reader, IonType::Bool, false); + next_type(reader, IonType::Bool, false); // The reader is now at the second 'true' in the s-expression nested in 'bar'/'b' reader.step_out()?; reader.step_out()?; @@ -1208,7 +1208,7 @@ mod reader_tests { reader.stream_complete(); next_type(reader, IonType::Null, true); - next_type(reader, IonType::Boolean, false); + next_type(reader, IonType::Bool, false); assert!(reader.read_bool()?); next_type(reader, IonType::Integer, false); @@ -1328,7 +1328,7 @@ mod reader_tests { next_type(reader, IonType::Null, true); annotations_eq(reader, ["mercury"]); - next_type(reader, IonType::Boolean, false); + next_type(reader, IonType::Bool, false); assert!(reader.read_bool()?); annotations_eq(reader, ["venus", "earth"]); diff --git a/src/text/parent_container.rs b/src/text/parent_container.rs index e2c650e0..d54d47c5 100644 --- a/src/text/parent_container.rs +++ b/src/text/parent_container.rs @@ -47,7 +47,7 @@ mod parent_container_tests { #[rstest] #[case::list(IonType::List)] - #[case::list(IonType::SExpression)] + #[case::list(IonType::SExp)] #[case::list(IonType::Struct)] #[should_panic] #[case::list(IonType::Integer)] diff --git a/src/text/parsers/null.rs b/src/text/parsers/null.rs index ea5cea54..a57fc03e 100644 --- a/src/text/parsers/null.rs +++ b/src/text/parsers/null.rs @@ -33,7 +33,7 @@ fn ion_type_from_text(text: &str) -> Option { use IonType::*; let ion_type = match text { "null" => Null, - "bool" => Boolean, + "bool" => Bool, "int" => Integer, "float" => Float, "decimal" => Decimal, @@ -70,7 +70,7 @@ mod null_parsing_tests { use IonType::*; parse_equals("null ", Null); parse_equals("null.null ", Null); - parse_equals("null.bool ", Boolean); + parse_equals("null.bool ", Bool); parse_equals("null.int ", Integer); parse_equals("null.float ", Float); parse_equals("null.decimal ", Decimal); diff --git a/src/text/parsers/top_level.rs b/src/text/parsers/top_level.rs index 565163d7..d0066457 100644 --- a/src/text/parsers/top_level.rs +++ b/src/text/parsers/top_level.rs @@ -110,8 +110,8 @@ mod parse_top_level_values_tests { expect_type("null ", IonType::Null); expect_type("null.timestamp ", IonType::Timestamp); expect_type("null.list ", IonType::List); - expect_type("true ", IonType::Boolean); - expect_type("false ", IonType::Boolean); + expect_type("true ", IonType::Bool); + expect_type("false ", IonType::Bool); expect_type("5 ", IonType::Integer); expect_type("-5 ", IonType::Integer); expect_type("5.0 ", IonType::Decimal); diff --git a/src/text/raw_text_reader.rs b/src/text/raw_text_reader.rs index 7d3aaeaa..a9a354a0 100644 --- a/src/text/raw_text_reader.rs +++ b/src/text/raw_text_reader.rs @@ -306,8 +306,8 @@ mod reader_tests { next_type(reader, IonType::Integer, false); next_type(reader, IonType::SExp, false); reader.step_in()?; - next_type(reader, IonType::Boolean, false); - next_type(reader, IonType::Boolean, false); + next_type(reader, IonType::Bool, false); + next_type(reader, IonType::Bool, false); // The reader is now at the second 'true' in the s-expression nested in 'bar'/'b' reader.step_out()?; reader.step_out()?; @@ -369,7 +369,7 @@ mod reader_tests { let reader = &mut RawTextReader::new(ion_data)?; next_type(reader, IonType::Null, true); - next_type(reader, IonType::Boolean, false); + next_type(reader, IonType::Bool, false); assert!(reader.read_bool()?); next_type(reader, IonType::Integer, false); @@ -488,7 +488,7 @@ mod reader_tests { next_type(reader, IonType::Null, true); annotations_eq(reader, ["mercury"]); - next_type(reader, IonType::Boolean, false); + next_type(reader, IonType::Bool, false); assert!(reader.read_bool()?); annotations_eq(reader, ["venus", "earth"]); diff --git a/src/text/raw_text_writer.rs b/src/text/raw_text_writer.rs index 979e4b76..ec4e1f9d 100644 --- a/src/text/raw_text_writer.rs +++ b/src/text/raw_text_writer.rs @@ -492,7 +492,7 @@ impl IonWriter for RawTextWriter { self.write_scalar(|output| { let null_text = match ion_type { Null => "null", - Boolean => "null.bool", + Bool => "null.bool", Integer => "null.int", Float => "null.float", Decimal => "null.decimal", diff --git a/src/text/text_formatter.rs b/src/text/text_formatter.rs index e111ceee..72d70743 100644 --- a/src/text/text_formatter.rs +++ b/src/text/text_formatter.rs @@ -295,7 +295,7 @@ impl<'a, W: std::fmt::Write> IonValueFormatter<'a, W> { use IonType::*; let null_text = match ion_type { Null => "null", - Boolean => "null.bool", + Bool => "null.bool", Integer => "null.int", Float => "null.float", Decimal => "null.decimal", diff --git a/src/text/text_value.rs b/src/text/text_value.rs index 8b297741..c3f31d10 100644 --- a/src/text/text_value.rs +++ b/src/text/text_value.rs @@ -67,7 +67,7 @@ impl TextValue { pub fn ion_type(&self) -> IonType { match self { TextValue::Null(ion_type) => *ion_type, - TextValue::Boolean(_) => IonType::Boolean, + TextValue::Boolean(_) => IonType::Bool, TextValue::Integer(_) => IonType::Integer, TextValue::Float(_) => IonType::Float, TextValue::Decimal(_) => IonType::Decimal, diff --git a/src/types/mod.rs b/src/types/mod.rs index 8d82aacf..e1ebe9d3 100644 --- a/src/types/mod.rs +++ b/src/types/mod.rs @@ -17,7 +17,7 @@ use std::fmt; #[derive(Debug, PartialEq, Eq, PartialOrd, Copy, Clone)] pub enum IonType { Null, - Boolean, + Bool, Integer, Float, Decimal, @@ -38,7 +38,7 @@ impl fmt::Display for IonType { "{}", match self { IonType::Null => "null", - IonType::Boolean => "boolean", + IonType::Bool => "bool", IonType::Integer => "integer", IonType::Float => "float", IonType::Decimal => "decimal", diff --git a/tests/good_test_vectors.rs b/tests/good_test_vectors.rs index 0e331727..aacd3cba 100644 --- a/tests/good_test_vectors.rs +++ b/tests/good_test_vectors.rs @@ -158,7 +158,7 @@ fn read_all_values(reader: &mut Reader) -> IonResult<()> { Timestamp => { let _timestamp = reader.read_timestamp()?; } - Boolean => { + Bool => { let _boolean = reader.read_bool()?; } Blob => { From 52c1f2b249c60c4f41132bb195f5776efc02c04f Mon Sep 17 00:00:00 2001 From: Zack Slayton Date: Thu, 16 Mar 2023 08:34:44 -0400 Subject: [PATCH 11/14] Adds Display impl for List,SExp,Struct,Value --- src/element/owned.rs | 105 +++++++++++++++++++++++++++++++++++-------- 1 file changed, 86 insertions(+), 19 deletions(-) diff --git a/src/element/owned.rs b/src/element/owned.rs index da5a8738..acf8d3bd 100644 --- a/src/element/owned.rs +++ b/src/element/owned.rs @@ -107,6 +107,14 @@ impl List { } } +impl Display for List { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + let mut ivf = IonValueFormatter { output: f }; + ivf.format_list(self).map_err(|_| std::fmt::Error)?; + Ok(()) + } +} + impl IonSequence for List { fn iter(&self) -> ElementsIterator<'_> { ElementsIterator::new(&self.children) @@ -159,6 +167,14 @@ impl SExp { } } +impl Display for SExp { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + let mut ivf = IonValueFormatter { output: f }; + ivf.format_sexp(self).map_err(|_| std::fmt::Error)?; + Ok(()) + } +} + impl IonSequence for SExp { fn iter(&self) -> ElementsIterator<'_> { ElementsIterator::new(&self.children) @@ -250,6 +266,14 @@ pub struct Struct { fields: Fields, } +impl Display for Struct { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + let mut ivf = IonValueFormatter { output: f }; + ivf.format_struct(self).map_err(|_| std::fmt::Error)?; + Ok(()) + } +} + impl Struct { pub fn builder() -> StructBuilder { StructBuilder::new() @@ -417,6 +441,30 @@ pub enum Value { Struct(Struct), } +impl Display for Value { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + let mut ivf = IonValueFormatter { output: f }; + match &self { + Value::Null(ion_type) => ivf.format_null(*ion_type), + Value::Bool(bool) => ivf.format_bool(*bool), + Value::Integer(integer) => ivf.format_integer(integer), + Value::Float(float) => ivf.format_float(*float), + Value::Decimal(decimal) => ivf.format_decimal(decimal), + Value::Timestamp(timestamp) => ivf.format_timestamp(timestamp), + Value::Symbol(symbol) => ivf.format_symbol(symbol), + Value::String(string) => ivf.format_string(string), + Value::Clob(clob) => ivf.format_clob(clob), + Value::Blob(blob) => ivf.format_blob(blob), + Value::Struct(struct_) => ivf.format_struct(struct_), + Value::SExp(sexp) => ivf.format_sexp(sexp), + Value::List(list) => ivf.format_list(list), + } + .map_err(|_| std::fmt::Error)?; + + Ok(()) + } +} + /// An `(annotations, value)` pair representing an Ion value. #[derive(Debug, Clone)] pub struct Element { @@ -434,28 +482,11 @@ impl Display for Element { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> { let mut ivf = IonValueFormatter { output: f }; - // display for annotations of this owned_element + // display for annotations of this element ivf.format_annotations(&self.annotations) .map_err(|_| std::fmt::Error)?; - match &self.value { - Value::Null(ion_type) => ivf.format_null(*ion_type), - Value::Bool(bool) => ivf.format_bool(*bool), - Value::Integer(integer) => ivf.format_integer(integer), - Value::Float(float) => ivf.format_float(*float), - Value::Decimal(decimal) => ivf.format_decimal(decimal), - Value::Timestamp(timestamp) => ivf.format_timestamp(timestamp), - Value::Symbol(symbol) => ivf.format_symbol(symbol), - Value::String(string) => ivf.format_string(string), - Value::Clob(clob) => ivf.format_clob(clob), - Value::Blob(blob) => ivf.format_blob(blob), - Value::Struct(struct_) => ivf.format_struct(struct_), - Value::SExp(sexp) => ivf.format_sexp(sexp), - Value::List(list) => ivf.format_list(list), - } - .map_err(|_| std::fmt::Error)?; - - Ok(()) + self.value.fmt(f) } } @@ -867,4 +898,40 @@ mod value_tests { } } } + + #[test] + fn list_display_roundtrip() { + let list = ion_list![1, 2, 3, true, false]; + + // Use the Display impl to serialize the list to text + let text_list = format!("{list}"); + // Parse the result and make sure it represents the same data + let expected_element: Element = list.into(); + let actual_element = Element::read_one(text_list).unwrap(); + assert!(expected_element.ion_eq(&actual_element)); + } + + #[test] + fn sexp_display_roundtrip() { + let sexp = ion_sexp! (1 2 3 true false); + + // Use the Display impl to serialize the sexp to text + let text_sexp = format!("{sexp}"); + // Parse the result and make sure it represents the same data + let expected_element: Element = sexp.into(); + let actual_element = Element::read_one(text_sexp).unwrap(); + assert!(expected_element.ion_eq(&actual_element)); + } + + #[test] + fn struct_display_roundtrip() { + let struct_ = ion_struct! {"foo": 1, "bar": 2, "baz": ion_list! [true, false]}; + + // Use the Display impl to serialize the struct to text + let text_struct = format!("{struct_}"); + // Parse the result and make sure it represents the same data + let expected_element: Element = struct_.into(); + let actual_element = Element::read_one(text_struct).unwrap(); + assert!(expected_element.ion_eq(&actual_element)); + } } From 95e8b4f7f9fabae87c21c943cfc3dc82f0aff606 Mon Sep 17 00:00:00 2001 From: Zack Slayton Date: Thu, 16 Mar 2023 08:44:21 -0400 Subject: [PATCH 12/14] IonType Display uses official type names --- src/types/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/types/mod.rs b/src/types/mod.rs index e1ebe9d3..c7e75133 100644 --- a/src/types/mod.rs +++ b/src/types/mod.rs @@ -39,7 +39,7 @@ impl fmt::Display for IonType { match self { IonType::Null => "null", IonType::Bool => "bool", - IonType::Integer => "integer", + IonType::Integer => "int", IonType::Float => "float", IonType::Decimal => "decimal", IonType::Timestamp => "timestamp", From 85f7cfb40f335537dd452dc57c73865d528eaa1b Mon Sep 17 00:00:00 2001 From: Zack Slayton Date: Thu, 16 Mar 2023 09:09:19 -0400 Subject: [PATCH 13/14] Rename Integer to Int, UInteger to UInt --- examples/read_all_values.rs | 2 +- src/binary/binary_writer.rs | 6 +- src/binary/decimal.rs | 8 +- src/binary/int.rs | 36 +- src/binary/non_blocking/binary_buffer.rs | 36 +- src/binary/non_blocking/raw_binary_reader.rs | 42 +-- src/binary/non_blocking/type_descriptor.rs | 4 +- src/binary/raw_binary_reader.rs | 58 ++-- src/binary/raw_binary_writer.rs | 32 +- src/binary/type_code.rs | 2 +- src/binary/uint.rs | 34 +- src/element/element_stream_reader.rs | 38 +-- src/element/mod.rs | 16 +- src/element/native_writer.rs | 4 +- src/element/owned.rs | 28 +- src/element/reader.rs | 16 +- src/ion_hash/representation.rs | 12 +- src/ion_hash/type_qualifier.rs | 14 +- src/lib.rs | 2 +- src/raw_reader.rs | 6 +- src/reader.rs | 10 +- src/stream_reader.rs | 6 +- src/system_reader.rs | 4 +- src/text/non_blocking/raw_text_reader.rs | 76 ++--- src/text/parent_container.rs | 2 +- src/text/parsers/boolean.rs | 8 +- src/text/parsers/containers.rs | 30 +- src/text/parsers/decimal.rs | 8 +- src/text/parsers/integer.rs | 30 +- src/text/parsers/null.rs | 4 +- src/text/parsers/top_level.rs | 10 +- src/text/raw_text_reader.rs | 42 +-- src/text/raw_text_writer.rs | 6 +- src/text/text_formatter.rs | 19 +- src/text/text_value.rs | 14 +- src/text/text_writer.rs | 4 +- src/types/coefficient.rs | 34 +- src/types/decimal.rs | 16 +- src/types/integer.rs | 330 +++++++++---------- src/types/mod.rs | 4 +- src/types/timestamp.rs | 6 +- src/writer.rs | 4 +- tests/good_test_vectors.rs | 2 +- tests/ion_hash_tests.rs | 2 +- 44 files changed, 519 insertions(+), 548 deletions(-) diff --git a/examples/read_all_values.rs b/examples/read_all_values.rs index 4bd211d5..7a0daebc 100644 --- a/examples/read_all_values.rs +++ b/examples/read_all_values.rs @@ -67,7 +67,7 @@ fn read_all_values(reader: &mut R) -> IonResult { Symbol => { let _symbol_id = reader.read_symbol()?; } - Integer => { + Int => { let _int = reader.read_i64()?; } Float => { diff --git a/src/binary/binary_writer.rs b/src/binary/binary_writer.rs index 6c902d14..cdb57457 100644 --- a/src/binary/binary_writer.rs +++ b/src/binary/binary_writer.rs @@ -6,7 +6,7 @@ use crate::types::decimal::Decimal; use crate::types::timestamp::Timestamp; use crate::types::SymbolId; use crate::writer::IonWriter; -use crate::{Integer, IonType, SymbolTable}; +use crate::{Int, IonType, SymbolTable}; use delegate::delegate; use std::io::Write; @@ -180,7 +180,7 @@ impl IonWriter for BinaryWriter { fn write_null(&mut self, ion_type: IonType) -> IonResult<()>; fn write_bool(&mut self, value: bool) -> IonResult<()>; fn write_i64(&mut self, value: i64) -> IonResult<()>; - fn write_integer(&mut self, value: &Integer) -> IonResult<()>; + fn write_int(&mut self, value: &Int) -> IonResult<()>; fn write_f32(&mut self, value: f32) -> IonResult<()>; fn write_f64(&mut self, value: f64) -> IonResult<()>; fn write_decimal(&mut self, value: &Decimal) -> IonResult<()>; @@ -233,7 +233,7 @@ mod tests { binary_writer.flush()?; let mut reader = ReaderBuilder::new().build(buffer)?; - assert_eq!(Value(IonType::Integer), reader.next()?); + assert_eq!(Value(IonType::Int), reader.next()?); let mut annotations = reader.annotations(); assert_eq!("foo", annotations.next().unwrap()?); assert_eq!("bar", annotations.next().unwrap()?); diff --git a/src/binary/decimal.rs b/src/binary/decimal.rs index ddc02365..d2824002 100644 --- a/src/binary/decimal.rs +++ b/src/binary/decimal.rs @@ -14,7 +14,7 @@ use crate::{ types::{ coefficient::{Coefficient, Sign}, decimal::Decimal, - integer::UInteger, + integer::UInt, }, IonError, }; @@ -23,7 +23,7 @@ const DECIMAL_BUFFER_SIZE: usize = 32; const DECIMAL_POSITIVE_ZERO: Decimal = Decimal { coefficient: Coefficient { sign: Sign::Positive, - magnitude: UInteger::U64(0), + magnitude: UInt::U64(0), }, exponent: 0, }; @@ -75,8 +75,8 @@ where } else { // Otherwise, allocate a Vec with the necessary representation. let mut coefficient_bytes = match decimal.coefficient.magnitude() { - UInteger::U64(unsigned) => unsigned.to_be_bytes().into(), - UInteger::BigUInt(big) => big.to_bytes_be(), + UInt::U64(unsigned) => unsigned.to_be_bytes().into(), + UInt::BigUInt(big) => big.to_bytes_be(), }; let first_byte: &mut u8 = &mut coefficient_bytes[0]; diff --git a/src/binary/int.rs b/src/binary/int.rs index bc461af9..6d40ef7c 100644 --- a/src/binary/int.rs +++ b/src/binary/int.rs @@ -4,7 +4,7 @@ use crate::data_source::IonDataSource; use crate::result::{decoding_error, IonResult}; use crate::types::coefficient; use crate::types::coefficient::Coefficient; -use crate::Integer; +use crate::Int; use num_bigint::{BigInt, Sign}; use num_traits::Zero; use std::io::Write; @@ -23,14 +23,14 @@ const MAX_INT_SIZE_IN_BYTES: usize = 2048; #[derive(Debug)] pub struct DecodedInt { size_in_bytes: usize, - value: Integer, + value: Int, // [Integer] is not capable of natively representing negative zero. We track the sign // of the value separately so we can distinguish between 0 and -0. is_negative: bool, } impl DecodedInt { - pub(crate) fn new(value: Integer, is_negative: bool, size_in_bytes: usize) -> Self { + pub(crate) fn new(value: Int, is_negative: bool, size_in_bytes: usize) -> Self { DecodedInt { size_in_bytes, value, @@ -43,7 +43,7 @@ impl DecodedInt { if length == 0 { return Ok(DecodedInt { size_in_bytes: 0, - value: Integer::I64(0), + value: Int::I64(0), is_negative: false, }); } else if length > MAX_INT_SIZE_IN_BYTES { @@ -90,7 +90,7 @@ impl DecodedInt { magnitude <<= 8; magnitude |= byte; } - Integer::I64(sign * magnitude) + Int::I64(sign * magnitude) } else { // This Int is too big for an i64, we'll need to use a BigInt let sign: num_bigint::Sign = if buffer[0] & 0b1000_0000 == 0 { @@ -104,7 +104,7 @@ impl DecodedInt { // in the buffer to zero. buffer[0] &= 0b0111_1111; let value = BigInt::from_bytes_be(sign, buffer); - Integer::BigInt(value) + Int::BigInt(value) }; Ok(DecodedInt { @@ -154,7 +154,7 @@ impl DecodedInt { /// Returns the value of the signed integer. #[inline(always)] - pub fn value(&self) -> &Integer { + pub fn value(&self) -> &Int { &self.value } @@ -170,13 +170,13 @@ impl DecodedInt { pub fn zero() -> Self { DecodedInt { size_in_bytes: 0, - value: Integer::I64(0), + value: Int::I64(0), is_negative: false, } } } -impl From for Integer { +impl From for Int { /// Note that if the DecodedInt represents -0, converting it to an Integer will result in a 0. /// If negative zero is significant to your use case, check it using [DecodedInt::is_negative_zero] /// before converting it to an Integer. @@ -206,7 +206,7 @@ impl From for Coefficient { mod tests { use super::*; use crate::result::IonResult; - use crate::Integer; + use crate::Int; use std::io; use std::io::Cursor; @@ -217,7 +217,7 @@ mod tests { let data = &[0b0011_1100, 0b1000_0111, 0b1000_0001]; let int = DecodedInt::read(&mut Cursor::new(data), data.len()).expect(READ_ERROR_MESSAGE); assert_eq!(int.size_in_bytes(), 3); - assert_eq!(int.value(), &Integer::I64(3_966_849)); + assert_eq!(int.value(), &Int::I64(3_966_849)); } #[test] @@ -225,7 +225,7 @@ mod tests { let data = &[0b1011_1100, 0b1000_0111, 0b1000_0001]; let int = DecodedInt::read(&mut Cursor::new(data), data.len()).expect(READ_ERROR_MESSAGE); assert_eq!(int.size_in_bytes(), 3); - assert_eq!(int.value(), &Integer::I64(-3_966_849)); + assert_eq!(int.value(), &Int::I64(-3_966_849)); } #[test] @@ -233,7 +233,7 @@ mod tests { let data = &[0b1000_0000]; // Negative zero let int = DecodedInt::read(&mut Cursor::new(data), data.len()).expect(READ_ERROR_MESSAGE); assert_eq!(int.size_in_bytes(), 1); - assert_eq!(int.value(), &Integer::I64(0)); + assert_eq!(int.value(), &Int::I64(0)); assert!(int.is_negative_zero()); } @@ -242,7 +242,7 @@ mod tests { let data = &[0b0000_0000]; // Positive zero let int = DecodedInt::read(&mut Cursor::new(data), data.len()).expect(READ_ERROR_MESSAGE); assert_eq!(int.size_in_bytes(), 1); - assert_eq!(int.value(), &Integer::I64(0)); + assert_eq!(int.value(), &Int::I64(0)); assert!(!int.is_negative_zero()); } @@ -251,7 +251,7 @@ mod tests { let data = &[0b0111_1111, 0b1111_1111]; let int = DecodedInt::read(&mut Cursor::new(data), data.len()).expect(READ_ERROR_MESSAGE); assert_eq!(int.size_in_bytes(), 2); - assert_eq!(int.value(), &Integer::I64(32_767)); + assert_eq!(int.value(), &Int::I64(32_767)); } #[test] @@ -259,7 +259,7 @@ mod tests { let data = &[0b1111_1111, 0b1111_1111]; let int = DecodedInt::read(&mut Cursor::new(data), data.len()).expect(READ_ERROR_MESSAGE); assert_eq!(int.size_in_bytes(), 2); - assert_eq!(int.value(), &Integer::I64(-32_767)); + assert_eq!(int.value(), &Int::I64(-32_767)); } #[test] @@ -267,7 +267,7 @@ mod tests { let data = &[]; let int = DecodedInt::read(&mut Cursor::new(data), data.len()).expect(READ_ERROR_MESSAGE); assert_eq!(int.size_in_bytes(), 0); - assert_eq!(int.value(), &Integer::I64(0)); + assert_eq!(int.value(), &Int::I64(0)); } #[test] @@ -330,7 +330,7 @@ mod tests { let mut buffer: Vec = vec![]; let length = DecodedInt::write_i64(&mut buffer, i64::MAX)?; let i = DecodedInt::read(&mut io::Cursor::new(buffer.as_slice()), length)?; - assert_eq!(i.value, Integer::I64(i64::MAX)); + assert_eq!(i.value, Int::I64(i64::MAX)); Ok(()) } } diff --git a/src/binary/non_blocking/binary_buffer.rs b/src/binary/non_blocking/binary_buffer.rs index ead8b2ee..03acf1eb 100644 --- a/src/binary/non_blocking/binary_buffer.rs +++ b/src/binary/non_blocking/binary_buffer.rs @@ -7,8 +7,8 @@ use crate::binary::uint::DecodedUInt; use crate::binary::var_int::VarInt; use crate::binary::var_uint::VarUInt; use crate::result::{decoding_error, incomplete_data_error, incomplete_data_error_raw}; -use crate::types::integer::UInteger; -use crate::{Integer, IonResult, IonType}; +use crate::types::integer::UInt; +use crate::{Int, IonResult, IonType}; use num_bigint::{BigInt, BigUint, Sign}; use std::io::Read; use std::mem; @@ -278,7 +278,7 @@ impl> BinaryBuffer { .ok_or_else(|| incomplete_data_error_raw("a UInt", self.total_consumed()))?; let magnitude = DecodedUInt::small_uint_from_slice(uint_bytes); self.consume(length); - Ok(DecodedUInt::new(UInteger::U64(magnitude), length)) + Ok(DecodedUInt::new(UInt::U64(magnitude), length)) } /// Reads the first `length` bytes from the buffer as a `UInt`. If `length` is small enough @@ -299,7 +299,7 @@ impl> BinaryBuffer { let magnitude = BigUint::from_bytes_be(uint_bytes); self.consume(length); - Ok(DecodedUInt::new(UInteger::BigUInt(magnitude), length)) + Ok(DecodedUInt::new(UInt::BigUInt(magnitude), length)) } #[inline(never)] @@ -318,7 +318,7 @@ impl> BinaryBuffer { /// See: https://amazon-ion.github.io/ion-docs/docs/binary.html#uint-and-int-fields pub fn read_int(&mut self, length: usize) -> IonResult { if length == 0 { - return Ok(DecodedInt::new(Integer::I64(0), false, 0)); + return Ok(DecodedInt::new(Int::I64(0), false, 0)); } else if length > MAX_INT_SIZE_IN_BYTES { return decoding_error(format!( "Found a {length}-byte Int. Max supported size is {MAX_INT_SIZE_IN_BYTES} bytes." @@ -346,7 +346,7 @@ impl> BinaryBuffer { magnitude <<= 8; magnitude |= byte; } - Integer::I64(sign * magnitude) + Int::I64(sign * magnitude) } else { // This Int is too big for an i64, we'll need to use a BigInt let value = if int_bytes[0] & 0b1000_0000 == 0 { @@ -361,7 +361,7 @@ impl> BinaryBuffer { BigInt::from_bytes_be(Sign::Minus, owned_int_bytes.as_slice()) }; - Integer::BigInt(value) + Int::BigInt(value) }; self.consume(length); Ok(DecodedInt::new(value, is_negative, length)) @@ -684,7 +684,7 @@ mod tests { let mut buffer = BinaryBuffer::new(&[0b1000_0000]); let var_int = buffer.read_uint(buffer.remaining())?; assert_eq!(var_int.size_in_bytes(), 1); - assert_eq!(var_int.value(), &UInteger::U64(128)); + assert_eq!(var_int.value(), &UInt::U64(128)); Ok(()) } @@ -693,7 +693,7 @@ mod tests { let mut buffer = BinaryBuffer::new(&[0b0111_1111, 0b1111_1111]); let var_int = buffer.read_uint(buffer.remaining())?; assert_eq!(var_int.size_in_bytes(), 2); - assert_eq!(var_int.value(), &UInteger::U64(32_767)); + assert_eq!(var_int.value(), &UInt::U64(32_767)); Ok(()) } @@ -702,7 +702,7 @@ mod tests { let mut buffer = BinaryBuffer::new(&[0b0011_1100, 0b1000_0111, 0b1000_0001]); let var_int = buffer.read_uint(buffer.remaining())?; assert_eq!(var_int.size_in_bytes(), 3); - assert_eq!(var_int.value(), &UInteger::U64(3_966_849)); + assert_eq!(var_int.value(), &UInt::U64(3_966_849)); Ok(()) } @@ -714,7 +714,7 @@ mod tests { assert_eq!(uint.size_in_bytes(), 10); assert_eq!( uint.value(), - &UInteger::BigUInt(BigUint::from_str_radix("ffffffffffffffffffff", 16).unwrap()) + &UInt::BigUInt(BigUint::from_str_radix("ffffffffffffffffffff", 16).unwrap()) ); Ok(()) } @@ -734,7 +734,7 @@ mod tests { let mut buffer = BinaryBuffer::new(&[0b1000_0000]); // Negative zero let int = buffer.read_int(buffer.remaining())?; assert_eq!(int.size_in_bytes(), 1); - assert_eq!(int.value(), &Integer::I64(0)); + assert_eq!(int.value(), &Int::I64(0)); assert!(int.is_negative_zero()); Ok(()) } @@ -744,7 +744,7 @@ mod tests { let mut buffer = BinaryBuffer::new(&[0b0000_0000]); // Negative zero let int = buffer.read_int(buffer.remaining())?; assert_eq!(int.size_in_bytes(), 1); - assert_eq!(int.value(), &Integer::I64(0)); + assert_eq!(int.value(), &Int::I64(0)); assert!(!int.is_negative_zero()); Ok(()) } @@ -754,7 +754,7 @@ mod tests { let mut buffer = BinaryBuffer::new(&[]); // Negative zero let int = buffer.read_int(buffer.remaining())?; assert_eq!(int.size_in_bytes(), 0); - assert_eq!(int.value(), &Integer::I64(0)); + assert_eq!(int.value(), &Int::I64(0)); assert!(!int.is_negative_zero()); Ok(()) } @@ -764,7 +764,7 @@ mod tests { let mut buffer = BinaryBuffer::new(&[0b1111_1111, 0b1111_1111]); let int = buffer.read_int(buffer.remaining())?; assert_eq!(int.size_in_bytes(), 2); - assert_eq!(int.value(), &Integer::I64(-32_767)); + assert_eq!(int.value(), &Int::I64(-32_767)); Ok(()) } @@ -773,7 +773,7 @@ mod tests { let mut buffer = BinaryBuffer::new(&[0b0111_1111, 0b1111_1111]); let int = buffer.read_int(buffer.remaining())?; assert_eq!(int.size_in_bytes(), 2); - assert_eq!(int.value(), &Integer::I64(32_767)); + assert_eq!(int.value(), &Int::I64(32_767)); Ok(()) } @@ -782,7 +782,7 @@ mod tests { let mut buffer = BinaryBuffer::new(&[0b1011_1100, 0b1000_0111, 0b1000_0001]); let int = buffer.read_int(buffer.remaining())?; assert_eq!(int.size_in_bytes(), 3); - assert_eq!(int.value(), &Integer::I64(-3_966_849)); + assert_eq!(int.value(), &Int::I64(-3_966_849)); Ok(()) } @@ -791,7 +791,7 @@ mod tests { let mut buffer = BinaryBuffer::new(&[0b0011_1100, 0b1000_0111, 0b1000_0001]); let int = buffer.read_int(buffer.remaining())?; assert_eq!(int.size_in_bytes(), 3); - assert_eq!(int.value(), &Integer::I64(3_966_849)); + assert_eq!(int.value(), &Int::I64(3_966_849)); Ok(()) } diff --git a/src/binary/non_blocking/raw_binary_reader.rs b/src/binary/non_blocking/raw_binary_reader.rs index 6849b128..efc53d67 100644 --- a/src/binary/non_blocking/raw_binary_reader.rs +++ b/src/binary/non_blocking/raw_binary_reader.rs @@ -12,7 +12,7 @@ use crate::result::{ use crate::types::integer::IntAccess; use crate::types::SymbolId; use crate::{ - Decimal, Integer, IonReader, IonResult, IonType, RawStreamItem, RawSymbolToken, Timestamp, + Decimal, Int, IonReader, IonResult, IonType, RawStreamItem, RawSymbolToken, Timestamp, }; use bytes::{BigEndian, Buf, ByteOrder}; use num_bigint::BigUint; @@ -680,15 +680,15 @@ impl> IonReader for RawBinaryBufferReader { } fn read_i64(&mut self) -> IonResult { - self.read_integer().and_then(|i| { + self.read_int().and_then(|i| { i.as_i64() .ok_or_else(|| decoding_error_raw("integer was too large to fit in an i64")) }) } - fn read_integer(&mut self) -> IonResult { - let (encoded_value, bytes) = self.value_and_bytes(IonType::Integer)?; - let value: Integer = if bytes.len() <= mem::size_of::() { + fn read_int(&mut self) -> IonResult { + let (encoded_value, bytes) = self.value_and_bytes(IonType::Int)?; + let value: Int = if bytes.len() <= mem::size_of::() { DecodedUInt::small_uint_from_slice(bytes).into() } else { DecodedUInt::big_uint_from_slice(bytes).into() @@ -1354,7 +1354,7 @@ mod tests { fn read_int_header() -> IonResult<()> { let data = vec![0x21, 0x03]; let mut reader = RawBinaryBufferReader::new(data); - expect_value(reader.next(), IonType::Integer); + expect_value(reader.next(), IonType::Int); expect_eof(reader.next()); Ok(()) } @@ -1364,7 +1364,7 @@ mod tests { let data = vec![0x21]; let mut reader = RawBinaryBufferReader::new(data); // We can read the *header* of the int just fine - expect_value(reader.next(), IonType::Integer); + expect_value(reader.next(), IonType::Int); // Trying to advance beyond it is a problem. expect_incomplete(reader.next()); // This byte completes the int, but we still don't have another value to move to. @@ -1384,12 +1384,12 @@ mod tests { 0x21, 0x03, // 3 ]; let mut reader = RawBinaryBufferReader::new(data); - expect_value(reader.next(), IonType::Integer); - assert_eq!(reader.read_integer()?, Integer::I64(1)); - expect_value(reader.next(), IonType::Integer); - assert_eq!(reader.read_integer()?, Integer::I64(2)); - expect_value(reader.next(), IonType::Integer); - assert_eq!(reader.read_integer()?, Integer::I64(3)); + expect_value(reader.next(), IonType::Int); + assert_eq!(reader.read_int()?, Int::I64(1)); + expect_value(reader.next(), IonType::Int); + assert_eq!(reader.read_int()?, Int::I64(2)); + expect_value(reader.next(), IonType::Int); + assert_eq!(reader.read_int()?, Int::I64(3)); // Nothing else in the buffer expect_eof(reader.next()); Ok(()) @@ -1601,13 +1601,13 @@ mod tests { ]; let mut reader = RawBinaryBufferReader::new(data); - expect_value(reader.next(), IonType::Integer); + expect_value(reader.next(), IonType::Int); expect_annotations(&reader, [4]); - expect_value(reader.next(), IonType::Integer); + expect_value(reader.next(), IonType::Int); expect_annotations(&reader, [5]); - expect_value(reader.next(), IonType::Integer); + expect_value(reader.next(), IonType::Int); expect_annotations(&reader, [6, 7, 8]); // Nothing else in the buffer expect_eof(reader.next()); @@ -1634,7 +1634,7 @@ mod tests { let mut reader = RawBinaryBufferReader::new(data); expect_value(reader.next(), IonType::List); reader.step_in()?; - expect_value(reader.next(), IonType::Integer); + expect_value(reader.next(), IonType::Int); reader.step_out()?; // Skips second int in list expect_value(reader.next(), IonType::String); // Nothing else in the buffer @@ -1644,8 +1644,8 @@ mod tests { let mut reader = RawBinaryBufferReader::new(data); expect_value(reader.next(), IonType::List); reader.step_in()?; - expect_value(reader.next(), IonType::Integer); - expect_value(reader.next(), IonType::Integer); + expect_value(reader.next(), IonType::Int); + expect_value(reader.next(), IonType::Int); reader.step_out()?; // There's an empty string after the list expect_value(reader.next(), IonType::String); @@ -1793,8 +1793,8 @@ mod tests { reader.append_bytes(&[0xff]); assert_eq!(reader.next()?, RawStreamItem::Nothing); reader.append_bytes(&[0x20]); - assert_eq!(reader.next()?, RawStreamItem::Value(IonType::Integer)); - assert_eq!(reader.read_integer()?, Integer::I64(0)); + assert_eq!(reader.next()?, RawStreamItem::Value(IonType::Int)); + assert_eq!(reader.read_int()?, Int::I64(0)); Ok(()) } } diff --git a/src/binary/non_blocking/type_descriptor.rs b/src/binary/non_blocking/type_descriptor.rs index adfcbf50..24e9d915 100644 --- a/src/binary/non_blocking/type_descriptor.rs +++ b/src/binary/non_blocking/type_descriptor.rs @@ -65,8 +65,8 @@ impl TypeDescriptor { NullOrNop if length_code == length_codes::NULL => Some(IonType::Null), NullOrNop => None, Boolean => Some(IonType::Bool), - PositiveInteger => Some(IonType::Integer), - NegativeInteger => Some(IonType::Integer), + PositiveInteger => Some(IonType::Int), + NegativeInteger => Some(IonType::Int), Float => Some(IonType::Float), Decimal => Some(IonType::Decimal), Timestamp => Some(IonType::Timestamp), diff --git a/src/binary/raw_binary_reader.rs b/src/binary/raw_binary_reader.rs index e41ba7eb..18804d69 100644 --- a/src/binary/raw_binary_reader.rs +++ b/src/binary/raw_binary_reader.rs @@ -24,7 +24,7 @@ use crate::raw_symbol_token::RawSymbolToken; use crate::result::{decoding_error_raw, IonError}; use crate::stream_reader::IonReader; use crate::types::decimal::Decimal; -use crate::types::integer::{IntAccess, Integer}; +use crate::types::integer::{Int, IntAccess}; use crate::types::timestamp::Timestamp; use num_traits::Zero; use std::ops::Range; @@ -461,11 +461,11 @@ impl IonReader for RawBinaryReader { } } - fn read_integer(&mut self) -> IonResult { - read_safety_checks!(self, IonType::Integer); + fn read_int(&mut self) -> IonResult { + read_safety_checks!(self, IonType::Int); let uint = self.read_value_as_uint()?; - let value = Integer::from(uint); + let value = Int::from(uint); use self::IonTypeCode::*; let value = match (self.cursor.value.header.ion_type_code, value) { @@ -481,7 +481,7 @@ impl IonReader for RawBinaryReader { } fn read_i64(&mut self) -> IonResult { - self.read_integer()? + self.read_int()? .as_i64() .ok_or_else(|| decoding_error_raw("integer was too large to fit in an i64")) } @@ -525,7 +525,7 @@ impl IonReader for RawBinaryReader { self.cursor.value.value_length - exponent_var_int.size_in_bytes(); let exponent = exponent_var_int.value(); - let coefficient = self.read_int(coefficient_size_in_bytes)?; + let coefficient = self.read_int_primitive(coefficient_size_in_bytes)?; if coefficient.is_negative_zero() { return Ok(Decimal::negative_zero_with_exponent(exponent)); @@ -677,7 +677,7 @@ impl IonReader for RawBinaryReader { let subsecond_coefficient = if coefficient_size_in_bytes == 0 { DecodedInt::zero() } else { - self.read_int(coefficient_size_in_bytes)? + self.read_int_primitive(coefficient_size_in_bytes)? }; let builder = builder @@ -943,18 +943,18 @@ where #[inline(always)] fn read_value_as_uint(&mut self) -> IonResult { let number_of_bytes = self.cursor.value.value_length; - self.read_uint(number_of_bytes) + self.read_uint_primitive(number_of_bytes) } #[inline(always)] - fn read_uint(&mut self, number_of_bytes: usize) -> IonResult { + fn read_uint_primitive(&mut self, number_of_bytes: usize) -> IonResult { let uint = DecodedUInt::read(&mut self.data_source, number_of_bytes)?; self.cursor.bytes_read += uint.size_in_bytes(); Ok(uint) } #[inline(always)] - fn read_int(&mut self, number_of_bytes: usize) -> IonResult { + fn read_int_primitive(&mut self, number_of_bytes: usize) -> IonResult { let int = DecodedInt::read(&mut self.data_source, number_of_bytes)?; self.cursor.bytes_read += int.size_in_bytes(); Ok(int) @@ -1274,7 +1274,7 @@ mod tests { #[test] fn test_read_i64_zero() -> IonResult<()> { let mut cursor = ion_cursor_for(&[0x20]); - assert_eq!(cursor.next()?, Value(IonType::Integer)); + assert_eq!(cursor.next()?, Value(IonType::Int)); assert_eq!(cursor.read_i64()?, 0i64); Ok(()) } @@ -1282,7 +1282,7 @@ mod tests { #[test] fn test_read_i64_positive() -> IonResult<()> { let mut cursor = ion_cursor_for(&[0x21, 0x01]); - assert_eq!(cursor.next()?, Value(IonType::Integer)); + assert_eq!(cursor.next()?, Value(IonType::Int)); assert_eq!(cursor.read_i64()?, 1i64); Ok(()) } @@ -1290,7 +1290,7 @@ mod tests { #[test] fn test_read_i64_negative() -> IonResult<()> { let mut cursor = ion_cursor_for(&[0x31, 0x01]); - assert_eq!(cursor.next()?, Value(IonType::Integer)); + assert_eq!(cursor.next()?, Value(IonType::Int)); assert_eq!(cursor.read_i64()?, -1i64); Ok(()) } @@ -1489,7 +1489,7 @@ mod tests { assert_eq!(cursor.next()?, Value(IonType::List)); let mut list = vec![]; cursor.step_in()?; - while let Value(IonType::Integer) = cursor.next()? { + while let Value(IonType::Int) = cursor.next()? { list.push(cursor.read_i64()?); } cursor.step_out()?; @@ -1513,7 +1513,7 @@ mod tests { assert_eq!(cursor.next()?, Value(IonType::SExp)); let mut sexp = vec![]; cursor.step_in()?; - while let Value(IonType::Integer) = cursor.next()? { + while let Value(IonType::Int) = cursor.next()? { sexp.push(cursor.read_i64()?); } cursor.step_out()?; @@ -1548,13 +1548,13 @@ mod tests { ]); assert_eq!(cursor.next()?, Value(IonType::Struct)); cursor.step_in()?; - assert_eq!(cursor.next()?, Value(IonType::Integer)); + assert_eq!(cursor.next()?, Value(IonType::Int)); assert_eq!(cursor.field_name()?, local_sid_token(10)); assert_eq!(cursor.read_i64()?, 1i64); - assert_eq!(cursor.next()?, Value(IonType::Integer)); + assert_eq!(cursor.next()?, Value(IonType::Int)); assert_eq!(cursor.field_name()?, local_sid_token(11usize)); assert_eq!(cursor.read_i64()?, 2i64); - assert_eq!(cursor.next()?, Value(IonType::Integer)); + assert_eq!(cursor.next()?, Value(IonType::Int)); assert_eq!(cursor.field_name()?, local_sid_token(12usize)); assert_eq!(cursor.read_i64()?, 3i64); cursor.step_out()?; @@ -1585,19 +1585,19 @@ mod tests { assert_eq!(cursor.field_name()?, local_sid_token(11usize)); cursor.step_in()?; - assert_eq!(cursor.next()?, Value(IonType::Integer)); + assert_eq!(cursor.next()?, Value(IonType::Int)); assert_eq!(cursor.read_i64()?, 1i64); - assert_eq!(cursor.next()?, Value(IonType::Integer)); + assert_eq!(cursor.next()?, Value(IonType::Int)); assert_eq!(cursor.read_i64()?, 2i64); - assert_eq!(cursor.next()?, Value(IonType::Integer)); + assert_eq!(cursor.next()?, Value(IonType::Int)); assert_eq!(cursor.read_i64()?, 3i64); assert_eq!(cursor.next()?, Nothing); // End of the list's values cursor.step_out()?; // Step out of list - assert_eq!(cursor.next()?, Value(IonType::Integer)); + assert_eq!(cursor.next()?, Value(IonType::Int)); assert_eq!(cursor.field_name()?, local_sid_token(10usize)); assert_eq!(cursor.read_i64()?, 1i64); @@ -1647,19 +1647,19 @@ mod tests { assert_eq!(cursor.raw_header_bytes(), Some(&ion_data[2..=2])); assert_eq!(cursor.raw_value_bytes(), Some(&ion_data[3..9])); cursor.step_in()?; - assert_eq!(RawStreamItem::Value(IonType::Integer), cursor.next()?); + assert_eq!(RawStreamItem::Value(IonType::Int), cursor.next()?); assert_eq!(cursor.raw_bytes(), Some(&ion_data[3..=4])); assert_eq!(cursor.raw_field_id_bytes(), None); assert_eq!(cursor.raw_annotations_bytes(), None); assert_eq!(cursor.raw_header_bytes(), Some(&ion_data[3..=3])); assert_eq!(cursor.raw_value_bytes(), Some(&ion_data[4..=4])); - assert_eq!(RawStreamItem::Value(IonType::Integer), cursor.next()?); + assert_eq!(RawStreamItem::Value(IonType::Int), cursor.next()?); assert_eq!(cursor.raw_bytes(), Some(&ion_data[5..=6])); assert_eq!(cursor.raw_field_id_bytes(), None); assert_eq!(cursor.raw_annotations_bytes(), None); assert_eq!(cursor.raw_header_bytes(), Some(&ion_data[5..=5])); assert_eq!(cursor.raw_value_bytes(), Some(&ion_data[6..=6])); - assert_eq!(RawStreamItem::Value(IonType::Integer), cursor.next()?); + assert_eq!(RawStreamItem::Value(IonType::Int), cursor.next()?); assert_eq!(cursor.raw_bytes(), Some(&ion_data[7..=8])); assert_eq!(cursor.raw_field_id_bytes(), None); assert_eq!(cursor.raw_annotations_bytes(), None); @@ -1668,7 +1668,7 @@ mod tests { cursor.step_out()?; // Step out of list - assert_eq!(RawStreamItem::Value(IonType::Integer), cursor.next()?); + assert_eq!(RawStreamItem::Value(IonType::Int), cursor.next()?); assert_eq!(cursor.raw_bytes(), Some(&ion_data[9..=11])); assert_eq!(cursor.raw_field_id_bytes(), Some(&ion_data[9..=9])); assert_eq!(cursor.raw_annotations_bytes(), None); @@ -1737,7 +1737,7 @@ mod tests { cursor.step_in()?; // foo: bar::baz::5 - assert_eq!(RawStreamItem::Value(IonType::Integer), cursor.next()?); + assert_eq!(RawStreamItem::Value(IonType::Int), cursor.next()?); assert_eq!(cursor.raw_bytes(), Some(&ion_data[27..34])); assert_eq!(cursor.raw_field_id_bytes(), Some(&ion_data[27..=27])); assert_eq!(cursor.raw_annotations_bytes(), Some(&ion_data[28..32])); @@ -1746,7 +1746,7 @@ mod tests { assert_eq!(cursor.read_i64()?, 5); // quux: 7 - assert_eq!(RawStreamItem::Value(IonType::Integer), cursor.next()?); + assert_eq!(RawStreamItem::Value(IonType::Int), cursor.next()?); assert_eq!(cursor.raw_bytes(), Some(&ion_data[34..37])); assert_eq!(cursor.raw_field_id_bytes(), Some(&ion_data[34..=34])); assert_eq!(cursor.raw_annotations_bytes(), None); @@ -1906,7 +1906,7 @@ mod tests { assert_eq!(cursor.next()?, Value(IonType::List)); cursor.step_in()?; - assert_eq!(cursor.next()?, Value(IonType::Integer)); + assert_eq!(cursor.next()?, Value(IonType::Int)); assert!(matches!(cursor.next(), Err(IonError::DecodingError { .. }))); diff --git a/src/binary/raw_binary_writer.rs b/src/binary/raw_binary_writer.rs index d7d5f6ff..62ed6ef4 100644 --- a/src/binary/raw_binary_writer.rs +++ b/src/binary/raw_binary_writer.rs @@ -15,7 +15,7 @@ use crate::types::decimal::Decimal; use crate::types::timestamp::Timestamp; use crate::types::{ContainerType, SymbolId}; use crate::writer::IonWriter; -use crate::{Integer, IonType}; +use crate::{Int, IonType}; use super::decimal::DecimalBinaryEncoder; use super::timestamp::TimestampBinaryEncoder; @@ -548,7 +548,7 @@ impl IonWriter for RawBinaryWriter { let byte: u8 = match ion_type { IonType::Null => 0x0F, IonType::Bool => 0x1F, - IonType::Integer => 0x2F, + IonType::Int => 0x2F, IonType::Float => 0x4F, IonType::Decimal => 0x5F, IonType::Timestamp => 0x6F, @@ -598,11 +598,11 @@ impl IonWriter for RawBinaryWriter { } /// Writes an Ion integer with the specified value. - fn write_integer(&mut self, value: &Integer) -> IonResult<()> { + fn write_int(&mut self, value: &Int) -> IonResult<()> { // If the `value` is an `i64`, use `write_i64` and return. let value = match value { - Integer::I64(i) => return self.write_i64(*i), - Integer::BigInt(i) => i, + Int::I64(i) => return self.write_i64(*i), + Int::BigInt(i) => i, }; // From here on, `value` is a `BigInt`. @@ -971,7 +971,7 @@ mod writer_tests { let ion_types = &[ IonType::Null, IonType::Bool, - IonType::Integer, + IonType::Int, IonType::Float, IonType::Decimal, IonType::Timestamp, @@ -1014,7 +1014,7 @@ mod writer_tests { fn binary_writer_ints() -> IonResult<()> { binary_writer_scalar_test( &[-24_601, -17, -1, 0, 1, 17, 24_601], - IonType::Integer, + IonType::Int, |writer, v| writer.write_i64(*v), |reader| reader.read_i64(), ) @@ -1136,15 +1136,15 @@ mod writer_tests { } fn expect_integer(reader: &mut TestReader, value: i64) { - expect_scalar(reader, IonType::Integer, |r| r.read_i64(), value); + expect_scalar(reader, IonType::Int, |r| r.read_i64(), value); } fn expect_big_integer(reader: &mut TestReader, value: &BigInt) { expect_scalar( reader, - IonType::Integer, - |r| r.read_integer(), - Integer::BigInt(value.clone()), + IonType::Int, + |r| r.read_int(), + Int::BigInt(value.clone()), ); } @@ -1232,11 +1232,11 @@ mod writer_tests { let very_big_negative = -very_big_positive.clone(); binary_writer_test( |writer| { - writer.write_integer(&Integer::BigInt(BigInt::zero()))?; - writer.write_integer(&Integer::BigInt(big_positive.clone()))?; - writer.write_integer(&Integer::BigInt(very_big_positive.clone()))?; - writer.write_integer(&Integer::BigInt(big_negative.clone()))?; - writer.write_integer(&Integer::BigInt(very_big_negative.clone()))?; + writer.write_int(&Int::BigInt(BigInt::zero()))?; + writer.write_int(&Int::BigInt(big_positive.clone()))?; + writer.write_int(&Int::BigInt(very_big_positive.clone()))?; + writer.write_int(&Int::BigInt(big_negative.clone()))?; + writer.write_int(&Int::BigInt(very_big_negative.clone()))?; Ok(()) }, |reader| { diff --git a/src/binary/type_code.rs b/src/binary/type_code.rs index 08c571d3..c01ab4a7 100644 --- a/src/binary/type_code.rs +++ b/src/binary/type_code.rs @@ -43,7 +43,7 @@ impl TryFrom for IonType { let ion_type = match ion_type_code { NullOrNop => IonType::Null, Boolean => IonType::Bool, - PositiveInteger | NegativeInteger => IonType::Integer, + PositiveInteger | NegativeInteger => IonType::Int, Float => IonType::Float, Decimal => IonType::Decimal, Timestamp => IonType::Timestamp, diff --git a/src/binary/uint.rs b/src/binary/uint.rs index 5531b50c..ca67e256 100644 --- a/src/binary/uint.rs +++ b/src/binary/uint.rs @@ -4,7 +4,7 @@ use std::mem; use crate::data_source::IonDataSource; use crate::result::{decoding_error, IonResult}; -use crate::types::integer::{Integer, UInteger}; +use crate::types::integer::{Int, UInt}; // This limit is used for stack-allocating buffer space to encode/decode UInts. const UINT_STACK_BUFFER_SIZE: usize = 16; @@ -17,11 +17,11 @@ const MAX_UINT_SIZE_IN_BYTES: usize = 2048; #[derive(Debug)] pub struct DecodedUInt { size_in_bytes: usize, - value: UInteger, + value: UInt, } impl DecodedUInt { - pub(crate) fn new(value: UInteger, size_in_bytes: usize) -> Self { + pub(crate) fn new(value: UInt, size_in_bytes: usize) -> Self { DecodedUInt { size_in_bytes, value, @@ -83,11 +83,11 @@ impl DecodedUInt { magnitude <<= 8; magnitude |= byte; } - UInteger::U64(magnitude) + UInt::U64(magnitude) } else { // The UInt is too large to fit in a u64; read it as a BigUInt instead let magnitude = BigUint::from_bytes_be(buffer); - UInteger::BigUInt(magnitude) + UInt::BigUInt(magnitude) }; Ok(DecodedUInt { @@ -107,7 +107,7 @@ impl DecodedUInt { /// Returns the magnitude of the unsigned integer. #[inline(always)] - pub fn value(&self) -> &UInteger { + pub fn value(&self) -> &UInt { &self.value } @@ -119,13 +119,13 @@ impl DecodedUInt { } } -impl From for Integer { +impl From for Int { fn from(uint: DecodedUInt) -> Self { let DecodedUInt { value, .. // Ignore 'size_in_bytes' } = uint; - Integer::from(value) + Int::from(value) } } @@ -191,10 +191,10 @@ pub fn encode_u64(magnitude: u64) -> EncodedUInt { } /// Returns the magnitude as big-endian bytes. -pub fn encode_uinteger(magnitude: &UInteger) -> EncodedUInt { +pub fn encode_uint(magnitude: &UInt) -> EncodedUInt { let magnitude: &BigUint = match magnitude { - UInteger::U64(m) => return encode_u64(*m), - UInteger::BigUInt(m) => m, + UInt::U64(m) => return encode_u64(*m), + UInt::BigUInt(m) => m, }; let be_bytes = UIntBeBytes::Heap(magnitude.to_bytes_be()); @@ -220,7 +220,7 @@ mod tests { let data = &[0b1000_0000]; let uint = DecodedUInt::read(&mut Cursor::new(data), data.len()).expect(READ_ERROR_MESSAGE); assert_eq!(uint.size_in_bytes(), 1); - assert_eq!(uint.value(), &UInteger::U64(128)); + assert_eq!(uint.value(), &UInt::U64(128)); } #[test] @@ -228,7 +228,7 @@ mod tests { let data = &[0b0111_1111, 0b1111_1111]; let uint = DecodedUInt::read(&mut Cursor::new(data), data.len()).expect(READ_ERROR_MESSAGE); assert_eq!(uint.size_in_bytes(), 2); - assert_eq!(uint.value(), &UInteger::U64(32_767)); + assert_eq!(uint.value(), &UInt::U64(32_767)); } #[test] @@ -236,7 +236,7 @@ mod tests { let data = &[0b0011_1100, 0b1000_0111, 0b1000_0001]; let uint = DecodedUInt::read(&mut Cursor::new(data), data.len()).expect(READ_ERROR_MESSAGE); assert_eq!(uint.size_in_bytes(), 3); - assert_eq!(uint.value(), &UInteger::U64(3_966_849)); + assert_eq!(uint.value(), &UInt::U64(3_966_849)); } #[test] @@ -247,7 +247,7 @@ mod tests { assert_eq!(uint.size_in_bytes(), 10); assert_eq!( uint.value(), - &UInteger::BigUInt(BigUint::from_str_radix("ffffffffffffffffffff", 16).unwrap()) + &UInt::BigUInt(BigUint::from_str_radix("ffffffffffffffffffff", 16).unwrap()) ); } @@ -262,9 +262,9 @@ mod tests { #[test] fn test_write_ten_byte_uint() { - let value = UInteger::BigUInt(BigUint::from_str_radix("ffffffffffffffffffff", 16).unwrap()); + let value = UInt::BigUInt(BigUint::from_str_radix("ffffffffffffffffffff", 16).unwrap()); let mut buffer: Vec = vec![]; - let encoded = super::encode_uinteger(&value); + let encoded = super::encode_uint(&value); buffer.write_all(encoded.as_bytes()).unwrap(); let expected_bytes = vec![0xFFu8; 10]; assert_eq!(expected_bytes.as_slice(), buffer.as_slice()); diff --git a/src/element/element_stream_reader.rs b/src/element/element_stream_reader.rs index 482380e7..df5ee364 100644 --- a/src/element/element_stream_reader.rs +++ b/src/element/element_stream_reader.rs @@ -3,9 +3,7 @@ use crate::text::parent_container::ParentContainer; use crate::element::iterators::SymbolsIterator; use crate::element::owned::Element; -use crate::{ - Decimal, Integer, IonError, IonReader, IonResult, IonType, StreamItem, Symbol, Timestamp, -}; +use crate::{Decimal, Int, IonError, IonReader, IonResult, IonType, StreamItem, Symbol, Timestamp}; use std::fmt::Display; use std::mem; @@ -207,23 +205,21 @@ impl IonReader for ElementStreamReader { } fn read_bool(&mut self) -> IonResult { - self.current_value_as("bool value", |v| v.as_boolean()) + self.current_value_as("bool value", |v| v.as_bool()) } - fn read_integer(&mut self) -> IonResult { - self.current_value_as("int value", |v| v.as_integer().map(|i| i.to_owned())) + fn read_int(&mut self) -> IonResult { + self.current_value_as("int value", |v| v.as_int().map(|i| i.to_owned())) } fn read_i64(&mut self) -> IonResult { match self.current_value.as_ref() { - Some(element) if element.as_integer().is_some() => { - match element.as_integer().unwrap() { - Integer::I64(value) => Ok(*value), - Integer::BigInt(value) => { - decoding_error(format!("Integer {value} is too large to fit in an i64.")) - } + Some(element) if element.as_int().is_some() => match element.as_int().unwrap() { + Int::I64(value) => Ok(*value), + Int::BigInt(value) => { + decoding_error(format!("Integer {value} is too large to fit in an i64.")) } - } + }, _ => Err(self.expected("int value")), } } @@ -411,7 +407,7 @@ mod reader_tests { next_type(reader, IonType::List, false); reader.step_in()?; - next_type(reader, IonType::Integer, false); + next_type(reader, IonType::Int, false); assert_eq!(reader.read_i64()?, 1); reader.step_out()?; // This should skip 2, 3 and reach end of the element @@ -442,16 +438,16 @@ mod reader_tests { reader.step_in()?; next_type(reader, IonType::List, false); reader.step_in()?; - next_type(reader, IonType::Integer, false); + next_type(reader, IonType::Int, false); next_type(reader, IonType::List, false); reader.step_in()?; - next_type(reader, IonType::Integer, false); + next_type(reader, IonType::Int, false); // The reader is now at the '2' nested inside of 'foo' reader.step_out()?; reader.step_out()?; next_type(reader, IonType::Struct, false); reader.step_in()?; - next_type(reader, IonType::Integer, false); + next_type(reader, IonType::Int, false); next_type(reader, IonType::SExp, false); reader.step_in()?; next_type(reader, IonType::Bool, false); @@ -480,12 +476,12 @@ mod reader_tests { let reader = &mut ElementStreamReader::new(ion_data); next_type(reader, IonType::Struct, false); reader.step_in()?; - next_type(reader, IonType::Integer, false); + next_type(reader, IonType::Int, false); assert_eq!(reader.field_name()?, Symbol::owned("foo")); next_type(reader, IonType::Struct, false); assert_eq!(reader.field_name()?, Symbol::owned("bar")); reader.step_in()?; - next_type(reader, IonType::Integer, false); + next_type(reader, IonType::Int, false); assert_eq!(reader.read_i64()?, 5); reader.step_out()?; assert_eq!(reader.next()?, StreamItem::Nothing); @@ -596,10 +592,10 @@ mod reader_tests { assert_eq!(reader.next()?, StreamItem::Value(IonType::Struct)); reader.step_in()?; - assert_eq!(reader.next()?, StreamItem::Value(IonType::Integer)); + assert_eq!(reader.next()?, StreamItem::Value(IonType::Int)); assert_eq!(reader.field_name()?, Symbol::owned("a".to_string())); assert_eq!(reader.read_i64()?, 1); - assert_eq!(reader.next()?, StreamItem::Value(IonType::Integer)); + assert_eq!(reader.next()?, StreamItem::Value(IonType::Int)); assert_eq!(reader.field_name()?, Symbol::owned("b".to_string())); assert_eq!(reader.read_i64()?, 2); reader.step_out()?; diff --git a/src/element/mod.rs b/src/element/mod.rs index 6854704f..49ba7eeb 100644 --- a/src/element/mod.rs +++ b/src/element/mod.rs @@ -24,7 +24,7 @@ pub mod writer; mod tests { use crate::element::owned::*; use crate::types::timestamp::Timestamp; - use crate::{ion_list, ion_sexp, ion_struct, Decimal, Integer, IonType, Symbol}; + use crate::{ion_list, ion_sexp, ion_struct, Decimal, Int, IonType, Symbol}; use chrono::*; use rstest::*; use std::iter::{once, Once}; @@ -309,7 +309,7 @@ mod tests { ops: vec![AsBool], op_assert: Box::new(|e: &Element| { let expected = Element::from(true); - assert_eq!(Some(true), e.as_boolean()); + assert_eq!(Some(true), e.as_bool()); assert_eq!(&expected, e); }), } @@ -318,11 +318,11 @@ mod tests { fn i64_case() -> Case { Case { elem: 100.into(), - ion_type: IonType::Integer, + ion_type: IonType::Int, ops: vec![AsAnyInt], op_assert: Box::new(|e: &Element| { let expected: Element = 100i64.into(); - assert_eq!(Some(&Integer::I64(100)), e.as_integer()); + assert_eq!(Some(&Int::I64(100)), e.as_int()); assert_eq!(Some(100), e.as_i64()); assert_eq!(None, e.as_big_int()); assert_eq!(&expected, e); @@ -333,11 +333,11 @@ mod tests { fn big_int_case() -> Case { Case { elem: BigInt::from(100).into(), - ion_type: IonType::Integer, + ion_type: IonType::Int, ops: vec![AsAnyInt], op_assert: Box::new(|e: &Element| { let expected: Element = BigInt::from(100).into(); - assert_eq!(Some(&Integer::BigInt(BigInt::from(100))), e.as_integer()); + assert_eq!(Some(&Int::BigInt(BigInt::from(100))), e.as_int()); assert_eq!(BigInt::from_str("100").unwrap(), *e.as_big_int().unwrap()); assert_eq!(&expected, e); }), @@ -501,11 +501,11 @@ mod tests { // table of negative assertions for each operation let neg_table: Vec<(ElemOp, ElemAssertFn)> = vec![ (IsNull, Box::new(|e| assert!(!e.is_null()))), - (AsBool, Box::new(|e| assert_eq!(None, e.as_boolean()))), + (AsBool, Box::new(|e| assert_eq!(None, e.as_bool()))), ( AsAnyInt, Box::new(|e| { - assert_eq!(None, e.as_integer()); + assert_eq!(None, e.as_int()); assert_eq!(None, e.as_i64()); assert_eq!(None, e.as_big_int()); }), diff --git a/src/element/native_writer.rs b/src/element/native_writer.rs index ae759ea0..c2df2ee0 100644 --- a/src/element/native_writer.rs +++ b/src/element/native_writer.rs @@ -49,8 +49,8 @@ impl NativeElementWriter { match element.ion_type() { IonType::Null => unreachable!("element has IonType::Null but is_null() was false"), - IonType::Bool => self.writer.write_bool(element.as_boolean().unwrap()), - IonType::Integer => self.writer.write_integer(element.as_integer().unwrap()), + IonType::Bool => self.writer.write_bool(element.as_bool().unwrap()), + IonType::Int => self.writer.write_int(element.as_int().unwrap()), IonType::Float => self.writer.write_f64(element.as_float().unwrap()), IonType::Decimal => self.writer.write_decimal(element.as_decimal().unwrap()), IonType::Timestamp => self.writer.write_timestamp(element.as_timestamp().unwrap()), diff --git a/src/element/owned.rs b/src/element/owned.rs index acf8d3bd..b4c78d97 100644 --- a/src/element/owned.rs +++ b/src/element/owned.rs @@ -3,7 +3,7 @@ use crate::ion_eq::IonEq; use crate::text::text_formatter::IonValueFormatter; use crate::types::decimal::Decimal; -use crate::types::integer::Integer; +use crate::types::integer::Int; use crate::types::timestamp::Timestamp; use crate::{IonResult, IonType, ReaderBuilder, Symbol}; use num_bigint::BigInt; @@ -37,8 +37,8 @@ impl Element { symbol.into() } - pub fn integer>(integer: I) -> Element { - let integer: Integer = integer.into(); + pub fn integer>(integer: I) -> Element { + let integer: Int = integer.into(); integer.into() } @@ -427,7 +427,7 @@ impl IonEq for Vec { #[derive(Debug, Clone, PartialEq)] pub enum Value { Null(IonType), - Integer(Integer), + Int(Int), Float(f64), Decimal(Decimal), Timestamp(Timestamp), @@ -447,7 +447,7 @@ impl Display for Value { match &self { Value::Null(ion_type) => ivf.format_null(*ion_type), Value::Bool(bool) => ivf.format_bool(*bool), - Value::Integer(integer) => ivf.format_integer(integer), + Value::Int(integer) => ivf.format_integer(integer), Value::Float(float) => ivf.format_float(*float), Value::Decimal(decimal) => ivf.format_decimal(decimal), Value::Timestamp(timestamp) => ivf.format_timestamp(timestamp), @@ -525,19 +525,19 @@ impl From for Value { impl From for Value { fn from(i64_val: i64) -> Self { - Value::Integer(Integer::I64(i64_val)) + Value::Int(Int::I64(i64_val)) } } impl From for Value { fn from(big_int_val: BigInt) -> Self { - Value::Integer(Integer::BigInt(big_int_val)) + Value::Int(Int::BigInt(big_int_val)) } } -impl From for Value { - fn from(integer_val: Integer) -> Self { - Value::Integer(integer_val) +impl From for Value { + fn from(integer_val: Int) -> Self { + Value::Int(integer_val) } } @@ -637,7 +637,7 @@ impl Element { match &self.value { Null(t) => *t, - Integer(_) => IonType::Integer, + Int(_) => IonType::Int, Float(_) => IonType::Float, Decimal(_) => IonType::Decimal, Timestamp(_) => IonType::Timestamp, @@ -674,9 +674,9 @@ impl Element { matches!(&self.value, Value::Null(_)) } - pub fn as_integer(&self) -> Option<&Integer> { + pub fn as_int(&self) -> Option<&Int> { match &self.value { - Value::Integer(i) => Some(i), + Value::Int(i) => Some(i), _ => None, } } @@ -724,7 +724,7 @@ impl Element { } } - pub fn as_boolean(&self) -> Option { + pub fn as_bool(&self) -> Option { match &self.value { Value::Bool(b) => Some(*b), _ => None, diff --git a/src/element/reader.rs b/src/element/reader.rs index 7f077645..07a376cb 100644 --- a/src/element/reader.rs +++ b/src/element/reader.rs @@ -142,7 +142,7 @@ impl<'a, R: IonReader> ElementLoader<'a, R> match ion_type { Null => unreachable!("non-null value had IonType::Null"), Bool => Value::Bool(self.reader.read_bool()?), - Integer => Value::Integer(self.reader.read_integer()?), + Int => Value::Int(self.reader.read_int()?), Float => Value::Float(self.reader.read_f64()?), Decimal => Value::Decimal(self.reader.read_decimal()?), Timestamp => Value::Timestamp(self.reader.read_timestamp()?), @@ -198,7 +198,7 @@ mod reader_tests { use crate::element::owned::Value::*; use crate::element::owned::{Element, IntoAnnotatedElement}; use crate::ion_eq::IonEq; - use crate::types::integer::Integer; + use crate::types::integer::Int; use crate::types::timestamp::Timestamp as TS; use crate::{IonType, Symbol}; use bigdecimal::BigDecimal; @@ -226,7 +226,7 @@ mod reader_tests { vec![ Null(IonType::Null), Null(IonType::Bool), - Null(IonType::Integer), + Null(IonType::Int), Null(IonType::Float), Null(IonType::Decimal), Null(IonType::Timestamp), @@ -253,27 +253,27 @@ mod reader_tests { -65536, 65535, -4294967296, 4294967295, -9007199254740992, 9007199254740991, - ].into_iter().map(Integer::I64).chain( + ].into_iter().map(Int::I64).chain( vec![ "-18446744073709551616", "18446744073709551615", "-79228162514264337593543950336", "79228162514264337593543950335", ].into_iter() - .map(|v| Integer::BigInt(BigInt::parse_bytes(v.as_bytes(), 10).unwrap())) - ).map(|ai| Integer(ai).into()).collect(), + .map(|v| Int::BigInt(BigInt::parse_bytes(v.as_bytes(), 10).unwrap())) + ).map(|ai| Int(ai).into()).collect(), )] #[case::int64_threshold_as_big_int( &[0xE0, 0x01, 0x00, 0xEA, 0x28, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF], vec![ "18446744073709551615", ].into_iter() - .map(|v| Integer::BigInt(BigInt::parse_bytes(v.as_bytes(), 10).unwrap())).map(|ai| Integer(ai).into()).collect(), + .map(|v| Int::BigInt(BigInt::parse_bytes(v.as_bytes(), 10).unwrap())).map(|ai| Int(ai).into()).collect(), )] #[case::int64_threshold_as_int64( &[0xE0, 0x01, 0x00, 0xEA, 0x38, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], vec![ "-9223372036854775808", ].into_iter() - .map(|v| Integer::BigInt(BigInt::parse_bytes(v.as_bytes(), 10).unwrap())).map(|ai| Integer(ai).into()).collect(), + .map(|v| Int::BigInt(BigInt::parse_bytes(v.as_bytes(), 10).unwrap())).map(|ai| Int(ai).into()).collect(), )] #[case::floats( br#" diff --git a/src/ion_hash/representation.rs b/src/ion_hash/representation.rs index b416a5af..6063d3c3 100644 --- a/src/ion_hash/representation.rs +++ b/src/ion_hash/representation.rs @@ -11,7 +11,7 @@ use crate::element::owned::{Element, IonSequence, List, SExp, Struct}; use crate::ion_hash::element_hasher::ElementHasher; use crate::ion_hash::type_qualifier::type_qualifier_symbol; use crate::types::decimal::Decimal; -use crate::types::integer::Integer; +use crate::types::integer::Int; use crate::{result::IonResult, types::timestamp::Timestamp, IonType, Symbol}; use digest::{FixedOutput, Output, Reset, Update}; @@ -19,7 +19,7 @@ pub(crate) trait RepresentationEncoder { fn update_with_representation(&mut self, elem: &Element) -> IonResult<()> { match elem.ion_type() { IonType::Null | IonType::Bool => {} // these types have no representation - IonType::Integer => self.write_repr_integer(elem.as_integer())?, + IonType::Int => self.write_repr_integer(elem.as_int())?, IonType::Float => self.write_repr_float(elem.as_float())?, IonType::Decimal => self.write_repr_decimal(elem.as_decimal())?, IonType::Timestamp => self.write_repr_timestamp(elem.as_timestamp())?, @@ -34,7 +34,7 @@ pub(crate) trait RepresentationEncoder { Ok(()) } - fn write_repr_integer(&mut self, value: Option<&Integer>) -> IonResult<()>; + fn write_repr_integer(&mut self, value: Option<&Int>) -> IonResult<()>; fn write_repr_float(&mut self, value: Option) -> IonResult<()>; fn write_repr_decimal(&mut self, value: Option<&Decimal>) -> IonResult<()>; fn write_repr_timestamp(&mut self, value: Option<&Timestamp>) -> IonResult<()>; @@ -50,9 +50,9 @@ impl RepresentationEncoder for ElementHasher where D: Update + FixedOutput + Reset + Clone + Default, { - fn write_repr_integer(&mut self, value: Option<&Integer>) -> IonResult<()> { + fn write_repr_integer(&mut self, value: Option<&Int>) -> IonResult<()> { match value { - Some(Integer::I64(v)) => match v { + Some(Int::I64(v)) => match v { 0 => {} _ => { let magnitude = v.unsigned_abs(); @@ -60,7 +60,7 @@ where self.update_escaping(encoded.as_bytes()); } }, - Some(Integer::BigInt(b)) => self.update_escaping(&b.magnitude().to_bytes_be()[..]), + Some(Int::BigInt(b)) => self.update_escaping(&b.magnitude().to_bytes_be()[..]), None => {} } diff --git a/src/ion_hash/type_qualifier.rs b/src/ion_hash/type_qualifier.rs index b0748534..4daeb93a 100644 --- a/src/ion_hash/type_qualifier.rs +++ b/src/ion_hash/type_qualifier.rs @@ -7,7 +7,7 @@ use std::slice; ///! [spec]: https://amazon-ion.github.io/ion-hash/docs/spec.html. use crate::binary::IonTypeCode; use crate::element::owned::{Element, List, SExp, Struct}; -use crate::{Decimal, Integer, IonType, Symbol, Timestamp}; +use crate::{Decimal, Int, IonType, Symbol, Timestamp}; use num_bigint::Sign; // For many types, the qualifier is either 'null' or 'not null'. That's what @@ -38,8 +38,8 @@ impl TypeQualifier { pub(crate) fn from_element(elem: &Element) -> TypeQualifier { match elem.ion_type() { IonType::Null => type_qualifier_null(), - IonType::Bool => type_qualifier_boolean(elem.as_boolean()), - IonType::Integer => type_qualifier_integer(elem.as_integer()), + IonType::Bool => type_qualifier_boolean(elem.as_bool()), + IonType::Int => type_qualifier_integer(elem.as_int()), IonType::Float => type_qualifier_float(elem.as_float()), IonType::Decimal => type_qualifier_decimal(elem.as_decimal()), IonType::Timestamp => type_qualifier_timestamp(elem.as_timestamp()), @@ -59,12 +59,12 @@ impl TypeQualifier { } } -fn is_integer_positive(value: Option<&Integer>) -> bool { +fn is_integer_positive(value: Option<&Int>) -> bool { match value { None => true, Some(any) => match any { - Integer::I64(i) => *i >= 0, - Integer::BigInt(b) => !std::matches!(b.sign(), Sign::Minus), + Int::I64(i) => *i >= 0, + Int::BigInt(b) => !std::matches!(b.sign(), Sign::Minus), }, } } @@ -93,7 +93,7 @@ pub(crate) fn type_qualifier_boolean(value: Option) -> TypeQualifier { combine(IonTypeCode::Boolean, q) } -pub(crate) fn type_qualifier_integer(any: Option<&Integer>) -> TypeQualifier { +pub(crate) fn type_qualifier_integer(any: Option<&Int>) -> TypeQualifier { let t = match is_integer_positive(any) { true => IonTypeCode::PositiveInteger, false => IonTypeCode::NegativeInteger, diff --git a/src/lib.rs b/src/lib.rs index b719ba3f..842da4f6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -38,7 +38,7 @@ pub use symbol_ref::SymbolRef; pub use symbol_table::SymbolTable; pub use types::decimal::Decimal; -pub use types::integer::Integer; +pub use types::integer::Int; pub use types::timestamp::Timestamp; pub use types::IonType; diff --git a/src/raw_reader.rs b/src/raw_reader.rs index e5531678..c89a772b 100644 --- a/src/raw_reader.rs +++ b/src/raw_reader.rs @@ -1,7 +1,7 @@ use crate::raw_symbol_token::RawSymbolToken; use crate::stream_reader::IonReader; use crate::types::IonType; -use crate::{Decimal, Integer, IonResult, Timestamp}; +use crate::{Decimal, Int, IonResult, Timestamp}; use std::fmt::{Display, Formatter}; /// `RawReader` is a shorthand for a [Reader](crate::Reader) implementation that returns [RawStreamItem]s and @@ -68,8 +68,8 @@ impl IonReader for Box { (**self).read_i64() } - fn read_integer(&mut self) -> IonResult { - (**self).read_integer() + fn read_int(&mut self) -> IonResult { + (**self).read_int() } fn read_f32(&mut self) -> IonResult { diff --git a/src/reader.rs b/src/reader.rs index 9bd7e808..c113e9db 100644 --- a/src/reader.rs +++ b/src/reader.rs @@ -14,7 +14,7 @@ use crate::stream_reader::IonReader; use crate::symbol::Symbol; use crate::symbol_table::SymbolTable; use crate::types::decimal::Decimal; -use crate::types::integer::Integer; +use crate::types::integer::Int; use crate::types::timestamp::Timestamp; use crate::{IonType, RawBinaryReader, RawTextReader}; use std::fmt::{Display, Formatter}; @@ -426,7 +426,7 @@ impl IonReader for UserReader { fn ion_type(&self) -> Option; fn read_null(&mut self) -> IonResult; fn read_bool(&mut self) -> IonResult; - fn read_integer(&mut self) -> IonResult; + fn read_int(&mut self) -> IonResult; fn read_i64(&mut self) -> IonResult; fn read_f32(&mut self) -> IonResult; fn read_f64(&mut self) -> IonResult; @@ -550,13 +550,13 @@ mod tests { assert_eq!(Value(IonType::Struct), reader.next()?); reader.step_in()?; - assert_eq!(reader.next()?, Value(IonType::Integer)); + assert_eq!(reader.next()?, Value(IonType::Int)); assert_eq!(reader.field_name()?, "foo"); - assert_eq!(reader.next()?, Value(IonType::Integer)); + assert_eq!(reader.next()?, Value(IonType::Int)); assert_eq!(reader.field_name()?, "bar"); - assert_eq!(reader.next()?, Value(IonType::Integer)); + assert_eq!(reader.next()?, Value(IonType::Int)); assert_eq!(reader.field_name()?, "baz"); Ok(()) diff --git a/src/stream_reader.rs b/src/stream_reader.rs index b2f895aa..8b86549a 100644 --- a/src/stream_reader.rs +++ b/src/stream_reader.rs @@ -1,6 +1,6 @@ use crate::result::IonResult; use crate::types::decimal::Decimal; -use crate::types::integer::Integer; +use crate::types::integer::Int; use crate::types::timestamp::Timestamp; use crate::types::IonType; @@ -83,10 +83,10 @@ pub trait IonReader { /// error is encountered while reading, returns [crate::IonError]. fn read_i64(&mut self) -> IonResult; - /// Attempts to read the current item as an Ion integer and return it as an [crate::Integer]. If the + /// Attempts to read the current item as an Ion integer and return it as an [crate::Int]. If the /// current item is not an integer or an IO error is encountered while reading, returns /// [crate::IonError]. - fn read_integer(&mut self) -> IonResult; + fn read_int(&mut self) -> IonResult; /// Attempts to read the current item as an Ion float and return it as an f32. If the current /// item is not a float or an IO error is encountered while reading, returns [crate::IonError]. diff --git a/src/system_reader.rs b/src/system_reader.rs index 9024a3a1..93555438 100644 --- a/src/system_reader.rs +++ b/src/system_reader.rs @@ -10,7 +10,7 @@ use crate::result::{decoding_error, decoding_error_raw, illegal_operation, IonEr use crate::symbol::Symbol; use crate::system_reader::LstPosition::*; use crate::types::decimal::Decimal; -use crate::types::integer::Integer; +use crate::types::integer::Int; use crate::types::timestamp::Timestamp; use crate::{IonReader, IonType, RawBinaryReader, SymbolTable}; @@ -705,7 +705,7 @@ impl IonReader for SystemReader { fn ion_type(&self) -> Option; fn read_null(&mut self) -> IonResult; fn read_bool(&mut self) -> IonResult; - fn read_integer(&mut self) -> IonResult; + fn read_int(&mut self) -> IonResult; fn read_i64(&mut self) -> IonResult; fn read_f32(&mut self) -> IonResult; fn read_f64(&mut self) -> IonResult; diff --git a/src/text/non_blocking/raw_text_reader.rs b/src/text/non_blocking/raw_text_reader.rs index 6495c06b..c3a710f4 100644 --- a/src/text/non_blocking/raw_text_reader.rs +++ b/src/text/non_blocking/raw_text_reader.rs @@ -19,7 +19,7 @@ use crate::text::parsers::containers::{ use crate::text::parsers::top_level::{stream_item, RawTextStreamItem}; use crate::text::text_value::{AnnotatedTextValue, TextValue}; use crate::types::decimal::Decimal; -use crate::types::integer::Integer; +use crate::types::integer::Int; use crate::types::timestamp::Timestamp; use crate::IonType; @@ -580,7 +580,7 @@ impl> RawTextReader { let value = match stream_item(&remaining_text) { Ok(("\n", RawTextStreamItem::AnnotatedTextValue(value))) if value.annotations().is_empty() - && *value.value() == TextValue::Integer(Integer::I64(0)) => + && *value.value() == TextValue::Int(Int::I64(0)) => { // We found the unannotated zero that we appended to the end of the buffer. // The "\n" in this pattern is the unparsed text left in the buffer, @@ -772,22 +772,22 @@ impl> IonReader for RawTextReader { fn read_bool(&mut self) -> IonResult { match self.current_value.as_ref().map(|current| current.value()) { - Some(TextValue::Boolean(value)) => Ok(*value), + Some(TextValue::Bool(value)) => Ok(*value), _ => Err(self.expected("bool value")), } } - fn read_integer(&mut self) -> IonResult { + fn read_int(&mut self) -> IonResult { match self.current_value.as_ref().map(|current| current.value()) { - Some(TextValue::Integer(value)) => Ok(value.clone()), + Some(TextValue::Int(value)) => Ok(value.clone()), _ => Err(self.expected("int value")), } } fn read_i64(&mut self) -> IonResult { match self.current_value.as_ref().map(|current| current.value()) { - Some(TextValue::Integer(Integer::I64(value))) => Ok(*value), - Some(TextValue::Integer(Integer::BigInt(value))) => { + Some(TextValue::Int(Int::I64(value))) => Ok(*value), + Some(TextValue::Int(Int::BigInt(value))) => { decoding_error(format!("Integer {value} is too large to fit in an i64.")) } _ => Err(self.expected("int value")), @@ -1003,9 +1003,9 @@ mod reader_tests { let mut reader = RawTextReader::new(ion_data.as_bytes().to_owned()); next_type(&mut reader, IonType::List, false); reader.step_in()?; - next_type(&mut reader, IonType::Integer, false); + next_type(&mut reader, IonType::Int, false); assert_eq!(reader.read_i64()?, 1); - next_type(&mut reader, IonType::Integer, false); + next_type(&mut reader, IonType::Int, false); assert_eq!(reader.read_i64()?, 2); match reader.next() { // the failure occurs after reading the \n after 3, so it is identified on line 3. @@ -1026,7 +1026,7 @@ mod reader_tests { reader .append_bytes("]".as_bytes()) .expect("Unable to append bytes"); - next_type(&mut reader, IonType::Integer, false); + next_type(&mut reader, IonType::Int, false); assert_eq!(reader.read_i64()?, 3); Ok(()) } @@ -1068,18 +1068,18 @@ mod reader_tests { 0 [1, 2, 3] (4 5) 6 "#; let reader = &mut RawTextReader::new(ion_data); - next_type(reader, IonType::Integer, false); + next_type(reader, IonType::Int, false); assert_eq!(reader.read_i64()?, 0); next_type(reader, IonType::List, false); reader.step_in()?; - next_type(reader, IonType::Integer, false); + next_type(reader, IonType::Int, false); assert_eq!(reader.read_i64()?, 1); reader.step_out()?; // This should have skipped over the `2, 3` at the end of the list. next_type(reader, IonType::SExp, false); // Don't step into the s-expression. Instead, skip over it. - next_type(reader, IonType::Integer, false); + next_type(reader, IonType::Int, false); assert_eq!(reader.read_i64()?, 6); Ok(()) } @@ -1105,16 +1105,16 @@ mod reader_tests { reader.step_in()?; next_type(reader, IonType::List, false); reader.step_in()?; - next_type(reader, IonType::Integer, false); + next_type(reader, IonType::Int, false); next_type(reader, IonType::List, false); reader.step_in()?; - next_type(reader, IonType::Integer, false); + next_type(reader, IonType::Int, false); // The reader is now at the '2' nested inside of 'foo' reader.step_out()?; reader.step_out()?; next_type(reader, IonType::Struct, false); reader.step_in()?; - next_type(reader, IonType::Integer, false); + next_type(reader, IonType::Int, false); next_type(reader, IonType::SExp, false); reader.step_in()?; next_type(reader, IonType::Bool, false); @@ -1123,7 +1123,7 @@ mod reader_tests { reader.step_out()?; reader.step_out()?; reader.step_out()?; - next_type(reader, IonType::Integer, false); + next_type(reader, IonType::Int, false); assert_eq!(reader.read_i64()?, 11); Ok(()) } @@ -1144,17 +1144,17 @@ mod reader_tests { let reader = &mut RawTextReader::new(ion_data); next_type(reader, IonType::Struct, false); reader.step_in()?; - next_type(reader, IonType::Integer, false); + next_type(reader, IonType::Int, false); assert_eq!(reader.field_name()?, text_token("foo")); next_type(reader, IonType::Struct, false); assert_eq!(reader.field_name()?, text_token("bar")); reader.step_in()?; - next_type(reader, IonType::Integer, false); + next_type(reader, IonType::Int, false); assert_eq!(reader.read_i64()?, 5); reader.step_out()?; assert_eq!(reader.next()?, RawStreamItem::Nothing); reader.step_out()?; - next_type(reader, IonType::Integer, false); + next_type(reader, IonType::Int, false); assert_eq!(reader.read_i64()?, 42); Ok(()) } @@ -1162,9 +1162,9 @@ mod reader_tests { #[rstest] #[case(" null ", TextValue::Null(IonType::Null))] #[case(" null.string ", TextValue::Null(IonType::String))] - #[case(" true ", TextValue::Boolean(true))] - #[case(" false ", TextValue::Boolean(false))] - #[case(" 738 ", TextValue::Integer(Integer::I64(738)))] + #[case(" true ", TextValue::Bool(true))] + #[case(" false ", TextValue::Bool(false))] + #[case(" 738 ", TextValue::Int(Int::I64(738)))] #[case(" 2.5e0 ", TextValue::Float(2.5))] #[case(" 2.5 ", TextValue::Decimal(Decimal::new(25, -1)))] #[case(" 2007-07-12T ", TextValue::Timestamp(Timestamp::with_ymd(2007, 7, 12).build().unwrap()))] @@ -1211,7 +1211,7 @@ mod reader_tests { next_type(reader, IonType::Bool, false); assert!(reader.read_bool()?); - next_type(reader, IonType::Integer, false); + next_type(reader, IonType::Int, false); assert_eq!(reader.read_i64()?, 5); next_type(reader, IonType::Float, false); @@ -1301,7 +1301,7 @@ mod reader_tests { Timestamp::with_ymd(2014, 6, 26).build()? ); // TODO: Check for 'km' annotation after change to OwnedSymbolToken - next_type(reader, IonType::Integer, false); + next_type(reader, IonType::Int, false); assert_eq!(reader.read_i64()?, 36); Ok(()) } @@ -1332,7 +1332,7 @@ mod reader_tests { assert!(reader.read_bool()?); annotations_eq(reader, ["venus", "earth"]); - next_type(reader, IonType::Integer, false); + next_type(reader, IonType::Int, false); assert_eq!(reader.read_i64()?, 5); annotations_eq(reader, &[local_sid_token(17), text_token("mars")]); @@ -1375,13 +1375,13 @@ mod reader_tests { // Reading a list: pluto::[1, $77::2, 3] next_type(reader, IonType::List, false); reader.step_in()?; - next_type(reader, IonType::Integer, false); + next_type(reader, IonType::Int, false); assert_eq!(reader.number_of_annotations(), 0); assert_eq!(reader.read_i64()?, 1); - next_type(reader, IonType::Integer, false); + next_type(reader, IonType::Int, false); annotations_eq(reader, [77]); assert_eq!(reader.read_i64()?, 2); - next_type(reader, IonType::Integer, false); + next_type(reader, IonType::Int, false); assert_eq!(reader.number_of_annotations(), 0); assert_eq!(reader.read_i64()?, 3); assert_eq!(reader.next()?, Nothing); @@ -1424,10 +1424,10 @@ mod reader_tests { assert_eq!(reader.next()?, RawStreamItem::Value(IonType::Struct)); reader.step_in()?; - assert_eq!(reader.next()?, RawStreamItem::Value(IonType::Integer)); + assert_eq!(reader.next()?, RawStreamItem::Value(IonType::Int)); assert_eq!(reader.field_name()?, RawSymbolToken::Text("a".to_string())); assert_eq!(reader.read_i64()?, 1); - assert_eq!(reader.next()?, RawStreamItem::Value(IonType::Integer)); + assert_eq!(reader.next()?, RawStreamItem::Value(IonType::Int)); assert_eq!(reader.field_name()?, RawSymbolToken::Text("b".to_string())); assert_eq!(reader.read_i64()?, 2); reader.step_out()?; @@ -1490,7 +1490,7 @@ mod reader_tests { other => panic!("unexpected return from next: {other:?}"), } - assert_eq!(reader.ion_type().unwrap(), IonType::Integer); + assert_eq!(reader.ion_type().unwrap(), IonType::Int); assert_eq!(reader.field_name()?.text(), Some("field")); Ok(()) @@ -1585,7 +1585,7 @@ mod reader_tests { // We've stepped out of the inner structs, and we should be at the last field in the outter // most container. let result = reader.next()?; - assert_eq!(result, RawStreamItem::Value(IonType::Integer)); + assert_eq!(result, RawStreamItem::Value(IonType::Int)); assert_eq!(reader.field_name()?.text(), Some("other_field")); assert_eq!(reader.read_i64()?, 21); @@ -1617,13 +1617,13 @@ mod reader_tests { // Read 'foo'.. let result = reader.next()?; - assert_eq!(result, RawStreamItem::Value(IonType::Integer)); + assert_eq!(result, RawStreamItem::Value(IonType::Int)); assert_eq!(reader.field_name()?.text(), Some("foo")); assert_eq!(reader.read_i64()?, 1); // Read "bar" let result = reader.next()?; - assert_eq!(result, RawStreamItem::Value(IonType::Integer)); + assert_eq!(result, RawStreamItem::Value(IonType::Int)); assert_eq!(reader.field_name()?.text(), Some("bar")); assert_eq!(reader.read_i64()?, 2); @@ -1676,13 +1676,13 @@ mod reader_tests { // Read 'foo'.. let result = reader.next()?; - assert_eq!(result, RawStreamItem::Value(IonType::Integer)); + assert_eq!(result, RawStreamItem::Value(IonType::Int)); assert_eq!(reader.field_name()?.text(), Some("foo")); assert_eq!(reader.read_i64()?, 1); // Read "bar" let result = reader.next()?; - assert_eq!(result, RawStreamItem::Value(IonType::Integer)); + assert_eq!(result, RawStreamItem::Value(IonType::Int)); assert_eq!(reader.field_name()?.text(), Some("bar")); assert_eq!(reader.read_i64()?, 2); @@ -1773,7 +1773,7 @@ mod reader_tests { reader.step_in()?; // Step in, so we can read a value first.. let mut result = reader.next()?; - assert_eq!(result, RawStreamItem::Value(IonType::Integer)); + assert_eq!(result, RawStreamItem::Value(IonType::Int)); assert_eq!(reader.field_name()?.text(), Some("foo")); match reader.step_out() { diff --git a/src/text/parent_container.rs b/src/text/parent_container.rs index d54d47c5..a2ae6255 100644 --- a/src/text/parent_container.rs +++ b/src/text/parent_container.rs @@ -50,7 +50,7 @@ mod parent_container_tests { #[case::list(IonType::SExp)] #[case::list(IonType::Struct)] #[should_panic] - #[case::list(IonType::Integer)] + #[case::list(IonType::Int)] #[should_panic] #[case::list(IonType::Null)] #[should_panic] diff --git a/src/text/parsers/boolean.rs b/src/text/parsers/boolean.rs index 7c446ca8..6500d5c1 100644 --- a/src/text/parsers/boolean.rs +++ b/src/text/parsers/boolean.rs @@ -10,13 +10,13 @@ use crate::text::parsers::stop_character; use crate::text::text_value::TextValue; /// Matches the text representation of a boolean value and returns the resulting `true` or `false` -/// as a [TextValue::Boolean]. +/// as a [TextValue::Bool]. pub(crate) fn parse_boolean(input: &str) -> IonParseResult { map( recognize(terminated(tag("true").or(tag("false")), stop_character)), |bool_text: &str| match bool_text { - "true" => TextValue::Boolean(true), - "false" => TextValue::Boolean(false), + "true" => TextValue::Bool(true), + "false" => TextValue::Bool(false), _ => unreachable!("text had to match 'true' or 'false' before reaching this point"), }, )(input) @@ -29,7 +29,7 @@ mod boolean_parsing_tests { use crate::text::text_value::TextValue; fn parse_equals(text: &str, expected: bool) { - parse_test_ok(parse_boolean, text, TextValue::Boolean(expected)) + parse_test_ok(parse_boolean, text, TextValue::Bool(expected)) } fn parse_fails(text: &str) { diff --git a/src/text/parsers/containers.rs b/src/text/parsers/containers.rs index d7d11308..faccc241 100644 --- a/src/text/parsers/containers.rs +++ b/src/text/parsers/containers.rs @@ -29,9 +29,9 @@ pub(crate) fn list_start(input: &str) -> IResult<&str, TextValue> { value(TextValue::ListStart, tag("["))(input) } -/// Matches the beginning of an s-expression and returns a [TextValue::SExpressionStart]. +/// Matches the beginning of an s-expression and returns a [TextValue::SExpStart]. pub(crate) fn s_expression_start(input: &str) -> IResult<&str, TextValue> { - value(TextValue::SExpressionStart, tag("("))(input) + value(TextValue::SExpStart, tag("("))(input) } /// Matches the end of a struct and returns a `&str` containing the delimiter. @@ -233,14 +233,14 @@ mod container_parsing_tests { use crate::text::parsers::unit_test_support::{parse_test_err, parse_test_ok}; use crate::text::text_value::TextValue; use crate::types::decimal::Decimal; - use crate::types::integer::Integer; + use crate::types::integer::Int; use super::*; #[rstest] #[case::start_of_struct("{", TextValue::StructStart)] #[case::start_of_list("[", TextValue::ListStart)] - #[case::start_of_s_expression("(", TextValue::SExpressionStart)] + #[case::start_of_s_expression("(", TextValue::SExpStart)] fn test_parse_container_start_ok(#[case] text: &str, #[case] expected: TextValue) { parse_test_ok(container_start, text, expected) } @@ -257,8 +257,8 @@ mod container_parsing_tests { } #[rstest] - #[case("5,", TextValue::Integer(Integer::I64(5)).without_annotations())] - #[case("foo::bar::5,", TextValue::Integer(Integer::I64(5)).with_annotations(["foo", "bar"]))] + #[case("5,", TextValue::Int(Int::I64(5)).without_annotations())] + #[case("foo::bar::5,", TextValue::Int(Int::I64(5)).with_annotations(["foo", "bar"]))] #[case("foo::bar,", TextValue::Symbol(text_token("bar")).with_annotations("foo"))] #[case("bar]", TextValue::Symbol(text_token("bar")).without_annotations())] #[case("7.]", TextValue::Decimal(Decimal::new(7, 0)).without_annotations())] @@ -275,8 +275,8 @@ mod container_parsing_tests { #[rstest] #[case("'++',", Some(TextValue::Symbol(text_token("++")).without_annotations()))] #[case("foo::'++',", Some(TextValue::Symbol(text_token("++")).with_annotations("foo")))] - #[case("5 ,", Some(TextValue::Integer(Integer::I64(5)).without_annotations()))] - #[case("5]", Some(TextValue::Integer(Integer::I64(5)).without_annotations()))] + #[case("5 ,", Some(TextValue::Int(Int::I64(5)).without_annotations()))] + #[case("5]", Some(TextValue::Int(Int::I64(5)).without_annotations()))] #[case("]", None)] #[case(" ]", None)] #[case(" /*comment*/ ]", None)] @@ -290,9 +290,9 @@ mod container_parsing_tests { #[rstest] #[case("++ ", TextValue::Symbol(text_token("++")).without_annotations())] #[case("foo::++ ", TextValue::Symbol(text_token("++")).with_annotations("foo"))] - #[case("5 ", TextValue::Integer(Integer::I64(5)).without_annotations())] - #[case("5)", TextValue::Integer(Integer::I64(5)).without_annotations())] - #[case("foo::bar::5 ", TextValue::Integer(Integer::I64(5)).with_annotations(["foo", "bar"]))] + #[case("5 ", TextValue::Int(Int::I64(5)).without_annotations())] + #[case("5)", TextValue::Int(Int::I64(5)).without_annotations())] + #[case("foo::bar::5 ", TextValue::Int(Int::I64(5)).with_annotations(["foo", "bar"]))] // v--- This zero allows the parser to tell that the previous value is complete. #[case("foo::bar 0", TextValue::Symbol(text_token("bar")).with_annotations("foo"))] #[case("bar)", TextValue::Symbol(text_token("bar")).without_annotations())] @@ -310,7 +310,7 @@ mod container_parsing_tests { #[rstest] #[case("++ ", Some(TextValue::Symbol(text_token("++")).without_annotations()))] #[case("foo::++ ", Some(TextValue::Symbol(text_token("++")).with_annotations("foo")))] - #[case("5 ", Some(TextValue::Integer(Integer::I64(5)).without_annotations()))] + #[case("5 ", Some(TextValue::Int(Int::I64(5)).without_annotations()))] #[case(")", None)] #[case(" )", None)] #[case(" /*comment*/ )", None)] @@ -322,9 +322,9 @@ mod container_parsing_tests { } #[rstest] - #[case("5,", TextValue::Integer(Integer::I64(5)).without_annotations())] - #[case("5 ,", TextValue::Integer(Integer::I64(5)).without_annotations())] - #[case("foo::bar::5,", TextValue::Integer(Integer::I64(5)).with_annotations(["foo", "bar"]))] + #[case("5,", TextValue::Int(Int::I64(5)).without_annotations())] + #[case("5 ,", TextValue::Int(Int::I64(5)).without_annotations())] + #[case("foo::bar::5,", TextValue::Int(Int::I64(5)).with_annotations(["foo", "bar"]))] #[case("foo::bar,", TextValue::Symbol(text_token("bar")).with_annotations("foo"))] #[case("bar}", TextValue::Symbol(text_token("bar")).without_annotations())] #[case("7.}", TextValue::Decimal(Decimal::new(7, 0)).without_annotations())] diff --git a/src/text/parsers/decimal.rs b/src/text/parsers/decimal.rs index cfc31df2..5afec400 100644 --- a/src/text/parsers/decimal.rs +++ b/src/text/parsers/decimal.rs @@ -15,7 +15,7 @@ use crate::text::parsers::stop_character; use crate::text::text_value::TextValue; use crate::types::coefficient::{Coefficient, Sign}; use crate::types::decimal::Decimal; -use crate::types::integer::UInteger; +use crate::types::integer::UInt; /// Matches the text representation of a decimal value and returns the resulting [Decimal] /// as a [TextValue::Decimal]. @@ -88,16 +88,16 @@ fn decimal_from_text_components<'a>( // Ion's parsing rules should only let through strings of digits and underscores. Since // we've just removed the underscores above, the `from_str` methods below should always // succeed. - let magnitude: UInteger = if magnitude_text.len() < MAX_U64_DIGITS { + let magnitude: UInt = if magnitude_text.len() < MAX_U64_DIGITS { let value = u64::from_str(&magnitude_text) .or_fatal_parse_error(input, "parsing coefficient magnitude as u64 failed")? .1; - UInteger::U64(value) + UInt::U64(value) } else { let value = BigUint::from_str(&magnitude_text) .or_fatal_parse_error(input, "parsing coefficient magnitude as u64 failed")? .1; - UInteger::BigUInt(value) + UInt::BigUInt(value) }; let coefficient = Coefficient::new(sign, magnitude); diff --git a/src/text/parsers/integer.rs b/src/text/parsers/integer.rs index 23e83da1..c7a03e2b 100644 --- a/src/text/parsers/integer.rs +++ b/src/text/parsers/integer.rs @@ -4,7 +4,7 @@ use crate::text::parse_result::{ use crate::text::parsers::numeric_support::base_10_integer_digits; use crate::text::parsers::stop_character; use crate::text::text_value::TextValue; -use crate::types::integer::Integer; +use crate::types::integer::Int; use nom::branch::alt; use nom::bytes::streaming::{is_a, tag, take_while1}; use nom::character::streaming::char; @@ -21,7 +21,7 @@ use std::num::IntErrorKind; // decimal, the base-10 notation, or the fractional delimiter of a floating-point number. /// Matches the text representation of an integer in any supported notation (base-2, base-10, or -/// base-16) and returns the resulting [i64] as a [TextValue::Integer]. +/// base-16) and returns the resulting [i64] as a [TextValue::Int]. pub(crate) fn parse_integer(input: &str) -> IonParseResult { terminated( alt((base_16_integer, base_2_integer, base_10_integer)), @@ -30,7 +30,7 @@ pub(crate) fn parse_integer(input: &str) -> IonParseResult { } /// Matches a base-16 notation integer (e.g. `0xCAFE`, `0Xcafe`, or `-0xCa_Fe`) and returns the -/// resulting [i64] as a [TextValue::Integer]. +/// resulting [i64] as a [TextValue::Int]. fn base_16_integer(input: &str) -> IonParseResult { let (remaining, (maybe_sign, text_digits)) = separated_pair( opt(char('-')), @@ -39,7 +39,7 @@ fn base_16_integer(input: &str) -> IonParseResult { )(input)?; let integer = parse_integer_with_radix(text_digits, 16) .map(|(_, i)| if maybe_sign.is_some() { -i } else { i }) - .map(TextValue::Integer) + .map(TextValue::Int) .or_fatal_parse_error(input, "could not parse hex integer")? .1; Ok((remaining, integer)) @@ -62,7 +62,7 @@ fn take_base_16_digits1(input: &str) -> IonParseResult<&str> { } /// Matches a base-2 notation integer (e.g. `0b0`, `0B1`, or `-0b10_10`) and returns the resulting -/// [i64] as a [TextValue::Integer]. +/// [i64] as a [TextValue::Int]. fn base_2_integer(input: &str) -> IonParseResult { let (remaining, (maybe_sign, text_digits)) = separated_pair( opt(char('-')), @@ -71,7 +71,7 @@ fn base_2_integer(input: &str) -> IonParseResult { )(input)?; let integer = parse_integer_with_radix(text_digits, 2) .map(|(_, i)| if maybe_sign.is_some() { -i } else { i }) - .map(TextValue::Integer) + .map(TextValue::Int) .or_fatal_parse_error(input, "could not parse binary integer")? .1; Ok((remaining, integer)) @@ -89,11 +89,11 @@ fn base_2_integer_digits(input: &str) -> IonParseResult<&str> { } /// Matches a base-10 notation integer (e.g. `0`, `255`, or `-1_024`) and returns the resulting -/// [i64] as a [TextValue::Integer]. +/// [i64] as a [TextValue::Int]. fn base_10_integer(input: &str) -> IonParseResult { let (remaining, int_text) = recognize(preceded(opt(char('-')), base_10_integer_digits))(input)?; let integer = parse_integer_with_radix(int_text, 10) - .map(|(_, i)| TextValue::Integer(i)) + .map(|(_, i)| TextValue::Int(i)) .or_fatal_parse_error(input, "could not parse decimal integer")? .1; Ok((remaining, integer)) @@ -101,7 +101,7 @@ fn base_10_integer(input: &str) -> IonParseResult { /// Strips any underscores out of the provided text and then parses it according to the specified /// radix. -fn parse_integer_with_radix(text: &str, radix: u32) -> IonParseResult { +fn parse_integer_with_radix(text: &str, radix: u32) -> IonParseResult { if text.contains('_') { let sanitized = text.replace('_', ""); // Construct a new IonParseResult with a lifetime tied to `text`, not `sanitized` @@ -116,17 +116,17 @@ fn parse_integer_with_radix(text: &str, radix: u32) -> IonParseResult { } /// Parses the provided text according to the specified radix. -fn parse_sanitized_text_with_radix(text: &str, radix: u32) -> IonParseResult { +fn parse_sanitized_text_with_radix(text: &str, radix: u32) -> IonParseResult { // Try to parse it as an i64... match i64::from_str_radix(text, radix) { - Ok(integer) => Ok(("", Integer::I64(integer))), + Ok(integer) => Ok(("", Int::I64(integer))), Err(e) if e.kind() == &IntErrorKind::NegOverflow || e.kind() == &IntErrorKind::PosOverflow => { // The text is ok, but the magnitude of the integer it represents is too large to // represent using an i64. Try again with BigInt. BigInt::from_str_radix(text, radix) - .map(Integer::BigInt) + .map(Int::BigInt) .or_fatal_parse_error(text, "found big integer with invalid text") } Err(e) => { @@ -145,11 +145,7 @@ mod integer_parsing_tests { use crate::text::text_value::TextValue; fn parse_equals_i64(text: &str, expected: i64) { - parse_test_ok( - parse_integer, - text, - TextValue::Integer(Integer::I64(expected)), - ) + parse_test_ok(parse_integer, text, TextValue::Int(Int::I64(expected))) } fn parse_fails(text: &str) { diff --git a/src/text/parsers/null.rs b/src/text/parsers/null.rs index a57fc03e..53c03429 100644 --- a/src/text/parsers/null.rs +++ b/src/text/parsers/null.rs @@ -34,7 +34,7 @@ fn ion_type_from_text(text: &str) -> Option { let ion_type = match text { "null" => Null, "bool" => Bool, - "int" => Integer, + "int" => Int, "float" => Float, "decimal" => Decimal, "timestamp" => Timestamp, @@ -71,7 +71,7 @@ mod null_parsing_tests { parse_equals("null ", Null); parse_equals("null.null ", Null); parse_equals("null.bool ", Bool); - parse_equals("null.int ", Integer); + parse_equals("null.int ", Int); parse_equals("null.float ", Float); parse_equals("null.decimal ", Decimal); parse_equals("null.timestamp ", Timestamp); diff --git a/src/text/parsers/top_level.rs b/src/text/parsers/top_level.rs index d0066457..76596c55 100644 --- a/src/text/parsers/top_level.rs +++ b/src/text/parsers/top_level.rs @@ -90,7 +90,7 @@ mod parse_top_level_values_tests { use crate::text::parsers::unit_test_support::{parse_test_err, parse_test_ok, parse_unwrap}; use crate::text::parsers::value::value; use crate::text::text_value::TextValue; - use crate::types::integer::Integer; + use crate::types::integer::Int; use crate::IonType; use super::*; @@ -112,8 +112,8 @@ mod parse_top_level_values_tests { expect_type("null.list ", IonType::List); expect_type("true ", IonType::Bool); expect_type("false ", IonType::Bool); - expect_type("5 ", IonType::Integer); - expect_type("-5 ", IonType::Integer); + expect_type("5 ", IonType::Int); + expect_type("-5 ", IonType::Int); expect_type("5.0 ", IonType::Decimal); expect_type("-5.0 ", IonType::Decimal); expect_type("5.0d0 ", IonType::Decimal); @@ -145,9 +145,9 @@ mod parse_top_level_values_tests { // Here, 'END' is simply an unrelated symbol value that the parser knows to ignore. #[case("foo::bar::baz END", &["foo", "bar"], TextValue::Symbol(text_token("baz")))] #[case("foo::bar::baz END", &["foo", "bar"], TextValue::Symbol(text_token("baz")))] - #[case("foo::'bar'::7 END", &["foo", "bar"], TextValue::Integer(Integer::I64(7)))] + #[case("foo::'bar'::7 END", &["foo", "bar"], TextValue::Int(Int::I64(7)))] #[case("'foo'::'bar'::{ END", &["foo", "bar"], TextValue::StructStart)] - #[case("'foo bar'::false END", &["foo bar"], TextValue::Boolean(false))] + #[case("'foo bar'::false END", &["foo bar"], TextValue::Bool(false))] fn test_parse_annotated_value( #[case] text: &str, #[case] expected_annotations: &[&str], diff --git a/src/text/raw_text_reader.rs b/src/text/raw_text_reader.rs index a9a354a0..b1e4a719 100644 --- a/src/text/raw_text_reader.rs +++ b/src/text/raw_text_reader.rs @@ -4,7 +4,7 @@ use crate::raw_symbol_token::RawSymbolToken; use crate::result::IonResult; use crate::stream_reader::IonReader; use crate::types::timestamp::Timestamp; -use crate::{Decimal, Integer, IonError, IonType}; +use crate::{Decimal, Int, IonError, IonType}; use crate::text::non_blocking::raw_text_reader::RawTextReader as NonBlockingReader; @@ -122,8 +122,8 @@ impl IonReader for RawTextReader { self.reader.read_bool() } - fn read_integer(&mut self) -> IonResult { - self.reader.read_integer() + fn read_int(&mut self) -> IonResult { + self.reader.read_int() } fn read_i64(&mut self) -> IonResult { @@ -257,18 +257,18 @@ mod reader_tests { 0 [1, 2, 3] (4 5) 6 "#; let reader = &mut RawTextReader::new(ion_data)?; - next_type(reader, IonType::Integer, false); + next_type(reader, IonType::Int, false); assert_eq!(reader.read_i64()?, 0); next_type(reader, IonType::List, false); reader.step_in()?; - next_type(reader, IonType::Integer, false); + next_type(reader, IonType::Int, false); assert_eq!(reader.read_i64()?, 1); reader.step_out()?; // This should have skipped over the `2, 3` at the end of the list. next_type(reader, IonType::SExp, false); // Don't step into the s-expression. Instead, skip over it. - next_type(reader, IonType::Integer, false); + next_type(reader, IonType::Int, false); assert_eq!(reader.read_i64()?, 6); Ok(()) } @@ -294,16 +294,16 @@ mod reader_tests { reader.step_in()?; next_type(reader, IonType::List, false); reader.step_in()?; - next_type(reader, IonType::Integer, false); + next_type(reader, IonType::Int, false); next_type(reader, IonType::List, false); reader.step_in()?; - next_type(reader, IonType::Integer, false); + next_type(reader, IonType::Int, false); // The reader is now at the '2' nested inside of 'foo' reader.step_out()?; reader.step_out()?; next_type(reader, IonType::Struct, false); reader.step_in()?; - next_type(reader, IonType::Integer, false); + next_type(reader, IonType::Int, false); next_type(reader, IonType::SExp, false); reader.step_in()?; next_type(reader, IonType::Bool, false); @@ -312,7 +312,7 @@ mod reader_tests { reader.step_out()?; reader.step_out()?; reader.step_out()?; - next_type(reader, IonType::Integer, false); + next_type(reader, IonType::Int, false); assert_eq!(reader.read_i64()?, 11); Ok(()) } @@ -333,17 +333,17 @@ mod reader_tests { let reader = &mut RawTextReader::new(ion_data)?; next_type(reader, IonType::Struct, false); reader.step_in()?; - next_type(reader, IonType::Integer, false); + next_type(reader, IonType::Int, false); assert_eq!(reader.field_name()?, text_token("foo")); next_type(reader, IonType::Struct, false); assert_eq!(reader.field_name()?, text_token("bar")); reader.step_in()?; - next_type(reader, IonType::Integer, false); + next_type(reader, IonType::Int, false); assert_eq!(reader.read_i64()?, 5); reader.step_out()?; assert_eq!(reader.next()?, RawStreamItem::Nothing); reader.step_out()?; - next_type(reader, IonType::Integer, false); + next_type(reader, IonType::Int, false); assert_eq!(reader.read_i64()?, 42); Ok(()) } @@ -372,7 +372,7 @@ mod reader_tests { next_type(reader, IonType::Bool, false); assert!(reader.read_bool()?); - next_type(reader, IonType::Integer, false); + next_type(reader, IonType::Int, false); assert_eq!(reader.read_i64()?, 5); next_type(reader, IonType::Float, false); @@ -462,7 +462,7 @@ mod reader_tests { Timestamp::with_ymd(2014, 6, 26).build()? ); // TODO: Check for 'km' annotation after change to OwnedSymbolToken - next_type(reader, IonType::Integer, false); + next_type(reader, IonType::Int, false); assert_eq!(reader.read_i64()?, 36); Ok(()) } @@ -492,7 +492,7 @@ mod reader_tests { assert!(reader.read_bool()?); annotations_eq(reader, ["venus", "earth"]); - next_type(reader, IonType::Integer, false); + next_type(reader, IonType::Int, false); assert_eq!(reader.read_i64()?, 5); annotations_eq(reader, &[local_sid_token(17), text_token("mars")]); @@ -535,13 +535,13 @@ mod reader_tests { // Reading a list: pluto::[1, $77::2, 3] next_type(reader, IonType::List, false); reader.step_in()?; - next_type(reader, IonType::Integer, false); + next_type(reader, IonType::Int, false); assert_eq!(reader.number_of_annotations(), 0); assert_eq!(reader.read_i64()?, 1); - next_type(reader, IonType::Integer, false); + next_type(reader, IonType::Int, false); annotations_eq(reader, [77]); assert_eq!(reader.read_i64()?, 2); - next_type(reader, IonType::Integer, false); + next_type(reader, IonType::Int, false); assert_eq!(reader.number_of_annotations(), 0); assert_eq!(reader.read_i64()?, 3); assert_eq!(reader.next()?, Nothing); @@ -584,10 +584,10 @@ mod reader_tests { assert_eq!(reader.next()?, RawStreamItem::Value(IonType::Struct)); reader.step_in()?; - assert_eq!(reader.next()?, RawStreamItem::Value(IonType::Integer)); + assert_eq!(reader.next()?, RawStreamItem::Value(IonType::Int)); assert_eq!(reader.field_name()?, RawSymbolToken::Text("a".to_string())); assert_eq!(reader.read_i64()?, 1); - assert_eq!(reader.next()?, RawStreamItem::Value(IonType::Integer)); + assert_eq!(reader.next()?, RawStreamItem::Value(IonType::Int)); assert_eq!(reader.field_name()?, RawSymbolToken::Text("b".to_string())); assert_eq!(reader.read_i64()?, 2); reader.step_out()?; diff --git a/src/text/raw_text_writer.rs b/src/text/raw_text_writer.rs index ec4e1f9d..59b56890 100644 --- a/src/text/raw_text_writer.rs +++ b/src/text/raw_text_writer.rs @@ -10,7 +10,7 @@ use crate::types::decimal::Decimal; use crate::types::timestamp::Timestamp; use crate::types::ContainerType; use crate::writer::IonWriter; -use crate::{Integer, IonType}; +use crate::{Int, IonType}; pub struct RawTextWriterBuilder { whitespace_config: WhitespaceConfig, @@ -493,7 +493,7 @@ impl IonWriter for RawTextWriter { let null_text = match ion_type { Null => "null", Bool => "null.bool", - Integer => "null.int", + Int => "null.int", Float => "null.float", Decimal => "null.decimal", Timestamp => "null.timestamp", @@ -531,7 +531,7 @@ impl IonWriter for RawTextWriter { } /// Writes an Ion `integer` with the specified value to the output stream. - fn write_integer(&mut self, value: &Integer) -> IonResult<()> { + fn write_int(&mut self, value: &Int) -> IonResult<()> { self.write_scalar(|output| { write!(output, "{value}")?; Ok(()) diff --git a/src/text/text_formatter.rs b/src/text/text_formatter.rs index 72d70743..d725da67 100644 --- a/src/text/text_formatter.rs +++ b/src/text/text_formatter.rs @@ -1,6 +1,6 @@ use crate::element::owned::{IonSequence, List, SExp, Struct}; use crate::raw_symbol_token_ref::AsRawSymbolTokenRef; -use crate::{Decimal, Integer, IonResult, IonType, RawSymbolTokenRef, Symbol, Timestamp}; +use crate::{Decimal, Int, IonResult, IonType, RawSymbolTokenRef, Symbol, Timestamp}; pub const STRING_ESCAPE_CODES: &[&str] = &string_escape_code_init(); @@ -296,7 +296,7 @@ impl<'a, W: std::fmt::Write> IonValueFormatter<'a, W> { let null_text = match ion_type { Null => "null", Bool => "null.bool", - Integer => "null.int", + Int => "null.int", Float => "null.float", Decimal => "null.decimal", Timestamp => "null.timestamp", @@ -321,7 +321,7 @@ impl<'a, W: std::fmt::Write> IonValueFormatter<'a, W> { Ok(()) } - pub fn format_integer(&mut self, value: &Integer) -> IonResult<()> { + pub fn format_integer(&mut self, value: &Int) -> IonResult<()> { write!(self.output, "{value}")?; Ok(()) } @@ -449,7 +449,7 @@ impl<'a, W: std::fmt::Write> IonValueFormatter<'a, W> { #[cfg(test)] mod formatter_test { use crate::text::text_formatter::IonValueFormatter; - use crate::{ion_list, ion_sexp, ion_struct, Integer, IonResult, IonType, Timestamp}; + use crate::{ion_list, ion_sexp, ion_struct, Int, IonResult, IonType, Timestamp}; use num_bigint::BigInt; fn formatter(mut f: F, expected: &str) @@ -481,19 +481,16 @@ mod formatter_test { #[test] fn test_format_i64() -> IonResult<()> { - formatter(|ivf| ivf.format_integer(&Integer::I64(4)), "4"); - formatter(|ivf| ivf.format_integer(&Integer::I64(-4)), "-4"); + formatter(|ivf| ivf.format_integer(&Int::I64(4)), "4"); + formatter(|ivf| ivf.format_integer(&Int::I64(-4)), "-4"); Ok(()) } #[test] fn test_format_big_int() -> IonResult<()> { + formatter(|ivf| ivf.format_integer(&Int::BigInt(BigInt::from(4))), "4"); formatter( - |ivf| ivf.format_integer(&Integer::BigInt(BigInt::from(4))), - "4", - ); - formatter( - |ivf| ivf.format_integer(&Integer::BigInt(BigInt::from(-4))), + |ivf| ivf.format_integer(&Int::BigInt(BigInt::from(-4))), "-4", ); Ok(()) diff --git a/src/text/text_value.rs b/src/text/text_value.rs index c3f31d10..eb29e657 100644 --- a/src/text/text_value.rs +++ b/src/text/text_value.rs @@ -1,6 +1,6 @@ use crate::raw_symbol_token::RawSymbolToken; use crate::types::decimal::Decimal; -use crate::types::integer::Integer; +use crate::types::integer::Int; use crate::types::timestamp::Timestamp; use crate::IonType; @@ -46,8 +46,8 @@ impl PartialEq for AnnotatedTextValue { #[derive(Debug, Clone, PartialEq)] pub(crate) enum TextValue { Null(IonType), - Boolean(bool), - Integer(Integer), + Bool(bool), + Int(Int), Float(f64), Decimal(Decimal), Timestamp(Timestamp), @@ -58,7 +58,7 @@ pub(crate) enum TextValue { Blob(Vec), Clob(Vec), ListStart, - SExpressionStart, + SExpStart, StructStart, } @@ -67,8 +67,8 @@ impl TextValue { pub fn ion_type(&self) -> IonType { match self { TextValue::Null(ion_type) => *ion_type, - TextValue::Boolean(_) => IonType::Bool, - TextValue::Integer(_) => IonType::Integer, + TextValue::Bool(_) => IonType::Bool, + TextValue::Int(_) => IonType::Int, TextValue::Float(_) => IonType::Float, TextValue::Decimal(_) => IonType::Decimal, TextValue::Timestamp(_) => IonType::Timestamp, @@ -77,7 +77,7 @@ impl TextValue { TextValue::Blob(_) => IonType::Blob, TextValue::Clob(_) => IonType::Clob, TextValue::ListStart => IonType::List, - TextValue::SExpressionStart => IonType::SExp, + TextValue::SExpStart => IonType::SExp, TextValue::StructStart => IonType::Struct, } } diff --git a/src/text/text_writer.rs b/src/text/text_writer.rs index 33357d92..2355b8c8 100644 --- a/src/text/text_writer.rs +++ b/src/text/text_writer.rs @@ -5,7 +5,7 @@ use crate::text::raw_text_writer::RawTextWriter; use crate::types::decimal::Decimal; use crate::types::timestamp::Timestamp; use crate::writer::IonWriter; -use crate::{Integer, IonType, RawTextWriterBuilder, SymbolTable}; +use crate::{Int, IonType, RawTextWriterBuilder, SymbolTable}; use delegate::delegate; use std::io::Write; @@ -171,7 +171,7 @@ impl IonWriter for TextWriter { fn write_null(&mut self, ion_type: IonType) -> IonResult<()>; fn write_bool(&mut self, value: bool) -> IonResult<()>; fn write_i64(&mut self, value: i64) -> IonResult<()>; - fn write_integer(&mut self, value: &Integer) -> IonResult<()>; + fn write_int(&mut self, value: &Int) -> IonResult<()>; fn write_f32(&mut self, value: f32) -> IonResult<()>; fn write_f64(&mut self, value: f64) -> IonResult<()>; fn write_decimal(&mut self, value: &Decimal) -> IonResult<()>; diff --git a/src/types/coefficient.rs b/src/types/coefficient.rs index 04d9b0ea..089fa3f2 100644 --- a/src/types/coefficient.rs +++ b/src/types/coefficient.rs @@ -2,7 +2,7 @@ use num_bigint::{BigInt, BigUint}; use num_traits::Zero; use crate::result::{illegal_operation, IonError}; -use crate::types::integer::UInteger; +use crate::types::integer::UInt; use std::convert::TryFrom; use std::fmt::{Display, Formatter}; use std::ops::{MulAssign, Neg}; @@ -22,11 +22,11 @@ pub enum Sign { #[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq)] pub struct Coefficient { pub(crate) sign: Sign, - pub(crate) magnitude: UInteger, + pub(crate) magnitude: UInt, } impl Coefficient { - pub(crate) fn new>(sign: Sign, magnitude: I) -> Self { + pub(crate) fn new>(sign: Sign, magnitude: I) -> Self { let magnitude = magnitude.into(); Coefficient { sign, magnitude } } @@ -35,7 +35,7 @@ impl Coefficient { self.sign } - pub(crate) fn magnitude(&self) -> &UInteger { + pub(crate) fn magnitude(&self) -> &UInt { &self.magnitude } @@ -48,15 +48,15 @@ impl Coefficient { pub(crate) fn negative_zero() -> Self { Coefficient { sign: Sign::Negative, - magnitude: UInteger::U64(0), + magnitude: UInt::U64(0), } } /// Returns true if the Coefficient represents positive zero. pub(crate) fn is_negative_zero(&self) -> bool { match (self.sign, &self.magnitude) { - (Sign::Negative, UInteger::U64(0)) => true, - (Sign::Negative, UInteger::BigUInt(b)) if b.is_zero() => true, + (Sign::Negative, UInt::U64(0)) => true, + (Sign::Negative, UInt::BigUInt(b)) if b.is_zero() => true, _ => false, } } @@ -64,8 +64,8 @@ impl Coefficient { /// Returns true if the Coefficient represents positive zero. pub(crate) fn is_positive_zero(&self) -> bool { match (self.sign, &self.magnitude) { - (Sign::Positive, UInteger::U64(0)) => true, - (Sign::Positive, UInteger::BigUInt(b)) if b.is_zero() => true, + (Sign::Positive, UInt::U64(0)) => true, + (Sign::Positive, UInt::BigUInt(b)) if b.is_zero() => true, _ => false, } } @@ -73,8 +73,8 @@ impl Coefficient { /// Returns true if the Coefficient represents a zero of any sign. pub(crate) fn is_zero(&self) -> bool { match (self.sign, &self.magnitude) { - (_, UInteger::U64(0)) => true, - (_, UInteger::BigUInt(b)) if b.is_zero() => true, + (_, UInt::U64(0)) => true, + (_, UInt::BigUInt(b)) if b.is_zero() => true, _ => false, } } @@ -83,14 +83,14 @@ impl Coefficient { /// inline representations. pub(crate) fn as_i64(&self) -> Option { match self.magnitude { - UInteger::U64(unsigned) => match i64::try_from(unsigned) { + UInt::U64(unsigned) => match i64::try_from(unsigned) { Ok(signed) => match self.sign { Sign::Negative => Some(signed.neg()), // cannot overflow (never `MIN`) Sign::Positive => Some(signed), }, Err(_) => None, }, - UInteger::BigUInt(_) => None, + UInt::BigUInt(_) => None, } } } @@ -131,8 +131,8 @@ impl TryFrom for BigInt { illegal_operation("Cannot convert negative zero Decimal to BigDecimal")?; } let mut big_int: BigInt = match value.magnitude { - UInteger::U64(m) => m.into(), - UInteger::BigUInt(m) => m.into(), + UInt::U64(m) => m.into(), + UInt::BigUInt(m) => m.into(), }; if value.sign == Sign::Negative { big_int.mul_assign(-1); @@ -148,8 +148,8 @@ impl Display for Coefficient { Sign::Negative => write!(f, "-")?, }; match &self.magnitude { - UInteger::U64(m) => write!(f, "{}", *m), - UInteger::BigUInt(m) => write!(f, "{m}"), + UInt::U64(m) => write!(f, "{}", *m), + UInt::BigUInt(m) => write!(f, "{m}"), } } } diff --git a/src/types/decimal.rs b/src/types/decimal.rs index 1afa795b..f5981173 100644 --- a/src/types/decimal.rs +++ b/src/types/decimal.rs @@ -6,7 +6,7 @@ use num_bigint::{BigInt, BigUint, ToBigUint}; use crate::ion_eq::IonEq; use crate::result::{illegal_operation, IonError}; use crate::types::coefficient::{Coefficient, Sign}; -use crate::types::integer::UInteger; +use crate::types::integer::UInt; use num_traits::Zero; use std::convert::{TryFrom, TryInto}; use std::fmt::{Display, Formatter}; @@ -67,8 +67,8 @@ impl Decimal { /// Returns `true` if this Decimal is a zero of any sign or exponent. pub fn is_zero(&self) -> bool { match self.coefficient.magnitude() { - UInteger::U64(0) => true, - UInteger::BigUInt(m) => m.is_zero(), + UInt::U64(0) => true, + UInt::BigUInt(m) => m.is_zero(), _ => false, } } @@ -77,8 +77,8 @@ impl Decimal { /// zero. Otherwise, returns false. (Negative zero returns false.) pub fn is_less_than_zero(&self) -> bool { match (self.coefficient.sign(), self.coefficient.magnitude()) { - (Sign::Negative, UInteger::U64(m)) if *m > 0 => true, - (Sign::Negative, UInteger::BigUInt(m)) if m > &BigUint::zero() => true, + (Sign::Negative, UInt::U64(m)) if *m > 0 => true, + (Sign::Negative, UInt::BigUInt(m)) if m > &BigUint::zero() => true, _ => false, } } @@ -88,8 +88,8 @@ impl Decimal { // If the coefficient has a magnitude of zero, the Decimal is a zero of some precision // and so is not >= 1. match &self.coefficient.magnitude { - UInteger::U64(magnitude) if magnitude.is_zero() => return false, - UInteger::BigUInt(magnitude) if magnitude.is_zero() => return false, + UInt::U64(magnitude) if magnitude.is_zero() => return false, + UInt::BigUInt(magnitude) if magnitude.is_zero() => return false, _ => {} } @@ -166,7 +166,7 @@ impl Decimal { // This lets us compare 80 and 80, determining that the decimals are equal. let mut scaled_coefficient: BigUint = d1.coefficient.magnitude().to_biguint().unwrap(); scaled_coefficient *= BigUint::from(10u64).pow(exponent_delta as u32); - UInteger::BigUInt(scaled_coefficient).cmp(d2.coefficient.magnitude()) + UInt::BigUInt(scaled_coefficient).cmp(d2.coefficient.magnitude()) } } diff --git a/src/types/integer.rs b/src/types/integer.rs index f9cd83bf..eeb85c20 100644 --- a/src/types/integer.rs +++ b/src/types/integer.rs @@ -6,7 +6,7 @@ use std::cmp::Ordering; use std::fmt::{Display, Formatter}; use std::ops::{Add, Neg}; -/// Provides convenient integer accessors for integer values that are like [`Integer`] +/// Provides convenient integer accessors for integer values that are like [`Int`] pub trait IntAccess { /// Returns the value as an `i64` if it can be represented as such. /// @@ -16,8 +16,8 @@ pub trait IntAccess { /// # use ion_rs::element::owned::*; /// # use ion_rs::types::integer::*; /// # use num_bigint::*; - /// let big_int = Integer::BigInt(BigInt::from(100)); - /// let i64_int = Integer::I64(100); + /// let big_int = Int::BigInt(BigInt::from(100)); + /// let i64_int = Int::I64(100); /// assert_eq!(big_int.as_i64(), i64_int.as_i64()); /// /// // works on element too @@ -40,9 +40,9 @@ pub trait IntAccess { /// # use ion_rs::types::integer::*; /// # use num_bigint::*; /// # use std::str::FromStr; - /// let big_int = Integer::BigInt(BigInt::from(100)); + /// let big_int = Int::BigInt(BigInt::from(100)); /// assert_eq!(BigInt::from_str("100").unwrap(), *big_int.as_big_int().unwrap()); - /// let i64_int = Integer::I64(100); + /// let i64_int = Int::I64(100); /// assert_eq!(None, i64_int.as_big_int()); /// /// // works on element too @@ -57,17 +57,17 @@ pub trait IntAccess { /// Represents a UInt of any size. Used for reading binary integers and symbol Ids. /// Used to represent the unsigned magnitude of Decimal values and fractional seconds. #[derive(Debug, Clone)] -pub enum UInteger { +pub enum UInt { U64(u64), BigUInt(BigUint), } -impl UInteger { +impl UInt { /// Compares a [u64] integer with a [BigUint] to see if they are equal. This method never /// allocates. It will always prefer to downgrade a BigUint and compare the two integers as /// u64 values. If this is not possible, then the two numbers cannot be equal anyway. fn cross_representation_eq(m1: u64, m2: &BigUint) -> bool { - UInteger::cross_representation_cmp(m1, m2) == Ordering::Equal + UInt::cross_representation_cmp(m1, m2) == Ordering::Equal } /// Compares a [u64] integer with a [BigUint]. This method never allocates. It will always @@ -86,10 +86,8 @@ impl UInteger { /// Returns the number of digits in the base-10 representation of the UInteger. pub(crate) fn number_of_decimal_digits(&self) -> u64 { match self { - UInteger::U64(u64_value) => super::num_decimal_digits_in_u64(*u64_value), - UInteger::BigUInt(big_uint_value) => { - UInteger::calculate_big_uint_digits(big_uint_value) - } + UInt::U64(u64_value) => super::num_decimal_digits_in_u64(*u64_value), + UInt::BigUInt(big_uint_value) => UInt::calculate_big_uint_digits(big_uint_value), } } @@ -108,69 +106,69 @@ impl UInteger { } } -impl PartialEq for UInteger { +impl PartialEq for UInt { fn eq(&self, other: &Self) -> bool { - use UInteger::*; + use UInt::*; match (self, other) { (U64(m1), U64(m2)) => m1 == m2, (BigUInt(m1), BigUInt(m2)) => m1 == m2, - (U64(m1), BigUInt(m2)) => UInteger::cross_representation_eq(*m1, m2), - (BigUInt(m1), U64(m2)) => UInteger::cross_representation_eq(*m2, m1), + (U64(m1), BigUInt(m2)) => UInt::cross_representation_eq(*m1, m2), + (BigUInt(m1), U64(m2)) => UInt::cross_representation_eq(*m2, m1), } } } -impl Eq for UInteger {} +impl Eq for UInt {} -impl PartialOrd for UInteger { +impl PartialOrd for UInt { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } -impl Ord for UInteger { +impl Ord for UInt { fn cmp(&self, other: &Self) -> Ordering { - use UInteger::*; + use UInt::*; match (self, other) { (U64(m1), U64(m2)) => m1.cmp(m2), (BigUInt(m1), BigUInt(m2)) => m1.cmp(m2), - (U64(m1), BigUInt(m2)) => UInteger::cross_representation_cmp(*m1, m2), - (BigUInt(m1), U64(m2)) => UInteger::cross_representation_cmp(*m2, m1).reverse(), + (U64(m1), BigUInt(m2)) => UInt::cross_representation_cmp(*m1, m2), + (BigUInt(m1), U64(m2)) => UInt::cross_representation_cmp(*m2, m1).reverse(), } } } -impl From for Integer { - fn from(value: UInteger) -> Self { +impl From for Int { + fn from(value: UInt) -> Self { match value { - UInteger::U64(uint) => { + UInt::U64(uint) => { if let Ok(signed) = i64::try_from(uint) { // The u64 was successfully converted to an i64 - Integer::I64(signed) + Int::I64(signed) } else { // The u64 was slightly too big to be represented as an i64; it required the // 64th bit to store the magnitude. Up-convert it to a BigInt. big_integer_from_u64(uint) } } - UInteger::BigUInt(big_uint) => big_integer_from_big_uint(big_uint), + UInt::BigUInt(big_uint) => big_integer_from_big_uint(big_uint), } } } -impl From for UInteger { +impl From for UInt { fn from(value: BigUint) -> Self { // prefer a compact representation for the magnitude match value.to_u64() { - Some(unsigned) => UInteger::U64(unsigned), - None => UInteger::BigUInt(value), + Some(unsigned) => UInt::U64(unsigned), + None => UInt::BigUInt(value), } } } -impl From for BigUint { - fn from(value: UInteger) -> Self { - use UInteger::*; +impl From for BigUint { + fn from(value: UInt) -> Self { + use UInt::*; match value { U64(m) => BigUint::from(m), BigUInt(m) => m, @@ -178,7 +176,7 @@ impl From for BigUint { } } -impl ToBigUint for UInteger { +impl ToBigUint for UInt { fn to_biguint(&self) -> Option { // This implementation never fails, but the trait requires an `Option` return type. Some(self.clone().into()) @@ -188,76 +186,76 @@ impl ToBigUint for UInteger { // This macro makes it possible to turn unsigned int primitives into a UInteger using `.into()`. // Note that it works for both signed and unsigned ints. The resulting UInteger will be the // absolute value of the integer being converted. -macro_rules! impl_uinteger_from_small_unsigned_int_types { +macro_rules! impl_uint_from_small_unsigned_int_types { ($($t:ty),*) => ($( - impl From<$t> for UInteger { - fn from(value: $t) -> UInteger { - UInteger::U64(value as u64) + impl From<$t> for UInt { + fn from(value: $t) -> UInt { + UInt::U64(value as u64) } } )*) } -impl_uinteger_from_small_unsigned_int_types!(u8, u16, u32, u64, usize); +impl_uint_from_small_unsigned_int_types!(u8, u16, u32, u64, usize); -macro_rules! impl_uinteger_from_small_signed_int_types { +macro_rules! impl_uint_from_small_signed_int_types { ($($t:ty),*) => ($( - impl From<$t> for UInteger { - fn from(value: $t) -> UInteger { + impl From<$t> for UInt { + fn from(value: $t) -> UInt { let abs_value = value.unsigned_abs(); - UInteger::U64(abs_value.try_into().unwrap()) + UInt::U64(abs_value.try_into().unwrap()) } } )*) } -impl_uinteger_from_small_signed_int_types!(i8, i16, i32, i64, isize); +impl_uint_from_small_signed_int_types!(i8, i16, i32, i64, isize); -impl From for UInteger { - fn from(value: u128) -> UInteger { - UInteger::BigUInt(BigUint::from(value)) +impl From for UInt { + fn from(value: u128) -> UInt { + UInt::BigUInt(BigUint::from(value)) } } -impl From for UInteger { - fn from(value: i128) -> UInteger { - UInteger::BigUInt(value.abs().to_biguint().unwrap()) +impl From for UInt { + fn from(value: i128) -> UInt { + UInt::BigUInt(value.abs().to_biguint().unwrap()) } } -impl From for UInteger { - fn from(value: Integer) -> Self { +impl From for UInt { + fn from(value: Int) -> Self { match value { - Integer::I64(i) => i.into(), + Int::I64(i) => i.into(), // num_bigint::BigInt's `into_parts` consumes the BigInt and returns a // (sign: Sign, magnitude: BigUint) tuple. We only care about the magnitude, so we // extract it here with `.1` ---------------v and then convert the BigUint to a UInteger - Integer::BigInt(i) => i.into_parts().1.into(), // <-- using `.into()` + Int::BigInt(i) => i.into_parts().1.into(), // <-- using `.into()` } } } #[inline(never)] -fn big_integer_from_u64(value: u64) -> Integer { - Integer::BigInt(BigInt::from(value)) +fn big_integer_from_u64(value: u64) -> Int { + Int::BigInt(BigInt::from(value)) } #[inline(never)] -fn big_integer_from_big_uint(value: BigUint) -> Integer { - Integer::BigInt(BigInt::from(value)) +fn big_integer_from_big_uint(value: BigUint) -> Int { + Int::BigInt(BigInt::from(value)) } -impl TryFrom<&UInteger> for i64 { +impl TryFrom<&UInt> for i64 { type Error = IonError; - fn try_from(value: &UInteger) -> Result { + fn try_from(value: &UInt) -> Result { match value { - UInteger::U64(uint) => i64::try_from(*uint).or_else(|_| { + UInt::U64(uint) => i64::try_from(*uint).or_else(|_| { decoding_error(format!( "Unsigned integer {uint:?} was too large to be represented as an i64." )) }), - UInteger::BigUInt(big_uint) => i64::try_from(big_uint).or_else(|_| { + UInt::BigUInt(big_uint) => i64::try_from(big_uint).or_else(|_| { decoding_error(format!( "Unsigned integer {big_uint:?} was too large to be represented as an i64." )) @@ -266,17 +264,17 @@ impl TryFrom<&UInteger> for i64 { } } -impl TryFrom<&UInteger> for usize { +impl TryFrom<&UInt> for usize { type Error = IonError; - fn try_from(value: &UInteger) -> Result { + fn try_from(value: &UInt) -> Result { match value { - UInteger::U64(uint) => usize::try_from(*uint).or_else(|_| { + UInt::U64(uint) => usize::try_from(*uint).or_else(|_| { decoding_error(format!( "Unsigned integer {uint:?} was too large to be represented as an usize." )) }), - UInteger::BigUInt(big_uint) => usize::try_from(big_uint).or_else(|_| { + UInt::BigUInt(big_uint) => usize::try_from(big_uint).or_else(|_| { decoding_error(format!( "Unsigned integer {big_uint:?} was too large to be represented as an usize." )) @@ -290,17 +288,17 @@ impl TryFrom<&UInteger> for usize { /// /// See [`IntAccess`] for common operations. #[derive(Debug, Clone)] -pub enum Integer { +pub enum Int { I64(i64), BigInt(BigInt), } -impl Integer { +impl Int { /// Compares a [i64] integer with a [BigInt] to see if they are equal. This method never /// allocates. It will always prefer to downgrade a BigUint and compare the two integers as /// u64 values. If this is not possible, then the two numbers cannot be equal anyway. fn cross_representation_eq(m1: i64, m2: &BigInt) -> bool { - Integer::cross_representation_cmp(m1, m2) == Ordering::Equal + Int::cross_representation_cmp(m1, m2) == Ordering::Equal } /// Compares a [i64] integer with a [BigInt]. This method never allocates. It will always @@ -317,43 +315,43 @@ impl Integer { } } -impl IntAccess for Integer { +impl IntAccess for Int { #[inline] fn as_i64(&self) -> Option { match &self { - Integer::I64(i) => Some(*i), - Integer::BigInt(big) => big.to_i64(), + Int::I64(i) => Some(*i), + Int::BigInt(big) => big.to_i64(), } } #[inline] fn as_big_int(&self) -> Option<&BigInt> { match &self { - Integer::I64(_) => None, - Integer::BigInt(big) => Some(big), + Int::I64(_) => None, + Int::BigInt(big) => Some(big), } } } -impl PartialEq for Integer { +impl PartialEq for Int { fn eq(&self, other: &Self) -> bool { - use Integer::*; + use Int::*; match (self, other) { (I64(m1), I64(m2)) => m1 == m2, (BigInt(m1), BigInt(m2)) => m1 == m2, - (I64(m1), BigInt(m2)) => Integer::cross_representation_eq(*m1, m2), - (BigInt(m1), I64(m2)) => Integer::cross_representation_eq(*m2, m1), + (I64(m1), BigInt(m2)) => Int::cross_representation_eq(*m1, m2), + (BigInt(m1), I64(m2)) => Int::cross_representation_eq(*m2, m1), } } } -impl Eq for Integer {} +impl Eq for Int {} -impl Neg for Integer { +impl Neg for Int { type Output = Self; fn neg(self) -> Self::Output { - use Integer::*; + use Int::*; match self { I64(value) => I64(-value), BigInt(value) => BigInt(-value), @@ -361,30 +359,30 @@ impl Neg for Integer { } } -impl PartialOrd for Integer { +impl PartialOrd for Int { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } -impl Ord for Integer { +impl Ord for Int { fn cmp(&self, other: &Self) -> Ordering { - use Integer::*; + use Int::*; match (self, other) { (I64(m1), I64(m2)) => m1.cmp(m2), (BigInt(m1), BigInt(m2)) => m1.cmp(m2), - (I64(m1), BigInt(m2)) => Integer::cross_representation_cmp(*m1, m2), - (BigInt(m1), I64(m2)) => Integer::cross_representation_cmp(*m2, m1).reverse(), + (I64(m1), BigInt(m2)) => Int::cross_representation_cmp(*m1, m2), + (BigInt(m1), I64(m2)) => Int::cross_representation_cmp(*m2, m1).reverse(), } } } -impl Add for Integer { - type Output = Integer; +impl Add for Int { + type Output = Int; fn add(self, rhs: Self) -> Self::Output { // The alias 'Big' differentiates the enum variant from the wrapped 'BigInt' type - use Integer::{BigInt as Big, I64}; + use Int::{BigInt as Big, I64}; match (self, rhs) { (I64(this), I64(that)) => { // Try to add the i64s together; if they overflow, upconvert to BigInts @@ -400,91 +398,91 @@ impl Add for Integer { } } -impl Zero for Integer { +impl Zero for Int { fn zero() -> Self { - Integer::I64(0) + Int::I64(0) } fn is_zero(&self) -> bool { match self { - Integer::I64(value) => *value == 0i64, - Integer::BigInt(value) => value.is_zero(), + Int::I64(value) => *value == 0i64, + Int::BigInt(value) => value.is_zero(), } } } -impl Display for UInteger { +impl Display for UInt { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> { match &self { - UInteger::U64(i) => write!(f, "{i}"), - UInteger::BigUInt(i) => write!(f, "{i}"), + UInt::U64(i) => write!(f, "{i}"), + UInt::BigUInt(i) => write!(f, "{i}"), } } } -// Trivial conversion to Integer::I64 from integers that can safely be converted to an i64 -macro_rules! impl_integer_i64_from { +// Trivial conversion to Int::I64 from integers that can safely be converted to an i64 +macro_rules! impl_int_i64_from { ($($t:ty),*) => ($( - impl From<$t> for Integer { - fn from(value: $t) -> Integer { + impl From<$t> for Int { + fn from(value: $t) -> Int { let i64_value = i64::from(value); - Integer::I64(i64_value) + Int::I64(i64_value) } } )*) } -impl_integer_i64_from!(u8, u16, u32, i8, i16, i32, i64); +impl_int_i64_from!(u8, u16, u32, i8, i16, i32, i64); // Conversion to Integer from integer types that may or may not fit in an i64 -macro_rules! impl_integer_from { +macro_rules! impl_int_from { ($($t:ty),*) => ($( - impl From<$t> for Integer { - fn from(value: $t) -> Integer { + impl From<$t> for Int { + fn from(value: $t) -> Int { match i64::try_from(value) { - Ok(i64_value) => Integer::I64(i64_value), - Err(_) => Integer::BigInt(BigInt::from(value)) + Ok(i64_value) => Int::I64(i64_value), + Err(_) => Int::BigInt(BigInt::from(value)) } } } )*) } -impl_integer_from!(isize, usize, u64); +impl_int_from!(isize, usize, u64); -impl From for Integer { +impl From for Int { fn from(value: BigUint) -> Self { let big_int = BigInt::from(value); - Integer::BigInt(big_int) + Int::BigInt(big_int) } } -impl From for Integer { +impl From for Int { fn from(value: BigInt) -> Self { - Integer::BigInt(value) + Int::BigInt(value) } } impl IntAccess for Element { fn as_i64(&self) -> Option { - match self.as_integer() { + match self.as_int() { Some(any) => any.as_i64(), _ => None, } } fn as_big_int(&self) -> Option<&BigInt> { - match self.as_integer() { + match self.as_int() { Some(any) => any.as_big_int(), _ => None, } } } -impl Display for Integer { +impl Display for Int { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> { match &self { - Integer::I64(i) => write!(f, "{i}"), - Integer::BigInt(i) => write!(f, "{i}"), + Int::I64(i) => write!(f, "{i}"), + Int::BigInt(i) => write!(f, "{i}"), } } } @@ -497,8 +495,8 @@ mod integer_tests { use num_bigint::BigUint; use num_traits::Zero; // The 'Big' alias helps distinguish between the enum variant and the wrapped numeric type - use crate::types::integer::Integer::{self, BigInt as Big, I64}; - use crate::types::integer::UInteger; + use crate::types::integer::Int::{self, BigInt as Big, I64}; + use crate::types::integer::UInt; use rstest::*; use std::cmp::Ordering; @@ -514,7 +512,7 @@ mod integer_tests { #[test] fn zero() { - assert!(Integer::zero().is_zero()); + assert!(Int::zero().is_zero()); } #[test] @@ -531,93 +529,77 @@ mod integer_tests { } #[rstest] - #[case::i64(Integer::I64(5), Integer::I64(4), Ordering::Greater)] - #[case::i64_equal(Integer::I64(-5), Integer::I64(-5), Ordering::Equal)] - #[case::i64_gt_big_int(Integer::I64(4), Integer::BigInt(BigInt::from(3)), Ordering::Greater)] - #[case::i64_eq_big_int(Integer::I64(3), Integer::BigInt(BigInt::from(3)), Ordering::Equal)] - #[case::i64_lt_big_int(Integer::I64(-3), Integer::BigInt(BigInt::from(5)), Ordering::Less)] + #[case::i64(Int::I64(5), Int::I64(4), Ordering::Greater)] + #[case::i64_equal(Int::I64(-5), Int::I64(-5), Ordering::Equal)] + #[case::i64_gt_big_int(Int::I64(4), Int::BigInt(BigInt::from(3)), Ordering::Greater)] + #[case::i64_eq_big_int(Int::I64(3), Int::BigInt(BigInt::from(3)), Ordering::Equal)] + #[case::i64_lt_big_int(Int::I64(-3), Int::BigInt(BigInt::from(5)), Ordering::Less)] #[case::big_int( - Integer::BigInt(BigInt::from(1100)), - Integer::BigInt(BigInt::from(-1005)), + Int::BigInt(BigInt::from(1100)), + Int::BigInt(BigInt::from(-1005)), Ordering::Greater )] #[case::big_int( - Integer::BigInt(BigInt::from(1100)), - Integer::BigInt(BigInt::from(1100)), + Int::BigInt(BigInt::from(1100)), + Int::BigInt(BigInt::from(1100)), Ordering::Equal )] - fn integer_ordering_tests( - #[case] this: Integer, - #[case] other: Integer, - #[case] expected: Ordering, - ) { + fn integer_ordering_tests(#[case] this: Int, #[case] other: Int, #[case] expected: Ordering) { assert_eq!(this.cmp(&other), expected) } #[rstest] - #[case::u64(UInteger::U64(5), UInteger::U64(4), Ordering::Greater)] - #[case::u64_equal(UInteger::U64(5), UInteger::U64(5), Ordering::Equal)] - #[case::u64_gt_big_uint( - UInteger::U64(4), - UInteger::BigUInt(BigUint::from(3u64)), - Ordering::Greater - )] - #[case::u64_lt_big_uint( - UInteger::U64(3), - UInteger::BigUInt(BigUint::from(5u64)), - Ordering::Less - )] - #[case::u64_eq_big_uint( - UInteger::U64(3), - UInteger::BigUInt(BigUint::from(3u64)), - Ordering::Equal - )] + #[case::u64(UInt::U64(5), UInt::U64(4), Ordering::Greater)] + #[case::u64_equal(UInt::U64(5), UInt::U64(5), Ordering::Equal)] + #[case::u64_gt_big_uint(UInt::U64(4), UInt::BigUInt(BigUint::from(3u64)), Ordering::Greater)] + #[case::u64_lt_big_uint(UInt::U64(3), UInt::BigUInt(BigUint::from(5u64)), Ordering::Less)] + #[case::u64_eq_big_uint(UInt::U64(3), UInt::BigUInt(BigUint::from(3u64)), Ordering::Equal)] #[case::big_uint( - UInteger::BigUInt(BigUint::from(1100u64)), - UInteger::BigUInt(BigUint::from(1005u64)), + UInt::BigUInt(BigUint::from(1100u64)), + UInt::BigUInt(BigUint::from(1005u64)), Ordering::Greater )] #[case::big_uint( - UInteger::BigUInt(BigUint::from(1005u64)), - UInteger::BigUInt(BigUint::from(1005u64)), + UInt::BigUInt(BigUint::from(1005u64)), + UInt::BigUInt(BigUint::from(1005u64)), Ordering::Equal )] fn unsigned_integer_ordering_tests( - #[case] this: UInteger, - #[case] other: UInteger, + #[case] this: UInt, + #[case] other: UInt, #[case] expected: Ordering, ) { assert_eq!(this.cmp(&other), expected) } #[rstest] - #[case(UInteger::U64(1), 1)] // only one test case for U64 as that's delegated to another impl - #[case(UInteger::BigUInt(BigUint::from(0u64)), 1)] - #[case(UInteger::BigUInt(BigUint::from(1u64)), 1)] - #[case(UInteger::BigUInt(BigUint::from(10u64)), 2)] - #[case(UInteger::BigUInt(BigUint::from(3117u64)), 4)] - fn uint_decimal_digits_test(#[case] uint: UInteger, #[case] expected: i32) { + #[case(UInt::U64(1), 1)] // only one test case for U64 as that's delegated to another impl + #[case(UInt::BigUInt(BigUint::from(0u64)), 1)] + #[case(UInt::BigUInt(BigUint::from(1u64)), 1)] + #[case(UInt::BigUInt(BigUint::from(10u64)), 2)] + #[case(UInt::BigUInt(BigUint::from(3117u64)), 4)] + fn uint_decimal_digits_test(#[case] uint: UInt, #[case] expected: i32) { assert_eq!(uint.number_of_decimal_digits(), expected as u64) } #[rstest] - #[case(Integer::I64(5), "5")] - #[case(Integer::I64(-5), "-5")] - #[case(Integer::I64(0), "0")] - #[case(Integer::BigInt(BigInt::from(1100)), "1100")] - #[case(Integer::BigInt(BigInt::from(-1100)), "-1100")] - fn int_display_test(#[case] value: Integer, #[case] expect: String) { + #[case(Int::I64(5), "5")] + #[case(Int::I64(-5), "-5")] + #[case(Int::I64(0), "0")] + #[case(Int::BigInt(BigInt::from(1100)), "1100")] + #[case(Int::BigInt(BigInt::from(-1100)), "-1100")] + fn int_display_test(#[case] value: Int, #[case] expect: String) { let mut buf = Vec::new(); write!(&mut buf, "{value}").unwrap(); assert_eq!(expect, String::from_utf8(buf).unwrap()); } #[rstest] - #[case(UInteger::U64(5), "5")] - #[case(UInteger::U64(0), "0")] - #[case(UInteger::BigUInt(BigUint::from(0u64)), "0")] - #[case(UInteger::BigUInt(BigUint::from(1100u64)), "1100")] - fn uint_display_test(#[case] value: UInteger, #[case] expect: String) { + #[case(UInt::U64(5), "5")] + #[case(UInt::U64(0), "0")] + #[case(UInt::BigUInt(BigUint::from(0u64)), "0")] + #[case(UInt::BigUInt(BigUint::from(1100u64)), "1100")] + fn uint_display_test(#[case] value: UInt, #[case] expect: String) { let mut buf = Vec::new(); write!(&mut buf, "{value}").unwrap(); assert_eq!(expect, String::from_utf8(buf).unwrap()); diff --git a/src/types/mod.rs b/src/types/mod.rs index c7e75133..9e4f8f58 100644 --- a/src/types/mod.rs +++ b/src/types/mod.rs @@ -18,7 +18,7 @@ use std::fmt; pub enum IonType { Null, Bool, - Integer, + Int, Float, Decimal, Timestamp, @@ -39,7 +39,7 @@ impl fmt::Display for IonType { match self { IonType::Null => "null", IonType::Bool => "bool", - IonType::Integer => "int", + IonType::Int => "int", IonType::Float => "float", IonType::Decimal => "decimal", IonType::Timestamp => "timestamp", diff --git a/src/types/timestamp.rs b/src/types/timestamp.rs index 2cd171d7..9f1c91c5 100644 --- a/src/types/timestamp.rs +++ b/src/types/timestamp.rs @@ -4,7 +4,7 @@ use crate::result::{ }; use crate::types::coefficient::Sign::Negative; use crate::types::decimal::Decimal; -use crate::types::integer::UInteger; +use crate::types::integer::UInt; use chrono::{ DateTime, Datelike, FixedOffset, LocalResult, NaiveDate, NaiveDateTime, TimeZone, Timelike, }; @@ -248,8 +248,8 @@ impl Timestamp { const NANOSECONDS_EXPONENT: i64 = -9; let exponent_delta = decimal.exponent - NANOSECONDS_EXPONENT; let magnitude = match decimal.coefficient.magnitude() { - UInteger::U64(magnitude) => *magnitude, - UInteger::BigUInt(magnitude) => { + UInt::U64(magnitude) => *magnitude, + UInt::BigUInt(magnitude) => { // If the magnitude is small enough to fit in a u64, do the conversion. if let Ok(small_magnitude) = u64::try_from(magnitude) { small_magnitude diff --git a/src/writer.rs b/src/writer.rs index 138bff45..b5dc7415 100644 --- a/src/writer.rs +++ b/src/writer.rs @@ -3,7 +3,7 @@ use crate::result::IonResult; use crate::types::decimal::Decimal; use crate::types::timestamp::Timestamp; use crate::types::IonType; -use crate::Integer; +use crate::Int; /** * This trait captures the format-agnostic encoding functionality needed to write native Rust types @@ -42,7 +42,7 @@ pub trait IonWriter { fn write_i64(&mut self, value: i64) -> IonResult<()>; /// Writes an Ion `integer` with the specified value to the output stream. - fn write_integer(&mut self, value: &Integer) -> IonResult<()>; + fn write_int(&mut self, value: &Int) -> IonResult<()>; /// Writes an Ion `float` with the specified value to the output stream. fn write_f32(&mut self, value: f32) -> IonResult<()>; diff --git a/tests/good_test_vectors.rs b/tests/good_test_vectors.rs index aacd3cba..ea5b5f9a 100644 --- a/tests/good_test_vectors.rs +++ b/tests/good_test_vectors.rs @@ -146,7 +146,7 @@ fn read_all_values(reader: &mut Reader) -> IonResult<()> { // The binary reader's tokens are always SIDs let _symbol_id = reader.read_symbol()?; } - Integer => { + Int => { let _int = reader.read_i64()?; } Float => { diff --git a/tests/ion_hash_tests.rs b/tests/ion_hash_tests.rs index c0e077f9..96d534b8 100644 --- a/tests/ion_hash_tests.rs +++ b/tests/ion_hash_tests.rs @@ -283,7 +283,7 @@ fn seq_to_bytes(elem: &Element) -> Vec { .expect("expected a sequence") .iter() .map(|it| { - it.as_integer() + it.as_int() .and_then(|i| i.as_i64()) .expect("expected a sequence of bytes") as u8 }) From 057527b2a4dbe6d429cf17bebe9badc4e4e9a42e Mon Sep 17 00:00:00 2001 From: Zack Slayton Date: Thu, 16 Mar 2023 09:30:52 -0400 Subject: [PATCH 14/14] clippy suggestions in ion_hash_tests --- tests/ion_hash_tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/ion_hash_tests.rs b/tests/ion_hash_tests.rs index 96d534b8..684fc541 100644 --- a/tests/ion_hash_tests.rs +++ b/tests/ion_hash_tests.rs @@ -122,7 +122,7 @@ fn ion_hash_tests() -> IonHashTestResult<()> { fn test_file(file_name: &str) -> IonHashTestResult<()> { let data = read(file_name).map_err(|source| ion_rs::IonError::IoError { source })?; - let elems = Element::read_all(&data)?; + let elems = Element::read_all(data)?; test_all(elems) } @@ -266,7 +266,7 @@ fn test_case_name_from_value(test_input_ion: &Element) -> IonResult { text_writer.flush()?; drop(text_writer); - Ok(String::from_utf8_lossy(&*buf).to_string()) + Ok(String::from_utf8_lossy(&buf).to_string()) } fn test_case_name_from_annotation(test_case_ion: &Element) -> Option {