datatypes/types/
list_type.rs1use std::sync::Arc;
16
17use arrow::datatypes::{DataType as ArrowDataType, Field};
18use serde::{Deserialize, Serialize};
19
20use crate::data_type::{ConcreteDataType, DataType};
21use crate::type_id::LogicalTypeId;
22use crate::value::{ListValue, Value};
23use crate::vectors::{ListVectorBuilder, MutableVector};
24
25#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
27pub struct ListType {
28 item_type: Arc<ConcreteDataType>,
30}
31
32impl Default for ListType {
33 fn default() -> Self {
34 ListType::new(Arc::new(ConcreteDataType::null_datatype()))
35 }
36}
37
38impl ListType {
39 pub fn new(item_type: Arc<ConcreteDataType>) -> Self {
41 ListType { item_type }
42 }
43
44 #[inline]
46 pub fn item_type(&self) -> &ConcreteDataType {
47 &self.item_type
48 }
49}
50
51impl DataType for ListType {
52 fn name(&self) -> String {
53 format!("List<{}>", self.item_type.name())
54 }
55
56 fn logical_type_id(&self) -> LogicalTypeId {
57 LogicalTypeId::List
58 }
59
60 fn default_value(&self) -> Value {
61 Value::List(ListValue::new(vec![], self.item_type.clone()))
62 }
63
64 fn as_arrow_type(&self) -> ArrowDataType {
65 let field = Arc::new(Field::new(
66 Field::LIST_FIELD_DEFAULT_NAME,
67 self.item_type.as_arrow_type(),
68 true,
69 ));
70 ArrowDataType::List(field)
71 }
72
73 fn create_mutable_vector(&self, capacity: usize) -> Box<dyn MutableVector> {
74 Box::new(ListVectorBuilder::with_type_capacity(
75 self.item_type.clone(),
76 capacity,
77 ))
78 }
79
80 fn try_cast(&self, from: Value) -> Option<Value> {
81 match from {
82 Value::List(v) => Some(Value::List(v)),
83 _ => None,
84 }
85 }
86}
87
88#[cfg(test)]
89mod tests {
90 use super::*;
91 use crate::value::ListValue;
92
93 #[test]
94 fn test_list_type() {
95 let t = ListType::new(Arc::new(ConcreteDataType::boolean_datatype()));
96 assert_eq!("List<Boolean>", t.name());
97 assert_eq!(LogicalTypeId::List, t.logical_type_id());
98 assert_eq!(
99 Value::List(ListValue::new(
100 vec![],
101 Arc::new(ConcreteDataType::boolean_datatype())
102 )),
103 t.default_value()
104 );
105 assert_eq!(
106 ArrowDataType::List(Arc::new(Field::new("item", ArrowDataType::Boolean, true))),
107 t.as_arrow_type()
108 );
109 assert_eq!(ConcreteDataType::boolean_datatype(), *t.item_type());
110 }
111}