1use syn::ext::IdentExt;
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23enum PhysicalType {
24 Boolean,
25 Int32,
26 Int64,
27 Float,
28 Double,
29 ByteArray,
30 FixedLenByteArray,
31}
32
33#[derive(Debug, PartialEq)]
34pub struct Field {
35 ident: syn::Ident,
36 ty: Type,
37 is_a_byte_buf: bool,
38 third_party_type: Option<ThirdPartyType>,
39}
40
41#[derive(Debug, PartialEq)]
49enum ThirdPartyType {
50 ChronoNaiveDateTime,
51 ChronoNaiveDate,
52 Uuid,
53}
54
55impl Field {
56 pub fn from(f: &syn::Field) -> Self {
57 let ty = Type::from(f);
58 let is_a_byte_buf = ty.physical_type() == PhysicalType::ByteArray;
59
60 let third_party_type = match &ty.last_part()[..] {
61 "NaiveDateTime" => Some(ThirdPartyType::ChronoNaiveDateTime),
62 "NaiveDate" => Some(ThirdPartyType::ChronoNaiveDate),
63 "Uuid" => Some(ThirdPartyType::Uuid),
64 _ => None,
65 };
66
67 Field {
68 ident: f
69 .ident
70 .clone()
71 .expect("Only structs with named fields are currently supported"),
72 ty,
73 is_a_byte_buf,
74 third_party_type,
75 }
76 }
77
78 pub fn writer_snippet(&self) -> proc_macro2::TokenStream {
99 let ident = &self.ident;
100 let column_writer = self.ty.column_writer();
101
102 let vals_builder = match &self.ty {
103 Type::TypePath(_) => self.copied_direct_vals(),
104 Type::Option(first_type) => match **first_type {
105 Type::TypePath(_) => self.option_into_vals(),
106 Type::Reference(_, ref second_type) => match **second_type {
107 Type::TypePath(_) => self.option_into_vals(),
108 _ => unimplemented!("Unsupported type encountered"),
109 },
110 Type::Vec(ref first_type) => match **first_type {
111 Type::TypePath(_) => self.option_into_vals(),
112 _ => unimplemented!("Unsupported type encountered"),
113 },
114 ref f => unimplemented!("Unsupported: {:#?}", f),
115 },
116 Type::Reference(_, first_type) => match **first_type {
117 Type::TypePath(_) => self.copied_direct_vals(),
118 Type::Option(ref second_type) => match **second_type {
119 Type::TypePath(_) => self.option_into_vals(),
120 Type::Reference(_, ref second_type) => match **second_type {
121 Type::TypePath(_) => self.option_into_vals(),
122 Type::Slice(ref second_type) => match **second_type {
123 Type::TypePath(_) => self.option_into_vals(),
124 ref f => unimplemented!("Unsupported: {:#?}", f),
125 },
126 _ => unimplemented!("Unsupported type encountered"),
127 },
128 Type::Vec(ref first_type) => match **first_type {
129 Type::TypePath(_) => self.option_into_vals(),
130 _ => unimplemented!("Unsupported type encountered"),
131 },
132 ref f => unimplemented!("Unsupported: {:#?}", f),
133 },
134 Type::Slice(ref second_type) => match **second_type {
135 Type::TypePath(_) => self.copied_direct_vals(),
136 ref f => unimplemented!("Unsupported: {:#?}", f),
137 },
138 ref f => unimplemented!("Unsupported: {:#?}", f),
139 },
140 Type::Vec(first_type) => match **first_type {
141 Type::TypePath(_) => self.copied_direct_vals(),
142 ref f => unimplemented!("Unsupported: {:#?}", f),
143 },
144 f => unimplemented!("Unsupported: {:#?}", f),
145 };
146
147 let definition_levels = match &self.ty {
148 Type::TypePath(_) => None,
149 Type::Option(first_type) => match **first_type {
150 Type::TypePath(_) => Some(self.optional_definition_levels()),
151 Type::Option(_) => unimplemented!("Unsupported nesting encountered"),
152 Type::Reference(_, ref second_type)
153 | Type::Vec(ref second_type)
154 | Type::Array(ref second_type, _)
155 | Type::Slice(ref second_type) => match **second_type {
156 Type::TypePath(_) => Some(self.optional_definition_levels()),
157 _ => unimplemented!("Unsupported nesting encountered"),
158 },
159 },
160 Type::Reference(_, first_type)
161 | Type::Vec(first_type)
162 | Type::Array(first_type, _)
163 | Type::Slice(first_type) => match **first_type {
164 Type::TypePath(_) => None,
165 Type::Vec(ref second_type)
166 | Type::Array(ref second_type, _)
167 | Type::Slice(ref second_type) => match **second_type {
168 Type::TypePath(_) => None,
169 Type::Reference(_, ref third_type) => match **third_type {
170 Type::TypePath(_) => None,
171 _ => unimplemented!("Unsupported definition encountered"),
172 },
173 _ => unimplemented!("Unsupported definition encountered"),
174 },
175 Type::Reference(_, ref second_type) | Type::Option(ref second_type) => {
176 match **second_type {
177 Type::TypePath(_) => Some(self.optional_definition_levels()),
178 Type::Vec(ref third_type)
179 | Type::Array(ref third_type, _)
180 | Type::Slice(ref third_type) => match **third_type {
181 Type::TypePath(_) => Some(self.optional_definition_levels()),
182 Type::Reference(_, ref fourth_type) => match **fourth_type {
183 Type::TypePath(_) => Some(self.optional_definition_levels()),
184 _ => unimplemented!("Unsupported definition encountered"),
185 },
186 _ => unimplemented!("Unsupported definition encountered"),
187 },
188 Type::Reference(_, ref third_type) => match **third_type {
189 Type::TypePath(_) => Some(self.optional_definition_levels()),
190 Type::Slice(ref fourth_type) => match **fourth_type {
191 Type::TypePath(_) => Some(self.optional_definition_levels()),
192 _ => unimplemented!("Unsupported definition encountered"),
193 },
194 _ => unimplemented!("Unsupported definition encountered"),
195 },
196 _ => unimplemented!("Unsupported definition encountered"),
197 }
198 }
199 },
200 };
201
202 let write_batch_expr = if definition_levels.is_some() {
209 quote! {
210 if let #column_writer(typed) = column_writer.untyped() {
211 typed.write_batch(&vals[..], Some(&definition_levels[..]), None)?;
212 } else {
213 panic!("Schema and struct disagree on type for {}", stringify!{#ident})
214 }
215 }
216 } else {
217 quote! {
218 if let #column_writer(typed) = column_writer.untyped() {
219 typed.write_batch(&vals[..], None, None)?;
220 } else {
221 panic!("Schema and struct disagree on type for {}", stringify!{#ident})
222 }
223 }
224 };
225
226 quote! {
227 {
228 #definition_levels
229
230 #vals_builder
231
232 #write_batch_expr
233 }
234 }
235 }
236
237 pub fn reader_snippet(&self) -> proc_macro2::TokenStream {
260 let ident = &self.ident;
261 let column_reader = self.ty.column_reader();
262
263 let write_batch_expr = quote! {
265 let mut vals = Vec::new();
266 if let #column_reader(mut typed) = column_reader {
267 let mut definition_levels = Vec::new();
268 let (total_num, valid_num, decoded_num) = typed.read_records(
269 num_records, Some(&mut definition_levels), None, &mut vals)?;
270 if valid_num != decoded_num {
271 panic!("Support only valid records, found {} null records in column type {}",
272 decoded_num - valid_num, stringify!{#ident});
273 }
274 } else {
275 panic!("Schema and struct disagree on type for {}", stringify!{#ident});
276 }
277 };
278
279 let vals_writer = match &self.ty {
282 Type::TypePath(_) => self.copied_direct_fields(),
283 Type::Reference(_, first_type) => match **first_type {
284 Type::TypePath(_) => self.copied_direct_fields(),
285 Type::Slice(ref second_type) => match **second_type {
286 Type::TypePath(_) => self.copied_direct_fields(),
287 ref f => unimplemented!("Unsupported: {:#?}", f),
288 },
289 ref f => unimplemented!("Unsupported: {:#?}", f),
290 },
291 Type::Vec(first_type) => match **first_type {
292 Type::TypePath(_) => self.copied_direct_fields(),
293 ref f => unimplemented!("Unsupported: {:#?}", f),
294 },
295 f => unimplemented!("Unsupported: {:#?}", f),
296 };
297
298 quote! {
299 {
300 #write_batch_expr
301
302 #vals_writer
303 }
304 }
305 }
306
307 pub fn parquet_type(&self) -> proc_macro2::TokenStream {
308 let field_name = self.ident.unraw().to_string();
314 let physical_type = match self.ty.physical_type() {
315 PhysicalType::Boolean => quote! {
316 ::parquet::basic::Type::BOOLEAN
317 },
318 PhysicalType::Int32 => quote! {
319 ::parquet::basic::Type::INT32
320 },
321 PhysicalType::Int64 => quote! {
322 ::parquet::basic::Type::INT64
323 },
324 PhysicalType::Float => quote! {
325 ::parquet::basic::Type::FLOAT
326 },
327 PhysicalType::Double => quote! {
328 ::parquet::basic::Type::DOUBLE
329 },
330 PhysicalType::ByteArray => quote! {
331 ::parquet::basic::Type::BYTE_ARRAY
332 },
333 PhysicalType::FixedLenByteArray => quote! {
334 ::parquet::basic::Type::FIXED_LEN_BYTE_ARRAY
335 },
336 };
337 let logical_type = self.ty.logical_type();
338 let repetition = self.ty.repetition();
339 let converted_type = self.ty.converted_type();
340 let length = self.ty.length();
341
342 let mut builder = quote! {
343 ParquetType::primitive_type_builder(#field_name, #physical_type)
344 .with_logical_type(#logical_type)
345 .with_repetition(#repetition)
346 };
347
348 if let Some(converted_type) = converted_type {
349 builder = quote! { #builder.with_converted_type(#converted_type) };
350 }
351
352 if let Some(length) = length {
353 builder = quote! { #builder.with_length(#length) };
354 }
355
356 quote! { fields.push(#builder.build().unwrap().into()) }
357 }
358
359 fn option_into_vals(&self) -> proc_macro2::TokenStream {
360 let field_name = &self.ident;
361 let is_a_byte_buf = self.is_a_byte_buf;
362 let is_a_timestamp = self.third_party_type == Some(ThirdPartyType::ChronoNaiveDateTime);
363 let is_a_date = self.third_party_type == Some(ThirdPartyType::ChronoNaiveDate);
364 let is_a_uuid = self.third_party_type == Some(ThirdPartyType::Uuid);
365 let copy_to_vec = !matches!(
366 self.ty.physical_type(),
367 PhysicalType::ByteArray | PhysicalType::FixedLenByteArray
368 );
369
370 let binding = if copy_to_vec {
371 quote! { let Some(inner) = rec.#field_name }
372 } else {
373 quote! { let Some(inner) = &rec.#field_name }
374 };
375
376 let some = if is_a_timestamp {
377 quote! { Some(inner.timestamp_millis()) }
378 } else if is_a_date {
379 quote! { Some(inner.signed_duration_since(::chrono::NaiveDate::from_ymd(1970, 1, 1)).num_days() as i32) }
380 } else if is_a_uuid {
381 quote! { Some((&inner.to_string()[..]).into()) }
382 } else if is_a_byte_buf {
383 quote! { Some((&inner[..]).into())}
384 } else {
385 match self.ty.physical_type() {
387 PhysicalType::Int32 => quote! { Some(inner as i32) },
388 PhysicalType::Int64 => quote! { Some(inner as i64) },
389 _ => quote! { Some(inner) },
390 }
391 };
392
393 quote! {
394 let vals: Vec<_> = records.iter().filter_map(|rec| {
395 if #binding {
396 #some
397 } else {
398 None
399 }
400 }).collect();
401 }
402 }
403
404 fn copied_direct_vals(&self) -> proc_macro2::TokenStream {
406 let field_name = &self.ident;
407
408 let access = match self.third_party_type {
409 Some(ThirdPartyType::ChronoNaiveDateTime) => {
410 quote! { rec.#field_name.timestamp_millis() }
411 }
412 Some(ThirdPartyType::ChronoNaiveDate) => {
413 quote! { rec.#field_name.signed_duration_since(::chrono::NaiveDate::from_ymd(1970, 1, 1)).num_days() as i32 }
414 }
415 Some(ThirdPartyType::Uuid) => {
416 quote! { rec.#field_name.as_bytes().to_vec().into() }
417 }
418 _ => {
419 if self.is_a_byte_buf {
420 quote! { (&rec.#field_name[..]).into() }
421 } else {
422 match self.ty.physical_type() {
424 PhysicalType::Int32 => quote! { rec.#field_name as i32 },
425 PhysicalType::Int64 => quote! { rec.#field_name as i64 },
426 _ => quote! { rec.#field_name },
427 }
428 }
429 }
430 };
431
432 quote! {
433 let vals: Vec<_> = records.iter().map(|rec| #access).collect();
434 }
435 }
436
437 fn copied_direct_fields(&self) -> proc_macro2::TokenStream {
439 let field_name = &self.ident;
440
441 let value = match self.third_party_type {
442 Some(ThirdPartyType::ChronoNaiveDateTime) => {
443 quote! { ::chrono::naive::NaiveDateTime::from_timestamp_millis(vals[i]).unwrap() }
444 }
445 Some(ThirdPartyType::ChronoNaiveDate) => {
446 quote! {
448 ::chrono::naive::NaiveDate::from_num_days_from_ce_opt(vals[i].saturating_add(719163)).unwrap()
449 }
450 }
451 Some(ThirdPartyType::Uuid) => {
452 quote! { ::uuid::Uuid::from_bytes(vals[i].data().try_into().unwrap()) }
453 }
454 _ => match &self.ty {
455 Type::TypePath(_) => match self.ty.last_part().as_str() {
456 "String" => quote! { String::from(std::str::from_utf8(vals[i].data())
457 .expect("invalid UTF-8 sequence")) },
458 t => {
459 let s: proc_macro2::TokenStream = t.parse().unwrap();
460 quote! { vals[i] as #s }
461 }
462 },
463 Type::Vec(_) => quote! { vals[i].data().to_vec() },
464 f => unimplemented!("Unsupported: {:#?}", f),
465 },
466 };
467
468 quote! {
469 for (i, r) in &mut records[..num_records].iter_mut().enumerate() {
470 r.#field_name = #value;
471 }
472 }
473 }
474
475 fn optional_definition_levels(&self) -> proc_macro2::TokenStream {
476 let field_name = &self.ident;
477
478 quote! {
479 let definition_levels: Vec<i16> = self
480 .iter()
481 .map(|rec| if rec.#field_name.is_some() { 1 } else { 0 })
482 .collect();
483 }
484 }
485}
486
487#[expect(clippy::enum_variant_names)]
488#[derive(Debug, PartialEq)]
489enum Type {
490 Array(Box<Type>, syn::Expr),
491 Option(Box<Type>),
492 Slice(Box<Type>),
493 Vec(Box<Type>),
494 TypePath(syn::Type),
495 Reference(Option<syn::Lifetime>, Box<Type>),
496}
497
498impl Type {
499 fn column_writer(&self) -> syn::TypePath {
502 match self.physical_type() {
503 PhysicalType::Boolean => {
504 syn::parse_quote!(ColumnWriter::BoolColumnWriter)
505 }
506 PhysicalType::Int32 => syn::parse_quote!(ColumnWriter::Int32ColumnWriter),
507 PhysicalType::Int64 => syn::parse_quote!(ColumnWriter::Int64ColumnWriter),
508 PhysicalType::Float => syn::parse_quote!(ColumnWriter::FloatColumnWriter),
509 PhysicalType::Double => syn::parse_quote!(ColumnWriter::DoubleColumnWriter),
510 PhysicalType::ByteArray => {
511 syn::parse_quote!(ColumnWriter::ByteArrayColumnWriter)
512 }
513 PhysicalType::FixedLenByteArray => {
514 syn::parse_quote!(ColumnWriter::FixedLenByteArrayColumnWriter)
515 }
516 }
517 }
518
519 fn column_reader(&self) -> syn::TypePath {
522 match self.physical_type() {
523 PhysicalType::Boolean => {
524 syn::parse_quote!(ColumnReader::BoolColumnReader)
525 }
526 PhysicalType::Int32 => syn::parse_quote!(ColumnReader::Int32ColumnReader),
527 PhysicalType::Int64 => syn::parse_quote!(ColumnReader::Int64ColumnReader),
528 PhysicalType::Float => syn::parse_quote!(ColumnReader::FloatColumnReader),
529 PhysicalType::Double => syn::parse_quote!(ColumnReader::DoubleColumnReader),
530 PhysicalType::ByteArray => {
531 syn::parse_quote!(ColumnReader::ByteArrayColumnReader)
532 }
533 PhysicalType::FixedLenByteArray => {
534 syn::parse_quote!(ColumnReader::FixedLenByteArrayColumnReader)
535 }
536 }
537 }
538
539 fn leaf_type_recursive(&self) -> &Type {
549 Type::leaf_type_recursive_helper(self, None)
550 }
551
552 fn leaf_type_recursive_helper<'a>(ty: &'a Type, parent_ty: Option<&'a Type>) -> &'a Type {
553 match ty {
554 Type::TypePath(_) => parent_ty.unwrap_or(ty),
555 Type::Option(first_type)
556 | Type::Vec(first_type)
557 | Type::Array(first_type, _)
558 | Type::Slice(first_type)
559 | Type::Reference(_, first_type) => {
560 Type::leaf_type_recursive_helper(first_type, Some(ty))
561 }
562 }
563 }
564
565 fn inner_type(&self) -> &syn::Type {
569 let leaf_type = self.leaf_type_recursive();
570
571 match leaf_type {
572 Type::TypePath(type_) => type_,
573 Type::Option(first_type)
574 | Type::Vec(first_type)
575 | Type::Array(first_type, _)
576 | Type::Slice(first_type)
577 | Type::Reference(_, first_type) => match **first_type {
578 Type::TypePath(ref type_) => type_,
579 _ => unimplemented!("leaf_type() should only return shallow types"),
580 },
581 }
582 }
583
584 fn last_part(&self) -> String {
597 let inner_type = self.inner_type();
598 let inner_type_str = (quote! { #inner_type }).to_string();
599
600 inner_type_str
601 .split("::")
602 .last()
603 .unwrap()
604 .trim()
605 .to_string()
606 }
607
608 fn physical_type(&self) -> PhysicalType {
616 let last_part = self.last_part();
617 let leaf_type = self.leaf_type_recursive();
618
619 match leaf_type {
620 Type::Array(first_type, _length) => {
621 if let Type::TypePath(_) = **first_type
622 && last_part == "u8"
623 {
624 return PhysicalType::FixedLenByteArray;
625 }
626 }
627 Type::Vec(first_type) | Type::Slice(first_type) => {
628 if let Type::TypePath(_) = **first_type
629 && last_part == "u8"
630 {
631 return PhysicalType::ByteArray;
632 }
633 }
634 _ => (),
635 }
636
637 match last_part.trim() {
638 "bool" => PhysicalType::Boolean,
639 "u8" | "u16" | "u32" => PhysicalType::Int32,
640 "i8" | "i16" | "i32" | "NaiveDate" => PhysicalType::Int32,
641 "u64" | "i64" | "NaiveDateTime" => PhysicalType::Int64,
642 "usize" | "isize" => {
643 if usize::BITS == 64 {
644 PhysicalType::Int64
645 } else {
646 PhysicalType::Int32
647 }
648 }
649 "f32" => PhysicalType::Float,
650 "f64" => PhysicalType::Double,
651 "String" | "str" | "Arc < str >" => PhysicalType::ByteArray,
652 "Uuid" => PhysicalType::FixedLenByteArray,
653 f => unimplemented!("{} currently is not supported", f),
654 }
655 }
656
657 fn length(&self) -> Option<syn::Expr> {
658 let last_part = self.last_part();
659 let leaf_type = self.leaf_type_recursive();
660
661 if let Type::Array(first_type, length) = leaf_type
663 && let Type::TypePath(_) = **first_type
664 && last_part == "u8"
665 {
666 return Some(length.clone());
667 }
668
669 match last_part.trim() {
670 "Uuid" => Some(syn::parse_quote!(16)),
672 _ => None,
673 }
674 }
675
676 fn logical_type(&self) -> proc_macro2::TokenStream {
677 let last_part = self.last_part();
678 let leaf_type = self.leaf_type_recursive();
679
680 match leaf_type {
681 Type::Array(first_type, _length) => {
682 if let Type::TypePath(_) = **first_type
683 && last_part == "u8"
684 {
685 return quote! { None };
686 }
687 }
688 Type::Vec(first_type) | Type::Slice(first_type) => {
689 if let Type::TypePath(_) = **first_type
690 && last_part == "u8"
691 {
692 return quote! { None };
693 }
694 }
695 _ => (),
696 }
697
698 match last_part.trim() {
699 "bool" => quote! { None },
700 "u8" => quote! { Some(LogicalType::integer(8, false)) },
701 "u16" => quote! { Some(LogicalType::integer(16, false)) },
702 "u32" => quote! { Some(LogicalType::integer(32, false)) },
703 "u64" => quote! { Some(LogicalType::integer(64, false)) },
704 "i8" => quote! { Some(LogicalType::integer(8, true)) },
705 "i16" => quote! { Some(LogicalType::integer(16, true)) },
706 "i32" | "i64" => quote! { None },
707 "usize" => {
708 quote! { Some(LogicalType::integer(usize::BITS as i8, false)) }
709 }
710 "isize" => {
711 quote! { Some(LogicalType::integer(usize::BITS as i8, true)) }
712 }
713 "NaiveDate" => quote! { Some(LogicalType::Date) },
714 "NaiveDateTime" => quote! { None },
715 "f32" | "f64" => quote! { None },
716 "String" | "str" | "Arc < str >" => quote! { Some(LogicalType::String) },
717 "Uuid" => quote! { Some(LogicalType::Uuid) },
718 f => unimplemented!("{} currently is not supported", f),
719 }
720 }
721
722 fn converted_type(&self) -> Option<proc_macro2::TokenStream> {
723 let last_part = self.last_part();
724
725 match last_part.trim() {
726 "NaiveDateTime" => Some(quote! { ::parquet::basic::ConvertedType::TIMESTAMP_MILLIS }),
727 _ => None,
728 }
729 }
730
731 fn repetition(&self) -> proc_macro2::TokenStream {
732 match self {
733 Type::Option(_) => quote! { ::parquet::basic::Repetition::OPTIONAL },
734 Type::Reference(_, ty) => ty.repetition(),
735 _ => quote! { ::parquet::basic::Repetition::REQUIRED },
736 }
737 }
738
739 fn from(f: &syn::Field) -> Self {
742 Type::from_type(f, &f.ty)
743 }
744
745 fn from_type(f: &syn::Field, ty: &syn::Type) -> Self {
746 match ty {
747 syn::Type::Path(p) => Type::from_type_path(f, p),
748 syn::Type::Reference(tr) => Type::from_type_reference(f, tr),
749 syn::Type::Array(ta) => Type::from_type_array(f, ta),
750 syn::Type::Slice(ts) => Type::from_type_slice(f, ts),
751 other => unimplemented!(
752 "Unable to derive {:?} - it is currently an unsupported type\n{:#?}",
753 f.ident.as_ref().unwrap(),
754 other
755 ),
756 }
757 }
758
759 fn from_type_path(f: &syn::Field, p: &syn::TypePath) -> Self {
760 let last_segment = p.path.segments.last().unwrap();
761
762 let is_vec = last_segment.ident == syn::Ident::new("Vec", proc_macro2::Span::call_site());
763 let is_option =
764 last_segment.ident == syn::Ident::new("Option", proc_macro2::Span::call_site());
765
766 if is_vec || is_option {
767 let generic_type = match &last_segment.arguments {
768 syn::PathArguments::AngleBracketed(angle_args) => {
769 assert_eq!(angle_args.args.len(), 1);
770 let first_arg = &angle_args.args[0];
771
772 match first_arg {
773 syn::GenericArgument::Type(typath) => typath.clone(),
774 other => unimplemented!("Unsupported: {:#?}", other),
775 }
776 }
777 other => unimplemented!("Unsupported: {:#?}", other),
778 };
779
780 if is_vec {
781 Type::Vec(Box::new(Type::from_type(f, &generic_type)))
782 } else {
783 Type::Option(Box::new(Type::from_type(f, &generic_type)))
784 }
785 } else {
786 Type::TypePath(syn::Type::Path(p.clone()))
787 }
788 }
789
790 fn from_type_reference(f: &syn::Field, tr: &syn::TypeReference) -> Self {
791 let lifetime = tr.lifetime.clone();
792 let inner_type = Type::from_type(f, tr.elem.as_ref());
793 Type::Reference(lifetime, Box::new(inner_type))
794 }
795
796 fn from_type_array(f: &syn::Field, ta: &syn::TypeArray) -> Self {
797 let inner_type = Type::from_type(f, ta.elem.as_ref());
798 Type::Array(Box::new(inner_type), ta.len.clone())
799 }
800
801 fn from_type_slice(f: &syn::Field, ts: &syn::TypeSlice) -> Self {
802 let inner_type = Type::from_type(f, ts.elem.as_ref());
803 Type::Slice(Box::new(inner_type))
804 }
805}
806
807#[cfg(test)]
808mod test {
809 use super::*;
810 use syn::{Data, DataStruct, DeriveInput};
811
812 fn extract_fields(input: proc_macro2::TokenStream) -> Vec<syn::Field> {
813 let input: DeriveInput = syn::parse2(input).unwrap();
814
815 let fields = match input.data {
816 Data::Struct(DataStruct { fields, .. }) => fields,
817 _ => panic!("Input must be a struct"),
818 };
819
820 fields.iter().map(|field| field.to_owned()).collect()
821 }
822
823 #[test]
824 fn test_generating_a_simple_writer_snippet() {
825 let snippet: proc_macro2::TokenStream = quote! {
826 struct ABoringStruct {
827 counter: usize,
828 }
829 };
830
831 let fields = extract_fields(snippet);
832 let counter = Field::from(&fields[0]);
833
834 let snippet = counter.writer_snippet().to_string();
835 assert_eq!(snippet,
836 (quote!{
837 {
838 let vals : Vec < _ > = records . iter ( ) . map ( | rec | rec . counter as i64 ) . collect ( );
839
840 if let ColumnWriter::Int64ColumnWriter ( typed ) = column_writer.untyped() {
841 typed . write_batch ( & vals [ .. ] , None , None ) ?;
842 } else {
843 panic!("Schema and struct disagree on type for {}" , stringify!{ counter } )
844 }
845 }
846 }).to_string()
847 )
848 }
849
850 #[test]
851 fn test_generating_a_simple_reader_snippet() {
852 let snippet: proc_macro2::TokenStream = quote! {
853 struct ABoringStruct {
854 counter: usize,
855 }
856 };
857
858 let fields = extract_fields(snippet);
859 let counter = Field::from(&fields[0]);
860
861 let snippet = counter.reader_snippet().to_string();
862 assert_eq!(
863 snippet,
864 (quote! {
865 {
866 let mut vals = Vec::new();
867 if let ColumnReader::Int64ColumnReader(mut typed) = column_reader {
868 let mut definition_levels = Vec::new();
869 let (total_num, valid_num, decoded_num) = typed.read_records(
870 num_records, Some(&mut definition_levels), None, &mut vals)?;
871 if valid_num != decoded_num {
872 panic!("Support only valid records, found {} null records in column type {}",
873 decoded_num - valid_num, stringify!{counter});
874 }
875 } else {
876 panic!("Schema and struct disagree on type for {}", stringify!{counter});
877 }
878 for (i, r) in &mut records[..num_records].iter_mut().enumerate() {
879 r.counter = vals[i] as usize;
880 }
881 }
882 })
883 .to_string()
884 )
885 }
886
887 #[test]
888 fn test_parquet_type_with_raw_identifier() {
889 let snippet: proc_macro2::TokenStream = quote! {
890 struct ABoringStruct {
891 r#type: i32,
892 }
893 };
894
895 let fields = extract_fields(snippet);
896 let r#type = Field::from(&fields[0]);
897
898 let snippet = r#type.parquet_type().to_string();
900 assert!(
901 snippet.contains("primitive_type_builder (\"type\""),
902 "{snippet}"
903 );
904 }
905
906 #[test]
907 fn test_optional_to_writer_snippet() {
908 let struct_def: proc_macro2::TokenStream = quote! {
909 struct StringBorrower<'a> {
910 optional_str: Option<&'a str>,
911 optional_string: Option<&String>,
912 optional_dumb_int: Option<&i32>,
913 }
914 };
915
916 let fields = extract_fields(struct_def);
917
918 let optional = Field::from(&fields[0]);
919 let snippet = optional.writer_snippet();
920 assert_eq!(snippet.to_string(),
921 (quote! {
922 {
923 let definition_levels : Vec < i16 > = self . iter ( ) . map ( | rec | if rec . optional_str . is_some ( ) { 1 } else { 0 } ) . collect ( ) ;
924
925 let vals: Vec <_> = records.iter().filter_map( |rec| {
926 if let Some ( inner ) = &rec . optional_str {
927 Some ( (&inner[..]).into() )
928 } else {
929 None
930 }
931 }).collect();
932
933 if let ColumnWriter::ByteArrayColumnWriter ( typed ) = column_writer.untyped() {
934 typed . write_batch ( & vals [ .. ] , Some(&definition_levels[..]) , None ) ? ;
935 } else {
936 panic!("Schema and struct disagree on type for {}" , stringify ! { optional_str } )
937 }
938 }
939 }
940 ).to_string());
941
942 let optional = Field::from(&fields[1]);
943 let snippet = optional.writer_snippet();
944 assert_eq!(snippet.to_string(),
945 (quote!{
946 {
947 let definition_levels : Vec < i16 > = self . iter ( ) . map ( | rec | if rec . optional_string . is_some ( ) { 1 } else { 0 } ) . collect ( ) ;
948
949 let vals: Vec <_> = records.iter().filter_map( |rec| {
950 if let Some ( inner ) = &rec . optional_string {
951 Some ( (&inner[..]).into() )
952 } else {
953 None
954 }
955 }).collect();
956
957 if let ColumnWriter::ByteArrayColumnWriter ( typed ) = column_writer.untyped() {
958 typed . write_batch ( & vals [ .. ] , Some(&definition_levels[..]) , None ) ? ;
959 } else {
960 panic!("Schema and struct disagree on type for {}" , stringify ! { optional_string } )
961 }
962 }
963 }).to_string());
964
965 let optional = Field::from(&fields[2]);
966 let snippet = optional.writer_snippet();
967 assert_eq!(snippet.to_string(),
968 (quote!{
969 {
970 let definition_levels : Vec < i16 > = self . iter ( ) . map ( | rec | if rec . optional_dumb_int . is_some ( ) { 1 } else { 0 } ) . collect ( ) ;
971
972 let vals: Vec <_> = records.iter().filter_map( |rec| {
973 if let Some ( inner ) = rec . optional_dumb_int {
974 Some ( inner as i32 )
975 } else {
976 None
977 }
978 }).collect();
979
980 if let ColumnWriter::Int32ColumnWriter ( typed ) = column_writer.untyped() {
981 typed . write_batch ( & vals [ .. ] , Some(&definition_levels[..]) , None ) ? ;
982 } else {
983 panic!("Schema and struct disagree on type for {}" , stringify ! { optional_dumb_int } )
984 }
985 }
986 }).to_string());
987 }
988
989 #[test]
990 fn test_converting_to_column_writer_type() {
991 let snippet: proc_macro2::TokenStream = quote! {
992 struct ABasicStruct {
993 yes_no: bool,
994 name: String,
995 }
996 };
997
998 let fields = extract_fields(snippet);
999 let processed: Vec<_> = fields.iter().map(Field::from).collect();
1000
1001 let column_writers: Vec<_> = processed
1002 .iter()
1003 .map(|field| field.ty.column_writer())
1004 .collect();
1005
1006 assert_eq!(
1007 column_writers,
1008 vec![
1009 syn::parse_quote!(ColumnWriter::BoolColumnWriter),
1010 syn::parse_quote!(ColumnWriter::ByteArrayColumnWriter)
1011 ]
1012 );
1013 }
1014
1015 #[test]
1016 fn test_converting_to_column_reader_type() {
1017 let snippet: proc_macro2::TokenStream = quote! {
1018 struct ABasicStruct {
1019 yes_no: bool,
1020 name: String,
1021 }
1022 };
1023
1024 let fields = extract_fields(snippet);
1025 let processed: Vec<_> = fields.iter().map(Field::from).collect();
1026
1027 let column_readers: Vec<_> = processed
1028 .iter()
1029 .map(|field| field.ty.column_reader())
1030 .collect();
1031
1032 assert_eq!(
1033 column_readers,
1034 vec![
1035 syn::parse_quote!(ColumnReader::BoolColumnReader),
1036 syn::parse_quote!(ColumnReader::ByteArrayColumnReader)
1037 ]
1038 );
1039 }
1040
1041 #[test]
1042 fn convert_basic_struct() {
1043 let snippet: proc_macro2::TokenStream = quote! {
1044 struct ABasicStruct {
1045 yes_no: bool,
1046 name: String,
1047 length: usize
1048 }
1049 };
1050
1051 let fields = extract_fields(snippet);
1052 let processed: Vec<_> = fields.iter().map(Field::from).collect();
1053 assert_eq!(processed.len(), 3);
1054
1055 assert_eq!(
1056 processed,
1057 vec![
1058 Field {
1059 ident: syn::Ident::new("yes_no", proc_macro2::Span::call_site()),
1060 ty: Type::TypePath(syn::parse_quote!(bool)),
1061 is_a_byte_buf: false,
1062 third_party_type: None,
1063 },
1064 Field {
1065 ident: syn::Ident::new("name", proc_macro2::Span::call_site()),
1066 ty: Type::TypePath(syn::parse_quote!(String)),
1067 is_a_byte_buf: true,
1068 third_party_type: None,
1069 },
1070 Field {
1071 ident: syn::Ident::new("length", proc_macro2::Span::call_site()),
1072 ty: Type::TypePath(syn::parse_quote!(usize)),
1073 is_a_byte_buf: false,
1074 third_party_type: None,
1075 }
1076 ]
1077 )
1078 }
1079
1080 #[test]
1081 fn test_get_inner_type() {
1082 let snippet: proc_macro2::TokenStream = quote! {
1083 struct LotsOfInnerTypes {
1084 a_vec: Vec<u8>,
1085 a_option: ::std::option::Option<bool>,
1086 a_silly_string: ::std::string::String,
1087 a_complicated_thing: ::std::option::Option<::std::result::Result<(),()>>,
1088 }
1089 };
1090
1091 let fields = extract_fields(snippet);
1092 let converted_fields: Vec<_> = fields.iter().map(Type::from).collect();
1093 let inner_types: Vec<_> = converted_fields
1094 .iter()
1095 .map(|field| field.inner_type())
1096 .collect();
1097 let inner_types_strs: Vec<_> = inner_types
1098 .iter()
1099 .map(|ty| (quote! { #ty }).to_string())
1100 .collect();
1101
1102 assert_eq!(
1103 inner_types_strs,
1104 vec![
1105 "u8",
1106 "bool",
1107 ":: std :: string :: String",
1108 ":: std :: result :: Result < () , () >"
1109 ]
1110 )
1111 }
1112
1113 #[test]
1114 fn test_physical_type() {
1115 let snippet: proc_macro2::TokenStream = quote! {
1116 struct LotsOfInnerTypes {
1117 a_buf: ::std::vec::Vec<u8>,
1118 a_number: i32,
1119 a_verbose_option: ::std::option::Option<bool>,
1120 a_silly_string: String,
1121 a_fix_byte_buf: [u8; 10],
1122 a_complex_option: ::std::option::Option<&Vec<u8>>,
1123 a_complex_vec: &::std::vec::Vec<&Option<u8>>,
1124 a_uuid: ::uuid::Uuid,
1125 }
1126 };
1127
1128 let fields = extract_fields(snippet);
1129 let converted_fields: Vec<_> = fields.iter().map(Type::from).collect();
1130 let physical_types: Vec<_> = converted_fields
1131 .iter()
1132 .map(|ty| ty.physical_type())
1133 .collect();
1134
1135 assert_eq!(
1136 physical_types,
1137 vec![
1138 PhysicalType::ByteArray,
1139 PhysicalType::Int32,
1140 PhysicalType::Boolean,
1141 PhysicalType::ByteArray,
1142 PhysicalType::FixedLenByteArray,
1143 PhysicalType::ByteArray,
1144 PhysicalType::Int32,
1145 PhysicalType::FixedLenByteArray,
1146 ]
1147 )
1148 }
1149
1150 #[test]
1151 fn test_type_length() {
1152 let snippet: proc_macro2::TokenStream = quote! {
1153 struct LotsOfInnerTypes {
1154 a_buf: ::std::vec::Vec<u8>,
1155 a_number: i32,
1156 a_verbose_option: ::std::option::Option<bool>,
1157 a_silly_string: String,
1158 a_fix_byte_buf: [u8; 10],
1159 a_complex_option: ::std::option::Option<&Vec<u8>>,
1160 a_complex_vec: &::std::vec::Vec<&Option<u8>>,
1161 a_uuid: ::uuid::Uuid,
1162 }
1163 };
1164
1165 let fields = extract_fields(snippet);
1166 let converted_fields: Vec<_> = fields.iter().map(Type::from).collect();
1167 let lengths: Vec<_> = converted_fields.iter().map(|ty| ty.length()).collect();
1168
1169 assert_eq!(
1170 lengths,
1171 vec![
1172 None,
1173 None,
1174 None,
1175 None,
1176 Some(syn::parse_quote!(10)),
1177 None,
1178 None,
1179 Some(syn::parse_quote!(16)),
1180 ]
1181 )
1182 }
1183
1184 #[test]
1185 fn test_convert_comprehensive_owned_struct() {
1186 let snippet: proc_macro2::TokenStream = quote! {
1187 struct VecHolder {
1188 a_vec: ::std::vec::Vec<u8>,
1189 a_option: ::std::option::Option<bool>,
1190 a_silly_string: ::std::string::String,
1191 a_complicated_thing: ::std::option::Option<::std::result::Result<(),()>>,
1192 }
1193 };
1194
1195 let fields = extract_fields(snippet);
1196 let converted_fields: Vec<_> = fields.iter().map(Type::from).collect();
1197
1198 assert_eq!(
1199 converted_fields,
1200 vec![
1201 Type::Vec(Box::new(Type::TypePath(syn::parse_quote!(u8)))),
1202 Type::Option(Box::new(Type::TypePath(syn::parse_quote!(bool)))),
1203 Type::TypePath(syn::parse_quote!(::std::string::String)),
1204 Type::Option(Box::new(Type::TypePath(
1205 syn::parse_quote!(::std::result::Result<(),()>)
1206 ))),
1207 ]
1208 );
1209 }
1210
1211 #[test]
1212 fn test_convert_borrowed_struct() {
1213 let snippet: proc_macro2::TokenStream = quote! {
1214 struct Borrower<'a> {
1215 a_str: &'a str,
1216 a_borrowed_option: &'a Option<bool>,
1217 so_many_borrows: &'a Option<&'a str>,
1218 }
1219 };
1220
1221 let fields = extract_fields(snippet);
1222 let types: Vec<_> = fields.iter().map(Type::from).collect();
1223
1224 assert_eq!(
1225 types,
1226 vec![
1227 Type::Reference(
1228 Some(syn::Lifetime::new("'a", proc_macro2::Span::call_site())),
1229 Box::new(Type::TypePath(syn::parse_quote!(str)))
1230 ),
1231 Type::Reference(
1232 Some(syn::Lifetime::new("'a", proc_macro2::Span::call_site())),
1233 Box::new(Type::Option(Box::new(Type::TypePath(syn::parse_quote!(
1234 bool
1235 )))))
1236 ),
1237 Type::Reference(
1238 Some(syn::Lifetime::new("'a", proc_macro2::Span::call_site())),
1239 Box::new(Type::Option(Box::new(Type::Reference(
1240 Some(syn::Lifetime::new("'a", proc_macro2::Span::call_site())),
1241 Box::new(Type::TypePath(syn::parse_quote!(str)))
1242 ))))
1243 ),
1244 ]
1245 );
1246 }
1247
1248 #[test]
1249 fn test_chrono_timestamp_millis_write() {
1250 let snippet: proc_macro2::TokenStream = quote! {
1251 struct ATimestampStruct {
1252 henceforth: chrono::NaiveDateTime,
1253 maybe_happened: Option<&chrono::NaiveDateTime>,
1254 }
1255 };
1256
1257 let fields = extract_fields(snippet);
1258 let when = Field::from(&fields[0]);
1259 assert_eq!(when.writer_snippet().to_string(),(quote!{
1260 {
1261 let vals : Vec<_> = records.iter().map(|rec| rec.henceforth.timestamp_millis() ).collect();
1262 if let ColumnWriter::Int64ColumnWriter(typed) = column_writer.untyped() {
1263 typed.write_batch(&vals[..], None, None) ?;
1264 } else {
1265 panic!("Schema and struct disagree on type for {}" , stringify!{ henceforth })
1266 }
1267 }
1268 }).to_string());
1269
1270 let maybe_happened = Field::from(&fields[1]);
1271 assert_eq!(maybe_happened.writer_snippet().to_string(),(quote!{
1272 {
1273 let definition_levels : Vec<i16> = self.iter().map(|rec| if rec.maybe_happened.is_some() { 1 } else { 0 }).collect();
1274 let vals : Vec<_> = records.iter().filter_map(|rec| {
1275 if let Some(inner) = rec.maybe_happened {
1276 Some(inner.timestamp_millis())
1277 } else {
1278 None
1279 }
1280 }).collect();
1281
1282 if let ColumnWriter::Int64ColumnWriter(typed) = column_writer.untyped() {
1283 typed.write_batch(&vals[..], Some(&definition_levels[..]), None) ?;
1284 } else {
1285 panic!("Schema and struct disagree on type for {}" , stringify!{ maybe_happened })
1286 }
1287 }
1288 }).to_string());
1289 }
1290
1291 #[test]
1292 fn test_chrono_timestamp_millis_read() {
1293 let snippet: proc_macro2::TokenStream = quote! {
1294 struct ATimestampStruct {
1295 henceforth: chrono::NaiveDateTime,
1296 }
1297 };
1298
1299 let fields = extract_fields(snippet);
1300 let when = Field::from(&fields[0]);
1301 assert_eq!(when.reader_snippet().to_string(),(quote!{
1302 {
1303 let mut vals = Vec::new();
1304 if let ColumnReader::Int64ColumnReader(mut typed) = column_reader {
1305 let mut definition_levels = Vec::new();
1306 let (total_num, valid_num, decoded_num) = typed.read_records(
1307 num_records, Some(&mut definition_levels), None, &mut vals)?;
1308 if valid_num != decoded_num {
1309 panic!("Support only valid records, found {} null records in column type {}",
1310 decoded_num - valid_num, stringify!{henceforth});
1311 }
1312 } else {
1313 panic!("Schema and struct disagree on type for {}", stringify!{ henceforth });
1314 }
1315 for (i, r) in &mut records[..num_records].iter_mut().enumerate() {
1316 r.henceforth = ::chrono::naive::NaiveDateTime::from_timestamp_millis(vals[i]).unwrap();
1317 }
1318 }
1319 }).to_string());
1320 }
1321
1322 #[test]
1323 fn test_chrono_date_write() {
1324 let snippet: proc_macro2::TokenStream = quote! {
1325 struct ATimestampStruct {
1326 henceforth: chrono::NaiveDate,
1327 maybe_happened: Option<&chrono::NaiveDate>,
1328 }
1329 };
1330
1331 let fields = extract_fields(snippet);
1332 let when = Field::from(&fields[0]);
1333 assert_eq!(when.writer_snippet().to_string(),(quote!{
1334 {
1335 let vals : Vec<_> = records.iter().map(|rec| rec.henceforth.signed_duration_since(::chrono::NaiveDate::from_ymd(1970, 1, 1)).num_days() as i32).collect();
1336 if let ColumnWriter::Int32ColumnWriter(typed) = column_writer.untyped() {
1337 typed.write_batch(&vals[..], None, None) ?;
1338 } else {
1339 panic!("Schema and struct disagree on type for {}" , stringify!{ henceforth })
1340 }
1341 }
1342 }).to_string());
1343
1344 let maybe_happened = Field::from(&fields[1]);
1345 assert_eq!(maybe_happened.writer_snippet().to_string(),(quote!{
1346 {
1347 let definition_levels : Vec<i16> = self.iter().map(|rec| if rec.maybe_happened.is_some() { 1 } else { 0 }).collect();
1348 let vals : Vec<_> = records.iter().filter_map(|rec| {
1349 if let Some(inner) = rec.maybe_happened {
1350 Some(inner.signed_duration_since(::chrono::NaiveDate::from_ymd(1970, 1, 1)).num_days() as i32)
1351 } else {
1352 None
1353 }
1354 }).collect();
1355
1356 if let ColumnWriter::Int32ColumnWriter(typed) = column_writer.untyped() {
1357 typed.write_batch(&vals[..], Some(&definition_levels[..]), None) ?;
1358 } else {
1359 panic!("Schema and struct disagree on type for {}" , stringify!{ maybe_happened })
1360 }
1361 }
1362 }).to_string());
1363 }
1364
1365 #[test]
1366 fn test_chrono_date_read() {
1367 let snippet: proc_macro2::TokenStream = quote! {
1368 struct ATimestampStruct {
1369 henceforth: chrono::NaiveDate,
1370 }
1371 };
1372
1373 let fields = extract_fields(snippet);
1374 let when = Field::from(&fields[0]);
1375 assert_eq!(when.reader_snippet().to_string(),(quote!{
1376 {
1377 let mut vals = Vec::new();
1378 if let ColumnReader::Int32ColumnReader(mut typed) = column_reader {
1379 let mut definition_levels = Vec::new();
1380 let (total_num, valid_num, decoded_num) = typed.read_records(
1381 num_records, Some(&mut definition_levels), None, &mut vals)?;
1382 if valid_num != decoded_num {
1383 panic!("Support only valid records, found {} null records in column type {}",
1384 decoded_num - valid_num, stringify!{henceforth});
1385 }
1386 } else {
1387 panic!("Schema and struct disagree on type for {}", stringify!{ henceforth });
1388 }
1389 for (i, r) in &mut records[..num_records].iter_mut().enumerate() {
1390 r.henceforth = ::chrono::naive::NaiveDate::from_num_days_from_ce_opt(vals[i].saturating_add(719163)).unwrap();
1391 }
1392 }
1393 }).to_string());
1394 }
1395
1396 #[test]
1397 fn test_uuid_write() {
1398 let snippet: proc_macro2::TokenStream = quote! {
1399 struct AUuidStruct {
1400 unique_id: uuid::Uuid,
1401 maybe_unique_id: Option<&uuid::Uuid>,
1402 }
1403 };
1404
1405 let fields = extract_fields(snippet);
1406 let when = Field::from(&fields[0]);
1407 assert_eq!(when.writer_snippet().to_string(),(quote!{
1408 {
1409 let vals : Vec<_> = records.iter().map(|rec| rec.unique_id.as_bytes().to_vec().into() ).collect();
1410 if let ColumnWriter::FixedLenByteArrayColumnWriter(typed) = column_writer.untyped() {
1411 typed.write_batch(&vals[..], None, None) ?;
1412 } else {
1413 panic!("Schema and struct disagree on type for {}" , stringify!{ unique_id })
1414 }
1415 }
1416 }).to_string());
1417
1418 let maybe_happened = Field::from(&fields[1]);
1419 assert_eq!(maybe_happened.writer_snippet().to_string(),(quote!{
1420 {
1421 let definition_levels : Vec<i16> = self.iter().map(|rec| if rec.maybe_unique_id.is_some() { 1 } else { 0 }).collect();
1422 let vals : Vec<_> = records.iter().filter_map(|rec| {
1423 if let Some(inner) = &rec.maybe_unique_id {
1424 Some((&inner.to_string()[..]).into())
1425 } else {
1426 None
1427 }
1428 }).collect();
1429
1430 if let ColumnWriter::FixedLenByteArrayColumnWriter(typed) = column_writer.untyped() {
1431 typed.write_batch(&vals[..], Some(&definition_levels[..]), None) ?;
1432 } else {
1433 panic!("Schema and struct disagree on type for {}" , stringify!{ maybe_unique_id })
1434 }
1435 }
1436 }).to_string());
1437 }
1438
1439 #[test]
1440 fn test_uuid_read() {
1441 let snippet: proc_macro2::TokenStream = quote! {
1442 struct AUuidStruct {
1443 unique_id: uuid::Uuid,
1444 }
1445 };
1446
1447 let fields = extract_fields(snippet);
1448 let when = Field::from(&fields[0]);
1449 assert_eq!(when.reader_snippet().to_string(),(quote!{
1450 {
1451 let mut vals = Vec::new();
1452 if let ColumnReader::FixedLenByteArrayColumnReader(mut typed) = column_reader {
1453 let mut definition_levels = Vec::new();
1454 let (total_num, valid_num, decoded_num) = typed.read_records(
1455 num_records, Some(&mut definition_levels), None, &mut vals)?;
1456 if valid_num != decoded_num {
1457 panic!("Support only valid records, found {} null records in column type {}",
1458 decoded_num - valid_num, stringify!{unique_id});
1459 }
1460 } else {
1461 panic!("Schema and struct disagree on type for {}", stringify!{ unique_id });
1462 }
1463 for (i, r) in &mut records[..num_records].iter_mut().enumerate() {
1464 r.unique_id = ::uuid::Uuid::from_bytes(vals[i].data().try_into().unwrap());
1465 }
1466 }
1467 }).to_string());
1468 }
1469
1470 #[test]
1471 fn test_converted_type() {
1472 let snippet: proc_macro2::TokenStream = quote! {
1473 struct ATimeStruct {
1474 time: chrono::NaiveDateTime,
1475 }
1476 };
1477
1478 let fields = extract_fields(snippet);
1479
1480 let time = Field::from(&fields[0]);
1481
1482 let converted_type = time.ty.converted_type();
1483 assert_eq!(
1484 converted_type.unwrap().to_string(),
1485 quote! { ::parquet::basic::ConvertedType::TIMESTAMP_MILLIS }.to_string()
1486 );
1487 }
1488}