Skip to main content

apache_avro/
lib.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18//! **[Apache Avro](https://avro.apache.org/)** is a data serialization system which provides rich
19//! data structures and a compact, fast, binary data format. If you are not familiar with the data
20//! format, please read [`documentation::primer`] first.
21//!
22//! There are two ways of working with Avro data in this crate:
23//!
24//! 1. Via the generic [`Value`](types::Value) type.
25//! 2. Via types implementing [`AvroSchema`] and Serde's [`Serialize`] and [`Deserialize`].
26//!
27//! The first option is great for dealing with Avro data in a dynamic way. For example, when working
28//! with unknown or rapidly changing schemas or when you don't want or need to map to Rust types. The
29//! module documentation of [`documentation::dynamic`] explains how to work in this dynamic way.
30//!
31//! The second option is great when dealing with static schemas that should be decoded to and encoded
32//! from Rust types. The module documentation of [`serde`] explains how to work in this static way.
33//!
34//! # Features
35//!
36//! - `derive`: enable support for deriving [`AvroSchema`]
37//! - `snappy`: enable support for the Snappy codec
38//! - `zstandard`: enable support for the Zstandard codec
39//! - `bzip`: enable support for the Bzip2 codec
40//! - `xz`: enable support for the Xz codec
41//!
42//! # MSRV
43//!
44//! The current MSRV is 1.88.0.
45//!
46//! The MSRV may be bumped in minor releases.
47//!
48// These are links because otherwise `cargo rdme` gets angry
49//! [`Serialize`]: https://docs.rs/serde/latest/serde/trait.Serialize.html
50//! [`Deserialize`]: https://docs.rs/serde/latest/serde/trait.Deserialize.html
51
52// Enable using `fake_variadic` on docs.rs
53#![cfg_attr(docsrs, feature(rustdoc_internals))]
54#![cfg_attr(docsrs, allow(internal_features))]
55
56mod bigdecimal;
57mod codec;
58mod decimal;
59mod decode;
60mod duration;
61mod encode;
62
63#[cfg(doc)]
64pub mod documentation;
65pub mod error;
66pub mod headers;
67pub mod rabin;
68pub mod reader;
69pub mod schema;
70pub mod schema_compatibility;
71pub mod schema_equality;
72pub mod serde;
73pub mod types;
74pub mod util;
75pub mod validator;
76pub mod writer;
77
78// Re-export types from private module
79pub use crate::{
80    bigdecimal::BigDecimal,
81    codec::{Codec, DeflateSettings},
82    decimal::Decimal,
83    duration::{Days, Duration, Millis, Months},
84};
85
86// Re-export types from private modules that need to be behind feature gates
87#[cfg(feature = "bzip")]
88pub use crate::codec::bzip::Bzip2Settings;
89#[cfg(feature = "xz")]
90pub use crate::codec::xz::XzSettings;
91#[cfg(feature = "zstandard")]
92pub use crate::codec::zstandard::ZstandardSettings;
93
94// Re-exports that are available at their respective paths but are made available in the root for
95// convenience.
96#[doc(inline)]
97pub use crate::{
98    error::Error,
99    reader::{
100        Reader,
101        single_object::{GenericSingleObjectReader, SpecificSingleObjectReader},
102    },
103    schema::Schema,
104    serde::{AvroSchema, AvroSchemaComponent, from_value, to_value},
105    writer::{
106        Clearable, Writer, WriterBuilder,
107        single_object::{GenericSingleObjectWriter, SpecificSingleObjectWriter},
108    },
109};
110
111// Re-exports from other crates
112pub use uuid::Uuid;
113
114#[cfg(feature = "derive")]
115pub use apache_avro_derive::AvroSchema;
116
117/// A convenience type alias for `Result`s with `Error`s.
118pub type AvroResult<T> = Result<T, Error>;
119
120#[cfg(test)]
121mod tests {
122    use crate::{
123        Codec, Reader, Schema, Writer,
124        reader::datum::GenericDatumReader,
125        types::{Record, Value},
126    };
127    use apache_avro_test_helper::TestResult;
128    use pretty_assertions::assert_eq;
129
130    //TODO: move where it fits better
131    #[test]
132    fn test_enum_default() {
133        let writer_raw_schema = r#"
134            {
135                "type": "record",
136                "name": "test",
137                "fields": [
138                    {"name": "a", "type": "long", "default": 42},
139                    {"name": "b", "type": "string"}
140                ]
141            }
142        "#;
143        let reader_raw_schema = r#"
144            {
145                "type": "record",
146                "name": "test",
147                "fields": [
148                    {"name": "a", "type": "long", "default": 42},
149                    {"name": "b", "type": "string"},
150                    {
151                        "name": "c",
152                        "type": {
153                            "type": "enum",
154                            "name": "suit",
155                            "symbols": ["diamonds", "spades", "clubs", "hearts"]
156                        },
157                        "default": "spades"
158                    }
159                ]
160            }
161        "#;
162        let writer_schema = Schema::parse_str(writer_raw_schema).unwrap();
163        let reader_schema = Schema::parse_str(reader_raw_schema).unwrap();
164        let mut writer = Writer::with_codec(&writer_schema, Vec::new(), Codec::Null).unwrap();
165        let mut record = Record::new(writer.schema()).unwrap();
166        record.put("a", 27i64);
167        record.put("b", "foo");
168        writer.append_value(record).unwrap();
169        let input = writer.into_inner().unwrap();
170        let mut reader = Reader::builder(&input[..])
171            .reader_schema(&reader_schema)
172            .build()
173            .unwrap();
174        assert_eq!(
175            reader.next().unwrap().unwrap(),
176            Value::Record(vec![
177                ("a".to_string(), Value::Long(27)),
178                ("b".to_string(), Value::String("foo".to_string())),
179                ("c".to_string(), Value::Enum(1, "spades".to_string())),
180            ])
181        );
182        assert!(reader.next().is_none());
183    }
184
185    //TODO: move where it fits better
186    #[test]
187    fn test_enum_string_value() {
188        let raw_schema = r#"
189            {
190                "type": "record",
191                "name": "test",
192                "fields": [
193                    {"name": "a", "type": "long", "default": 42},
194                    {"name": "b", "type": "string"},
195                    {
196                        "name": "c",
197                        "type": {
198                            "type": "enum",
199                            "name": "suit",
200                            "symbols": ["diamonds", "spades", "clubs", "hearts"]
201                        },
202                        "default": "spades"
203                    }
204                ]
205            }
206        "#;
207        let schema = Schema::parse_str(raw_schema).unwrap();
208        let mut writer = Writer::with_codec(&schema, Vec::new(), Codec::Null).unwrap();
209        let mut record = Record::new(writer.schema()).unwrap();
210        record.put("a", 27i64);
211        record.put("b", "foo");
212        record.put("c", "clubs");
213        writer.append_value(record).unwrap();
214        let input = writer.into_inner().unwrap();
215        let mut reader = Reader::builder(&input[..])
216            .reader_schema(&schema)
217            .build()
218            .unwrap();
219        assert_eq!(
220            reader.next().unwrap().unwrap(),
221            Value::Record(vec![
222                ("a".to_string(), Value::Long(27)),
223                ("b".to_string(), Value::String("foo".to_string())),
224                ("c".to_string(), Value::Enum(2, "clubs".to_string())),
225            ])
226        );
227        assert!(reader.next().is_none());
228    }
229
230    //TODO: move where it fits better
231    #[test]
232    fn test_enum_no_reader_schema() {
233        let writer_raw_schema = r#"
234            {
235                "type": "record",
236                "name": "test",
237                "fields": [
238                    {"name": "a", "type": "long", "default": 42},
239                    {"name": "b", "type": "string"},
240                    {
241                        "name": "c",
242                        "type": {
243                            "type": "enum",
244                            "name": "suit",
245                            "symbols": ["diamonds", "spades", "clubs", "hearts"]
246                        },
247                        "default": "spades"
248                    }
249                ]
250            }
251        "#;
252        let writer_schema = Schema::parse_str(writer_raw_schema).unwrap();
253        let mut writer = Writer::with_codec(&writer_schema, Vec::new(), Codec::Null).unwrap();
254        let mut record = Record::new(writer.schema()).unwrap();
255        record.put("a", 27i64);
256        record.put("b", "foo");
257        record.put("c", "clubs");
258        writer.append_value(record).unwrap();
259        let input = writer.into_inner().unwrap();
260        let mut reader = Reader::new(&input[..]).unwrap();
261        assert_eq!(
262            reader.next().unwrap().unwrap(),
263            Value::Record(vec![
264                ("a".to_string(), Value::Long(27)),
265                ("b".to_string(), Value::String("foo".to_string())),
266                ("c".to_string(), Value::Enum(2, "clubs".to_string())),
267            ])
268        );
269    }
270
271    #[test]
272    fn test_illformed_length() -> TestResult {
273        let raw_schema = r#"
274            {
275                "type": "record",
276                "name": "test",
277                "fields": [
278                    {"name": "a", "type": "long", "default": 42},
279                    {"name": "b", "type": "string"}
280                ]
281            }
282        "#;
283
284        let schema = Schema::parse_str(raw_schema).unwrap();
285
286        // Would allocate 18446744073709551605 bytes
287        let illformed: &[u8] = &[0x3e, 0x15, 0xff, 0x1f, 0x15, 0xff];
288
289        let value = GenericDatumReader::builder(&schema)
290            .build()?
291            .read_value(&mut &*illformed);
292        assert!(value.is_err());
293
294        Ok(())
295    }
296}