gel_protocol/
codec.rs

1/*!
2Implementations of the [Codec] trait into types found in the [Value] enum.
3*/
4
5use std::any::type_name;
6use std::collections::HashSet;
7use std::convert::{TryFrom, TryInto};
8use std::fmt;
9use std::ops::Deref;
10use std::str;
11use std::sync::Arc;
12
13use bytes::{Buf, BufMut, BytesMut};
14use snafu::{ensure, OptionExt, ResultExt};
15use uuid::Uuid as UuidVal;
16
17use crate::common::Cardinality;
18use crate::descriptors::{self, Descriptor, TypePos};
19use crate::errors::{self, CodecError, DecodeError, EncodeError};
20use crate::model;
21use crate::model::range;
22use crate::serialization::decode::DecodeRange;
23use crate::serialization::decode::{DecodeArrayLike, DecodeTupleLike, RawCodec};
24use crate::value::{SparseObject, Value};
25
26pub const STD_UUID: UuidVal = UuidVal::from_u128(0x100);
27pub const STD_STR: UuidVal = UuidVal::from_u128(0x101);
28pub const STD_BYTES: UuidVal = UuidVal::from_u128(0x102);
29pub const STD_INT16: UuidVal = UuidVal::from_u128(0x103);
30pub const STD_INT32: UuidVal = UuidVal::from_u128(0x104);
31pub const STD_INT64: UuidVal = UuidVal::from_u128(0x105);
32pub const STD_FLOAT32: UuidVal = UuidVal::from_u128(0x106);
33pub const STD_FLOAT64: UuidVal = UuidVal::from_u128(0x107);
34pub const STD_DECIMAL: UuidVal = UuidVal::from_u128(0x108);
35pub const STD_BOOL: UuidVal = UuidVal::from_u128(0x109);
36pub const STD_DATETIME: UuidVal = UuidVal::from_u128(0x10a);
37pub const CAL_LOCAL_DATETIME: UuidVal = UuidVal::from_u128(0x10b);
38pub const CAL_LOCAL_DATE: UuidVal = UuidVal::from_u128(0x10c);
39pub const CAL_LOCAL_TIME: UuidVal = UuidVal::from_u128(0x10d);
40pub const STD_DURATION: UuidVal = UuidVal::from_u128(0x10e);
41pub const CAL_RELATIVE_DURATION: UuidVal = UuidVal::from_u128(0x111);
42pub const CAL_DATE_DURATION: UuidVal = UuidVal::from_u128(0x112);
43pub const STD_JSON: UuidVal = UuidVal::from_u128(0x10f);
44pub const STD_BIGINT: UuidVal = UuidVal::from_u128(0x110);
45pub const CFG_MEMORY: UuidVal = UuidVal::from_u128(0x130);
46pub const PGVECTOR_VECTOR: UuidVal = UuidVal::from_u128(0x9565dd88_04f5_11ee_a691_0b6ebe179825);
47pub const STD_PG_JSON: UuidVal = UuidVal::from_u128(0x1000001);
48pub const STD_PG_TIMESTAMPTZ: UuidVal = UuidVal::from_u128(0x1000002);
49pub const STD_PG_TIMESTAMP: UuidVal = UuidVal::from_u128(0x1000003);
50pub const STD_PG_DATE: UuidVal = UuidVal::from_u128(0x1000004);
51pub const STD_PG_INTERVAL: UuidVal = UuidVal::from_u128(0x1000005);
52pub const POSTGIS_GEOMETRY: UuidVal = UuidVal::from_u128(0x44c901c0_d922_4894_83c8_061bd05e4840);
53pub const POSTGIS_GEOGRAPHY: UuidVal = UuidVal::from_u128(0x4d738878_3a5f_4821_ab76_9d8e7d6b32c4);
54pub const POSTGIS_BOX_2D: UuidVal = UuidVal::from_u128(0x7fae5536_6311_4f60_8eb9_096a5d972f48);
55pub const POSTGIS_BOX_3D: UuidVal = UuidVal::from_u128(0xc1a50ff8_fded_48b0_85c2_4905a8481433);
56
57pub(crate) fn uuid_to_known_name(uuid: &UuidVal) -> Option<&'static str> {
58    match *uuid {
59        STD_UUID => Some("BaseScalar(uuid)"),
60        STD_STR => Some("BaseScalar(str)"),
61        STD_BYTES => Some("BaseScalar(bytes)"),
62        STD_INT16 => Some("BaseScalar(int16)"),
63        STD_INT32 => Some("BaseScalar(int32)"),
64        STD_INT64 => Some("BaseScalar(int64)"),
65        STD_FLOAT32 => Some("BaseScalar(float32)"),
66        STD_FLOAT64 => Some("BaseScalar(float64)"),
67        STD_DECIMAL => Some("BaseScalar(decimal)"),
68        STD_BOOL => Some("BaseScalar(bool)"),
69        STD_DATETIME => Some("BaseScalar(datetime)"),
70        CAL_LOCAL_DATETIME => Some("BaseScalar(cal::local_datetime)"),
71        CAL_LOCAL_DATE => Some("BaseScalar(cal::local_date)"),
72        CAL_LOCAL_TIME => Some("BaseScalar(cal::local_time)"),
73        STD_DURATION => Some("BaseScalar(duration)"),
74        CAL_RELATIVE_DURATION => Some("BaseScalar(cal::relative_duration)"),
75        CAL_DATE_DURATION => Some("BaseScalar(cal::date_duration)"),
76        STD_JSON => Some("BaseScalar(std::json)"),
77        STD_BIGINT => Some("BaseScalar(bigint)"),
78        CFG_MEMORY => Some("BaseScalar(cfg::memory)"),
79        PGVECTOR_VECTOR => Some("BaseScalar(ext::pgvector::vector)"),
80        STD_PG_JSON => Some("BaseScalar(std::pg::json)"),
81        STD_PG_TIMESTAMPTZ => Some("BaseScalar(std::pg::timestamptz)"),
82        STD_PG_TIMESTAMP => Some("BaseScalar(std::pg::timestamp)"),
83        STD_PG_DATE => Some("BaseScalar(std::pg::date)"),
84        STD_PG_INTERVAL => Some("BaseScalar(std::pg::interval)"),
85        POSTGIS_GEOMETRY => Some("BaseScalar(ext::postgis::geometry)"),
86        POSTGIS_GEOGRAPHY => Some("BaseScalar(ext::postgis::geography)"),
87        POSTGIS_BOX_2D => Some("BaseScalar(ext::postgis::box2d)"),
88        POSTGIS_BOX_3D => Some("BaseScalar(ext::postgis::box3d)"),
89        _ => None,
90    }
91}
92
93pub trait Codec: fmt::Debug + Send + Sync + 'static {
94    fn decode(&self, buf: &[u8]) -> Result<Value, DecodeError>;
95    fn encode(&self, buf: &mut BytesMut, value: &Value) -> Result<(), EncodeError>;
96}
97
98#[derive(Debug, Clone, PartialEq, Eq)]
99pub struct EnumValue(Arc<str>);
100#[derive(Debug, Clone, PartialEq, Eq)]
101pub struct ObjectShape(pub(crate) Arc<ObjectShapeInfo>);
102#[derive(Debug, Clone, PartialEq, Eq)]
103pub struct NamedTupleShape(Arc<NamedTupleShapeInfo>);
104#[derive(Debug, Clone, PartialEq, Eq)]
105pub struct SQLRowShape(Arc<SQLRowShapeInfo>);
106
107#[derive(Debug, PartialEq, Eq)]
108pub struct ObjectShapeInfo {
109    pub elements: Vec<ShapeElement>,
110}
111
112#[derive(Debug, PartialEq, Eq)]
113pub struct ShapeElement {
114    pub flag_implicit: bool,
115    pub flag_link_property: bool,
116    pub flag_link: bool,
117    pub cardinality: Option<Cardinality>,
118    pub name: String,
119}
120
121#[derive(Debug, Clone, PartialEq, Eq)]
122pub struct InputObjectShape(pub(crate) Arc<InputObjectShapeInfo>);
123
124#[derive(Debug, PartialEq, Eq)]
125pub struct InputObjectShapeInfo {
126    pub elements: Vec<InputShapeElement>,
127}
128
129#[derive(Debug, PartialEq, Eq)]
130pub struct InputShapeElement {
131    pub cardinality: Option<Cardinality>,
132    pub name: String,
133}
134
135#[derive(Debug, PartialEq, Eq)]
136pub struct NamedTupleShapeInfo {
137    pub elements: Vec<TupleElement>,
138}
139
140#[derive(Debug, PartialEq, Eq)]
141pub struct TupleElement {
142    pub name: String,
143}
144
145#[derive(Debug, PartialEq, Eq)]
146pub struct SQLRowShapeInfo {
147    pub elements: Vec<SQLRowElement>,
148}
149
150#[derive(Debug, PartialEq, Eq)]
151pub struct SQLRowElement {
152    pub name: String,
153}
154
155#[derive(Debug)]
156pub struct Uuid;
157
158#[derive(Debug)]
159pub struct Int16;
160
161#[derive(Debug)]
162pub struct Int32;
163
164#[derive(Debug)]
165pub struct Int64;
166
167#[derive(Debug)]
168pub struct Float32;
169
170#[derive(Debug)]
171pub struct Float64;
172
173#[derive(Debug)]
174pub struct Str;
175
176#[derive(Debug)]
177pub struct Bytes;
178
179#[derive(Debug)]
180pub struct Duration;
181
182#[derive(Debug)]
183pub struct RelativeDuration;
184
185#[derive(Debug)]
186pub struct DateDuration;
187
188#[derive(Debug)]
189pub struct Datetime;
190
191#[derive(Debug)]
192pub struct LocalDatetime;
193
194#[derive(Debug)]
195pub struct LocalDate;
196
197#[derive(Debug)]
198pub struct LocalTime;
199
200#[derive(Debug)]
201pub struct Decimal;
202
203#[derive(Debug)]
204pub struct BigInt;
205
206#[derive(Debug)]
207pub struct ConfigMemory;
208
209#[derive(Debug)]
210pub struct Bool;
211
212#[derive(Debug)]
213pub struct Json;
214
215#[derive(Debug)]
216pub struct PgTextJson;
217
218#[derive(Debug)]
219pub struct Nothing;
220
221#[derive(Debug)]
222pub struct Object {
223    shape: ObjectShape,
224    codecs: Vec<Arc<dyn Codec>>,
225}
226
227#[derive(Debug)]
228pub struct Input {
229    shape: InputObjectShape,
230    codecs: Vec<Arc<dyn Codec>>,
231}
232
233#[derive(Debug)]
234pub struct Set {
235    element: Arc<dyn Codec>,
236}
237
238#[derive(Debug)]
239pub struct Scalar {
240    inner: Arc<dyn Codec>,
241}
242
243#[derive(Debug)]
244pub struct Tuple {
245    elements: Vec<Arc<dyn Codec>>,
246}
247
248#[derive(Debug)]
249pub struct NamedTuple {
250    shape: NamedTupleShape,
251    codecs: Vec<Arc<dyn Codec>>,
252}
253
254#[derive(Debug)]
255pub struct SQLRow {
256    shape: SQLRowShape,
257    codecs: Vec<Arc<dyn Codec>>,
258}
259
260#[derive(Debug)]
261pub struct Array {
262    element: Arc<dyn Codec>,
263}
264
265#[derive(Debug)]
266pub struct Vector {}
267
268#[derive(Debug)]
269pub struct Range {
270    element: Arc<dyn Codec>,
271}
272
273#[derive(Debug)]
274pub struct MultiRange {
275    element: Arc<dyn Codec>,
276}
277
278#[derive(Debug)]
279pub struct ArrayAdapter(Array);
280
281#[derive(Debug)]
282pub struct Enum {
283    members: HashSet<Arc<str>>,
284}
285
286#[derive(Debug)]
287pub struct PostGisGeometry {}
288
289#[derive(Debug)]
290pub struct PostGisGeography {}
291
292#[derive(Debug)]
293pub struct PostGisBox2d {}
294
295#[derive(Debug)]
296pub struct PostGisBox3d {}
297
298struct CodecBuilder<'a> {
299    descriptors: &'a [Descriptor],
300}
301
302impl ObjectShape {
303    pub fn new(elements: Vec<ShapeElement>) -> ObjectShape {
304        ObjectShape(Arc::new(ObjectShapeInfo { elements }))
305    }
306}
307
308impl Deref for ObjectShape {
309    type Target = ObjectShapeInfo;
310    fn deref(&self) -> &ObjectShapeInfo {
311        &self.0
312    }
313}
314
315impl InputObjectShape {
316    pub fn new(elements: Vec<InputShapeElement>) -> Self {
317        InputObjectShape(Arc::new(InputObjectShapeInfo { elements }))
318    }
319}
320
321impl Deref for InputObjectShape {
322    type Target = InputObjectShapeInfo;
323    fn deref(&self) -> &InputObjectShapeInfo {
324        &self.0
325    }
326}
327
328impl Deref for NamedTupleShape {
329    type Target = NamedTupleShapeInfo;
330    fn deref(&self) -> &NamedTupleShapeInfo {
331        &self.0
332    }
333}
334
335impl Deref for SQLRowShape {
336    type Target = SQLRowShapeInfo;
337    fn deref(&self) -> &SQLRowShapeInfo {
338        &self.0
339    }
340}
341
342impl CodecBuilder<'_> {
343    fn build(&self, pos: TypePos) -> Result<Arc<dyn Codec>, CodecError> {
344        use Descriptor as D;
345        if let Some(item) = self.descriptors.get(pos.0 as usize) {
346            match item {
347                D::BaseScalar(base) => scalar_codec(&base.id),
348                D::Set(d) => Ok(Arc::new(Set::build(d, self)?)),
349                D::ObjectShape(d) => Ok(Arc::new(Object::build(d, self)?)),
350                D::Scalar(d) => Ok(Arc::new(Scalar {
351                    inner: match d.base_type_pos {
352                        Some(type_pos) => self.build(type_pos)?,
353                        None => scalar_codec(&d.id)?,
354                    },
355                })),
356                D::Tuple(d) => Ok(Arc::new(Tuple::build(d, self)?)),
357                D::NamedTuple(d) => Ok(Arc::new(NamedTuple::build(d, self)?)),
358                D::Array(d) => Ok(Arc::new(Array {
359                    element: self.build(d.type_pos)?,
360                })),
361                D::Range(d) => Ok(Arc::new(Range {
362                    element: self.build(d.type_pos)?,
363                })),
364                D::MultiRange(d) => Ok(Arc::new(MultiRange {
365                    element: Arc::new(Range {
366                        element: self.build(d.type_pos)?,
367                    }),
368                })),
369                D::Enumeration(d) => Ok(Arc::new(Enum {
370                    members: d.members.iter().map(|x| x[..].into()).collect(),
371                })),
372                D::Object(_) => Ok(Arc::new(Nothing {})),
373                D::Compound(_) => Ok(Arc::new(Nothing {})),
374                D::InputShape(d) => Ok(Arc::new(Input::build(d, self)?)),
375                D::SQLRow(d) => Ok(Arc::new(SQLRow::build(d, self)?)),
376                // type annotations are stripped from codecs array before
377                // building a codec
378                D::TypeAnnotation(..) => unreachable!(),
379            }
380        } else {
381            errors::UnexpectedTypePos { position: pos.0 }.fail()?
382        }
383    }
384}
385
386pub fn build_codec(
387    root_pos: Option<TypePos>,
388    descriptors: &[Descriptor],
389) -> Result<Arc<dyn Codec>, CodecError> {
390    let dec = CodecBuilder { descriptors };
391    match root_pos {
392        Some(pos) => dec.build(pos),
393        None => Ok(Arc::new(Nothing {})),
394    }
395}
396
397pub fn scalar_codec(uuid: &UuidVal) -> Result<Arc<dyn Codec>, CodecError> {
398    match *uuid {
399        STD_UUID => Ok(Arc::new(Uuid {})),
400        STD_STR => Ok(Arc::new(Str {})),
401        STD_BYTES => Ok(Arc::new(Bytes {})),
402        STD_INT16 => Ok(Arc::new(Int16 {})),
403        STD_INT32 => Ok(Arc::new(Int32 {})),
404        STD_INT64 => Ok(Arc::new(Int64 {})),
405        STD_FLOAT32 => Ok(Arc::new(Float32 {})),
406        STD_FLOAT64 => Ok(Arc::new(Float64 {})),
407        STD_DECIMAL => Ok(Arc::new(Decimal {})),
408        STD_BOOL => Ok(Arc::new(Bool {})),
409        STD_DATETIME => Ok(Arc::new(Datetime {})),
410        CAL_LOCAL_DATETIME => Ok(Arc::new(LocalDatetime {})),
411        CAL_LOCAL_DATE => Ok(Arc::new(LocalDate {})),
412        CAL_LOCAL_TIME => Ok(Arc::new(LocalTime {})),
413        STD_DURATION => Ok(Arc::new(Duration {})),
414        CAL_RELATIVE_DURATION => Ok(Arc::new(RelativeDuration {})),
415        CAL_DATE_DURATION => Ok(Arc::new(DateDuration {})),
416        STD_JSON => Ok(Arc::new(Json {})),
417        STD_BIGINT => Ok(Arc::new(BigInt {})),
418        CFG_MEMORY => Ok(Arc::new(ConfigMemory {})),
419        PGVECTOR_VECTOR => Ok(Arc::new(Vector {})),
420        STD_PG_JSON => Ok(Arc::new(PgTextJson {})),
421        STD_PG_TIMESTAMPTZ => Ok(Arc::new(Datetime {})),
422        STD_PG_TIMESTAMP => Ok(Arc::new(LocalDatetime {})),
423        STD_PG_DATE => Ok(Arc::new(LocalDate {})),
424        STD_PG_INTERVAL => Ok(Arc::new(RelativeDuration {})),
425        POSTGIS_GEOMETRY => Ok(Arc::new(PostGisGeometry {})),
426        POSTGIS_GEOGRAPHY => Ok(Arc::new(PostGisGeography {})),
427        POSTGIS_BOX_2D => Ok(Arc::new(PostGisBox2d {})),
428        POSTGIS_BOX_3D => Ok(Arc::new(PostGisBox3d {})),
429        _ => errors::UndefinedBaseScalar { uuid: *uuid }.fail()?,
430    }
431}
432
433impl Codec for Int16 {
434    fn decode(&self, buf: &[u8]) -> Result<Value, DecodeError> {
435        RawCodec::decode(buf).map(Value::Int16)
436    }
437    fn encode(&self, buf: &mut BytesMut, val: &Value) -> Result<(), EncodeError> {
438        let &val = match val {
439            Value::Int16(val) => val,
440            _ => Err(errors::invalid_value(type_name::<Self>(), val))?,
441        };
442        buf.reserve(2);
443        buf.put_i16(val);
444        Ok(())
445    }
446}
447
448impl Codec for Int32 {
449    fn decode(&self, buf: &[u8]) -> Result<Value, DecodeError> {
450        RawCodec::decode(buf).map(Value::Int32)
451    }
452    fn encode(&self, buf: &mut BytesMut, val: &Value) -> Result<(), EncodeError> {
453        let val = match val {
454            Value::Int32(val) => *val,
455            Value::Int16(val) => *val as i32,
456            _ => Err(errors::invalid_value(type_name::<Self>(), val))?,
457        };
458        buf.reserve(4);
459        buf.put_i32(val);
460        Ok(())
461    }
462}
463
464impl Codec for Int64 {
465    fn decode(&self, buf: &[u8]) -> Result<Value, DecodeError> {
466        RawCodec::decode(buf).map(Value::Int64)
467    }
468    fn encode(&self, buf: &mut BytesMut, val: &Value) -> Result<(), EncodeError> {
469        let val = match val {
470            Value::Int64(val) => *val,
471            Value::Int32(val) => *val as i64,
472            Value::Int16(val) => *val as i64,
473            _ => Err(errors::invalid_value(type_name::<Self>(), val))?,
474        };
475        buf.reserve(8);
476        buf.put_i64(val);
477        Ok(())
478    }
479}
480
481impl Codec for ConfigMemory {
482    fn decode(&self, buf: &[u8]) -> Result<Value, DecodeError> {
483        RawCodec::decode(buf).map(Value::ConfigMemory)
484    }
485    fn encode(&self, buf: &mut BytesMut, val: &Value) -> Result<(), EncodeError> {
486        let &val = match val {
487            Value::ConfigMemory(val) => val,
488            _ => Err(errors::invalid_value(type_name::<Self>(), val))?,
489        };
490        buf.reserve(8);
491        buf.put_i64(val.0);
492        Ok(())
493    }
494}
495
496impl Codec for Float32 {
497    fn decode(&self, buf: &[u8]) -> Result<Value, DecodeError> {
498        RawCodec::decode(buf).map(Value::Float32)
499    }
500    fn encode(&self, buf: &mut BytesMut, val: &Value) -> Result<(), EncodeError> {
501        let &val = match val {
502            Value::Float32(val) => val,
503            _ => Err(errors::invalid_value(type_name::<Self>(), val))?,
504        };
505        buf.reserve(4);
506        buf.put_f32(val);
507        Ok(())
508    }
509}
510
511impl Codec for Float64 {
512    fn decode(&self, buf: &[u8]) -> Result<Value, DecodeError> {
513        RawCodec::decode(buf).map(Value::Float64)
514    }
515    fn encode(&self, buf: &mut BytesMut, val: &Value) -> Result<(), EncodeError> {
516        let val = match val {
517            Value::Float64(val) => *val,
518            Value::Float32(val) => *val as f64,
519            _ => Err(errors::invalid_value(type_name::<Self>(), val))?,
520        };
521        buf.reserve(8);
522        buf.put_f64(val);
523        Ok(())
524    }
525}
526
527impl Codec for Str {
528    fn decode(&self, buf: &[u8]) -> Result<Value, DecodeError> {
529        RawCodec::decode(buf).map(Value::Str)
530    }
531    fn encode(&self, buf: &mut BytesMut, val: &Value) -> Result<(), EncodeError> {
532        let val = match val {
533            Value::Str(val) => val,
534            _ => Err(errors::invalid_value(type_name::<Self>(), val))?,
535        };
536        buf.extend(val.as_bytes());
537        Ok(())
538    }
539}
540
541impl Codec for Bytes {
542    fn decode(&self, buf: &[u8]) -> Result<Value, DecodeError> {
543        RawCodec::decode(buf).map(Value::Bytes)
544    }
545    fn encode(&self, buf: &mut BytesMut, val: &Value) -> Result<(), EncodeError> {
546        let val = match val {
547            Value::Bytes(val) => val,
548            _ => Err(errors::invalid_value(type_name::<Self>(), val))?,
549        };
550        buf.extend(val);
551        Ok(())
552    }
553}
554
555impl Codec for Duration {
556    fn decode(&self, buf: &[u8]) -> Result<Value, DecodeError> {
557        RawCodec::decode(buf).map(Value::Duration)
558    }
559    fn encode(&self, buf: &mut BytesMut, val: &Value) -> Result<(), EncodeError> {
560        let val = match val {
561            Value::Duration(val) => val,
562            _ => Err(errors::invalid_value(type_name::<Self>(), val))?,
563        };
564        encode_duration(buf, val)
565    }
566}
567
568pub(crate) fn encode_duration(
569    buf: &mut BytesMut,
570    val: &model::Duration,
571) -> Result<(), EncodeError> {
572    buf.reserve(16);
573    buf.put_i64(val.micros);
574    buf.put_u32(0);
575    buf.put_u32(0);
576    Ok(())
577}
578
579impl Codec for RelativeDuration {
580    fn decode(&self, buf: &[u8]) -> Result<Value, DecodeError> {
581        RawCodec::decode(buf).map(Value::RelativeDuration)
582    }
583    fn encode(&self, buf: &mut BytesMut, val: &Value) -> Result<(), EncodeError> {
584        let val = match val {
585            Value::RelativeDuration(val) => val,
586            _ => Err(errors::invalid_value(type_name::<Self>(), val))?,
587        };
588        encode_relative_duration(buf, val)
589    }
590}
591
592pub(crate) fn encode_relative_duration(
593    buf: &mut BytesMut,
594    val: &model::RelativeDuration,
595) -> Result<(), EncodeError> {
596    buf.reserve(16);
597    buf.put_i64(val.micros);
598    buf.put_i32(val.days);
599    buf.put_i32(val.months);
600    Ok(())
601}
602
603impl Codec for DateDuration {
604    fn decode(&self, buf: &[u8]) -> Result<Value, DecodeError> {
605        RawCodec::decode(buf).map(Value::DateDuration)
606    }
607    fn encode(&self, buf: &mut BytesMut, val: &Value) -> Result<(), EncodeError> {
608        let val = match val {
609            Value::DateDuration(val) => val,
610            _ => Err(errors::invalid_value(type_name::<Self>(), val))?,
611        };
612        encode_date_duration(buf, val)
613    }
614}
615
616pub(crate) fn encode_date_duration(
617    buf: &mut BytesMut,
618    val: &model::DateDuration,
619) -> Result<(), EncodeError> {
620    buf.reserve(16);
621    buf.put_i64(0);
622    buf.put_i32(val.days);
623    buf.put_i32(val.months);
624    Ok(())
625}
626
627impl Codec for Uuid {
628    fn decode(&self, buf: &[u8]) -> Result<Value, DecodeError> {
629        RawCodec::decode(buf).map(Value::Uuid)
630    }
631    fn encode(&self, buf: &mut BytesMut, val: &Value) -> Result<(), EncodeError> {
632        let &val = match val {
633            Value::Uuid(val) => val,
634            _ => Err(errors::invalid_value(type_name::<Self>(), val))?,
635        };
636        buf.extend(val.as_bytes());
637        Ok(())
638    }
639}
640
641impl Codec for Nothing {
642    fn decode(&self, _buf: &[u8]) -> Result<Value, DecodeError> {
643        Ok(Value::Nothing)
644    }
645    fn encode(&self, _buf: &mut BytesMut, val: &Value) -> Result<(), EncodeError> {
646        match val {
647            Value::Nothing => Ok(()),
648            _ => Err(errors::invalid_value(type_name::<Self>(), val))?,
649        }
650    }
651}
652
653impl Object {
654    fn build(
655        d: &descriptors::ObjectShapeDescriptor,
656        dec: &CodecBuilder,
657    ) -> Result<Object, CodecError> {
658        Ok(Object {
659            shape: d.elements.as_slice().into(),
660            codecs: d
661                .elements
662                .iter()
663                .map(|e| dec.build(e.type_pos))
664                .collect::<Result<_, _>>()?,
665        })
666    }
667}
668
669impl Input {
670    fn build(
671        d: &descriptors::InputShapeTypeDescriptor,
672        dec: &CodecBuilder,
673    ) -> Result<Input, CodecError> {
674        Ok(Input {
675            shape: d.elements.as_slice().into(),
676            codecs: d
677                .elements
678                .iter()
679                .map(|e| dec.build(e.type_pos))
680                .collect::<Result<_, _>>()?,
681        })
682    }
683}
684
685impl Tuple {
686    fn build(
687        d: &descriptors::TupleTypeDescriptor,
688        dec: &CodecBuilder,
689    ) -> Result<Tuple, CodecError> {
690        Ok(Tuple {
691            elements: d
692                .element_types
693                .iter()
694                .map(|&t| dec.build(t))
695                .collect::<Result<_, _>>()?,
696        })
697    }
698}
699
700impl NamedTuple {
701    fn build(
702        d: &descriptors::NamedTupleTypeDescriptor,
703        dec: &CodecBuilder,
704    ) -> Result<NamedTuple, CodecError> {
705        Ok(NamedTuple {
706            shape: d.elements.as_slice().into(),
707            codecs: d
708                .elements
709                .iter()
710                .map(|e| dec.build(e.type_pos))
711                .collect::<Result<_, _>>()?,
712        })
713    }
714}
715
716impl SQLRow {
717    fn build(d: &descriptors::SQLRowDescriptor, dec: &CodecBuilder) -> Result<SQLRow, CodecError> {
718        Ok(SQLRow {
719            shape: d.elements.as_slice().into(),
720            codecs: d
721                .elements
722                .iter()
723                .map(|e| dec.build(e.type_pos))
724                .collect::<Result<_, _>>()?,
725        })
726    }
727}
728
729fn decode_tuple(
730    mut elements: DecodeTupleLike,
731    codecs: &[Arc<dyn Codec>],
732) -> Result<Vec<Value>, DecodeError> {
733    codecs
734        .iter()
735        .map(|codec| {
736            codec.decode(
737                elements
738                    .read()?
739                    .ok_or_else(|| errors::MissingRequiredElement.build())?,
740            )
741        })
742        .collect::<Result<Vec<Value>, DecodeError>>()
743}
744
745fn decode_object(
746    mut elements: DecodeTupleLike,
747    codecs: &[Arc<dyn Codec>],
748) -> Result<Vec<Option<Value>>, DecodeError> {
749    codecs
750        .iter()
751        .map(|codec| {
752            elements
753                .read()?
754                .map(|element| codec.decode(element))
755                .transpose()
756        })
757        .collect::<Result<Vec<Option<Value>>, DecodeError>>()
758}
759
760fn decode_array_like(
761    elements: DecodeArrayLike<'_>,
762    codec: &dyn Codec,
763) -> Result<Vec<Value>, DecodeError> {
764    elements
765        .map(|element| codec.decode(element?))
766        .collect::<Result<Vec<Value>, DecodeError>>()
767}
768
769impl Codec for Object {
770    fn decode(&self, buf: &[u8]) -> Result<Value, DecodeError> {
771        let elements = DecodeTupleLike::new_object(buf, self.codecs.len())?;
772        let fields = decode_object(elements, &self.codecs)?;
773        Ok(Value::Object {
774            shape: self.shape.clone(),
775            fields,
776        })
777    }
778    fn encode(&self, buf: &mut BytesMut, val: &Value) -> Result<(), EncodeError> {
779        let (shape, fields) = match val {
780            Value::Object { shape, fields } => (shape, fields),
781            _ => Err(errors::invalid_value(type_name::<Self>(), val))?,
782        };
783        ensure!(shape == &self.shape, errors::ObjectShapeMismatch);
784        ensure!(
785            self.codecs.len() == fields.len(),
786            errors::ObjectShapeMismatch
787        );
788        debug_assert_eq!(self.codecs.len(), shape.0.elements.len());
789        buf.reserve(4 + 8 * self.codecs.len());
790        buf.put_u32(
791            self.codecs
792                .len()
793                .try_into()
794                .ok()
795                .context(errors::TooManyElements)?,
796        );
797        for (codec, field) in self.codecs.iter().zip(fields) {
798            buf.reserve(8);
799            buf.put_u32(0);
800            match field {
801                Some(v) => {
802                    let pos = buf.len();
803                    buf.put_i32(0); // replaced after serializing a value
804                    codec.encode(buf, v)?;
805                    let len = buf.len() - pos - 4;
806                    buf[pos..pos + 4].copy_from_slice(
807                        &i32::try_from(len)
808                            .ok()
809                            .context(errors::ElementTooLong)?
810                            .to_be_bytes(),
811                    );
812                }
813                None => {
814                    buf.put_i32(-1);
815                }
816            }
817        }
818        Ok(())
819    }
820}
821
822impl Codec for Input {
823    fn decode(&self, mut buf: &[u8]) -> Result<Value, DecodeError> {
824        ensure!(buf.remaining() >= 4, errors::Underflow);
825        let count = buf.get_u32() as usize;
826        let mut fields = vec![None; self.codecs.len()];
827        for _ in 0..count {
828            ensure!(buf.remaining() >= 8, errors::Underflow);
829            let index = buf.get_u32() as usize;
830            ensure!(index < self.codecs.len(), errors::InvalidIndex { index });
831            let length = buf.get_i32();
832            if length < 0 {
833                fields[index] = Some(None);
834            } else {
835                let length = length as usize;
836                let value = self.codecs[index].decode(&buf[..length])?;
837                buf.advance(length);
838                fields[index] = Some(Some(value));
839            }
840        }
841        Ok(Value::SparseObject(SparseObject {
842            shape: self.shape.clone(),
843            fields,
844        }))
845    }
846    fn encode(&self, buf: &mut BytesMut, val: &Value) -> Result<(), EncodeError> {
847        let ob = match val {
848            Value::SparseObject(ob) => ob,
849            _ => Err(errors::invalid_value(type_name::<Self>(), val))?,
850        };
851        let mut items = Vec::with_capacity(self.codecs.len());
852        let dest_els = &self.shape.0.elements;
853        for (fld, el) in ob.fields.iter().zip(&ob.shape.0.elements) {
854            if let Some(value) = fld {
855                if let Some(index) = dest_els.iter().position(|x| x.name == el.name) {
856                    items.push((index, value));
857                }
858            }
859        }
860        buf.reserve(4 + 8 * items.len());
861        buf.put_u32(
862            items
863                .len()
864                .try_into()
865                .ok()
866                .context(errors::TooManyElements)?,
867        );
868        for (index, value) in items {
869            buf.reserve(8);
870            buf.put_u32(index as u32);
871            let pos = buf.len();
872            if let Some(value) = value {
873                buf.put_i32(0); // replaced after serializing a value
874                self.codecs[index].encode(buf, value)?;
875                let len = buf.len() - pos - 4;
876                buf[pos..pos + 4].copy_from_slice(
877                    &i32::try_from(len)
878                        .ok()
879                        .context(errors::ElementTooLong)?
880                        .to_be_bytes(),
881                );
882            } else {
883                buf.put_i32(-1);
884            }
885        }
886        Ok(())
887    }
888}
889
890impl Codec for ArrayAdapter {
891    fn decode(&self, mut buf: &[u8]) -> Result<Value, DecodeError> {
892        ensure!(buf.remaining() >= 12, errors::Underflow);
893        let count = buf.get_u32() as usize;
894        ensure!(count == 1, errors::InvalidArrayShape);
895        let _reserved = buf.get_i32() as usize;
896        let len = buf.get_i32() as usize;
897        ensure!(buf.remaining() >= len, errors::Underflow);
898        ensure!(buf.remaining() <= len, errors::ExtraData);
899        self.0.decode(buf)
900    }
901    fn encode(&self, buf: &mut BytesMut, val: &Value) -> Result<(), EncodeError> {
902        buf.reserve(12);
903        buf.put_u32(1);
904        buf.put_u32(0);
905        let pos = buf.len();
906        buf.put_i32(0); // replaced after serializing a value
907        self.0.encode(buf, val)?;
908        let len = buf.len() - pos - 4;
909        buf[pos..pos + 4].copy_from_slice(
910            &i32::try_from(len)
911                .ok()
912                .context(errors::ElementTooLong)?
913                .to_be_bytes(),
914        );
915        Ok(())
916    }
917}
918
919impl<'a> From<&'a [descriptors::ShapeElement]> for ObjectShape {
920    fn from(shape: &'a [descriptors::ShapeElement]) -> ObjectShape {
921        ObjectShape(Arc::new(ObjectShapeInfo {
922            elements: shape.iter().map(ShapeElement::from).collect(),
923        }))
924    }
925}
926
927impl<'a> From<&'a descriptors::ShapeElement> for ShapeElement {
928    fn from(e: &'a descriptors::ShapeElement) -> ShapeElement {
929        let descriptors::ShapeElement {
930            flag_implicit,
931            flag_link_property,
932            flag_link,
933            cardinality,
934            name,
935            type_pos: _,
936            source_type_pos: _,
937        } = e;
938        ShapeElement {
939            flag_implicit: *flag_implicit,
940            flag_link_property: *flag_link_property,
941            flag_link: *flag_link,
942            cardinality: *cardinality,
943            name: name.clone(),
944        }
945    }
946}
947
948impl<'a> From<&'a [descriptors::InputShapeElement]> for InputObjectShape {
949    fn from(shape: &'a [descriptors::InputShapeElement]) -> InputObjectShape {
950        InputObjectShape(Arc::new(InputObjectShapeInfo {
951            elements: shape.iter().map(InputShapeElement::from).collect(),
952        }))
953    }
954}
955
956impl<'a> From<&'a descriptors::InputShapeElement> for InputShapeElement {
957    fn from(e: &'a descriptors::InputShapeElement) -> InputShapeElement {
958        let descriptors::InputShapeElement {
959            cardinality,
960            name,
961            type_pos: _,
962        } = e;
963        InputShapeElement {
964            cardinality: *cardinality,
965            name: name.clone(),
966        }
967    }
968}
969
970impl<'a> From<&'a [descriptors::TupleElement]> for NamedTupleShape {
971    fn from(shape: &'a [descriptors::TupleElement]) -> NamedTupleShape {
972        NamedTupleShape(Arc::new(NamedTupleShapeInfo {
973            elements: shape
974                .iter()
975                .map(|e| {
976                    let descriptors::TupleElement { name, type_pos: _ } = e;
977                    TupleElement { name: name.clone() }
978                })
979                .collect(),
980        }))
981    }
982}
983
984impl<'a> From<&'a [descriptors::SQLRowElement]> for SQLRowShape {
985    fn from(shape: &'a [descriptors::SQLRowElement]) -> SQLRowShape {
986        SQLRowShape(Arc::new(SQLRowShapeInfo {
987            elements: shape
988                .iter()
989                .map(|e| {
990                    let descriptors::SQLRowElement { name, type_pos: _ } = e;
991                    SQLRowElement { name: name.clone() }
992                })
993                .collect(),
994        }))
995    }
996}
997
998impl From<&str> for EnumValue {
999    fn from(s: &str) -> EnumValue {
1000        EnumValue(s.into())
1001    }
1002}
1003
1004impl std::ops::Deref for EnumValue {
1005    type Target = str;
1006    fn deref(&self) -> &str {
1007        &self.0
1008    }
1009}
1010
1011impl Set {
1012    fn build(d: &descriptors::SetDescriptor, dec: &CodecBuilder) -> Result<Set, CodecError> {
1013        let element = match dec.descriptors.get(d.type_pos.0 as usize) {
1014            Some(Descriptor::Array(d)) => Arc::new(ArrayAdapter(Array {
1015                element: dec.build(d.type_pos)?,
1016            })),
1017            _ => dec.build(d.type_pos)?,
1018        };
1019        Ok(Set { element })
1020    }
1021}
1022
1023impl Codec for Set {
1024    fn decode(&self, buf: &[u8]) -> Result<Value, DecodeError> {
1025        let elements = DecodeArrayLike::new_set(buf)?;
1026        let items = decode_array_like(elements, &*self.element)?;
1027        Ok(Value::Set(items))
1028    }
1029    fn encode(&self, buf: &mut BytesMut, val: &Value) -> Result<(), EncodeError> {
1030        let items = match val {
1031            Value::Set(items) => items,
1032            _ => Err(errors::invalid_value(type_name::<Self>(), val))?,
1033        };
1034        if items.is_empty() {
1035            buf.reserve(12);
1036            buf.put_u32(0); // ndims
1037            buf.put_u32(0); // reserved0
1038            buf.put_u32(0); // reserved1
1039            return Ok(());
1040        }
1041        buf.reserve(20);
1042        buf.put_u32(1); // ndims
1043        buf.put_u32(0); // reserved0
1044        buf.put_u32(0); // reserved1
1045        buf.put_u32(items.len().try_into().ok().context(errors::ArrayTooLong)?);
1046        buf.put_u32(1); // lower
1047        for item in items {
1048            buf.reserve(4);
1049            let pos = buf.len();
1050            buf.put_u32(0); // replaced after serializing a value
1051            self.element.encode(buf, item)?;
1052            let len = buf.len() - pos - 4;
1053            buf[pos..pos + 4].copy_from_slice(
1054                &u32::try_from(len)
1055                    .ok()
1056                    .context(errors::ElementTooLong)?
1057                    .to_be_bytes(),
1058            );
1059        }
1060        Ok(())
1061    }
1062}
1063
1064impl Codec for Decimal {
1065    fn decode(&self, buf: &[u8]) -> Result<Value, DecodeError> {
1066        RawCodec::decode(buf).map(Value::Decimal)
1067    }
1068    fn encode(&self, buf: &mut BytesMut, val: &Value) -> Result<(), EncodeError> {
1069        let val = match val {
1070            Value::Decimal(val) => val,
1071            _ => Err(errors::invalid_value(type_name::<Self>(), val))?,
1072        };
1073        encode_decimal(buf, val)
1074    }
1075}
1076
1077pub(crate) fn encode_decimal(buf: &mut BytesMut, val: &model::Decimal) -> Result<(), EncodeError> {
1078    buf.reserve(8 + val.digits.len() * 2);
1079    buf.put_u16(
1080        val.digits
1081            .len()
1082            .try_into()
1083            .ok()
1084            .context(errors::BigIntTooLong)?,
1085    );
1086    buf.put_i16(val.weight);
1087    buf.put_u16(if val.negative { 0x4000 } else { 0x0000 });
1088    buf.put_u16(val.decimal_digits);
1089    for &dig in &val.digits {
1090        buf.put_u16(dig);
1091    }
1092    Ok(())
1093}
1094
1095impl Codec for BigInt {
1096    fn decode(&self, buf: &[u8]) -> Result<Value, DecodeError> {
1097        RawCodec::decode(buf).map(Value::BigInt)
1098    }
1099    fn encode(&self, buf: &mut BytesMut, val: &Value) -> Result<(), EncodeError> {
1100        let val = match val {
1101            Value::BigInt(val) => val,
1102            _ => Err(errors::invalid_value(type_name::<Self>(), val))?,
1103        };
1104        encode_big_int(buf, val)
1105    }
1106}
1107
1108pub(crate) fn encode_big_int(buf: &mut BytesMut, val: &model::BigInt) -> Result<(), EncodeError> {
1109    buf.reserve(8 + val.digits.len() * 2);
1110    buf.put_u16(
1111        val.digits
1112            .len()
1113            .try_into()
1114            .ok()
1115            .context(errors::BigIntTooLong)?,
1116    );
1117    buf.put_i16(val.weight);
1118    buf.put_u16(if val.negative { 0x4000 } else { 0x0000 });
1119    buf.put_u16(0);
1120    for &dig in &val.digits {
1121        buf.put_u16(dig);
1122    }
1123    Ok(())
1124}
1125
1126impl Codec for Bool {
1127    fn decode(&self, buf: &[u8]) -> Result<Value, DecodeError> {
1128        RawCodec::decode(buf).map(Value::Bool)
1129    }
1130    fn encode(&self, buf: &mut BytesMut, val: &Value) -> Result<(), EncodeError> {
1131        let val = match val {
1132            Value::Bool(val) => val,
1133            _ => Err(errors::invalid_value(type_name::<Self>(), val))?,
1134        };
1135        buf.reserve(1);
1136        buf.put_u8(match val {
1137            true => 1,
1138            false => 0,
1139        });
1140        Ok(())
1141    }
1142}
1143
1144impl Codec for Datetime {
1145    fn decode(&self, buf: &[u8]) -> Result<Value, DecodeError> {
1146        RawCodec::decode(buf).map(Value::Datetime)
1147    }
1148    fn encode(&self, buf: &mut BytesMut, val: &Value) -> Result<(), EncodeError> {
1149        let val = match val {
1150            Value::Datetime(val) => val,
1151            _ => Err(errors::invalid_value(type_name::<Self>(), val))?,
1152        };
1153        encode_datetime(buf, val)
1154    }
1155}
1156
1157pub(crate) fn encode_datetime(
1158    buf: &mut BytesMut,
1159    val: &model::Datetime,
1160) -> Result<(), EncodeError> {
1161    buf.reserve(8);
1162    buf.put_i64(val.micros);
1163    Ok(())
1164}
1165
1166impl Codec for LocalDatetime {
1167    fn decode(&self, buf: &[u8]) -> Result<Value, DecodeError> {
1168        RawCodec::decode(buf).map(Value::LocalDatetime)
1169    }
1170    fn encode(&self, buf: &mut BytesMut, val: &Value) -> Result<(), EncodeError> {
1171        let val = match val {
1172            Value::LocalDatetime(val) => val,
1173            _ => Err(errors::invalid_value(type_name::<Self>(), val))?,
1174        };
1175        encode_local_datetime(buf, val)
1176    }
1177}
1178
1179pub(crate) fn encode_local_datetime(
1180    buf: &mut BytesMut,
1181    val: &model::LocalDatetime,
1182) -> Result<(), EncodeError> {
1183    buf.reserve(8);
1184    buf.put_i64(val.micros);
1185    Ok(())
1186}
1187
1188impl Codec for LocalDate {
1189    fn decode(&self, buf: &[u8]) -> Result<Value, DecodeError> {
1190        RawCodec::decode(buf).map(Value::LocalDate)
1191    }
1192    fn encode(&self, buf: &mut BytesMut, val: &Value) -> Result<(), EncodeError> {
1193        let val = match val {
1194            Value::LocalDate(val) => val,
1195            _ => Err(errors::invalid_value(type_name::<Self>(), val))?,
1196        };
1197        encode_local_date(buf, val)
1198    }
1199}
1200
1201pub(crate) fn encode_local_date(
1202    buf: &mut BytesMut,
1203    val: &model::LocalDate,
1204) -> Result<(), EncodeError> {
1205    buf.reserve(4);
1206    buf.put_i32(val.days);
1207    Ok(())
1208}
1209
1210impl Codec for LocalTime {
1211    fn decode(&self, buf: &[u8]) -> Result<Value, DecodeError> {
1212        RawCodec::decode(buf).map(Value::LocalTime)
1213    }
1214    fn encode(&self, buf: &mut BytesMut, val: &Value) -> Result<(), EncodeError> {
1215        let val = match val {
1216            Value::LocalTime(val) => val,
1217            _ => Err(errors::invalid_value(type_name::<Self>(), val))?,
1218        };
1219        encode_local_time(buf, val)
1220    }
1221}
1222
1223pub(crate) fn encode_local_time(
1224    buf: &mut BytesMut,
1225    val: &model::LocalTime,
1226) -> Result<(), EncodeError> {
1227    buf.reserve(8);
1228    buf.put_i64(val.micros as i64);
1229    Ok(())
1230}
1231
1232impl Codec for Json {
1233    fn decode(&self, buf: &[u8]) -> Result<Value, DecodeError> {
1234        RawCodec::decode(buf).map(|json: model::Json| Value::Json(json))
1235    }
1236    fn encode(&self, buf: &mut BytesMut, val: &Value) -> Result<(), EncodeError> {
1237        let val = match val {
1238            Value::Json(val) => val,
1239            _ => Err(errors::invalid_value(type_name::<Self>(), val))?,
1240        };
1241        buf.reserve(1 + val.len());
1242        buf.put_u8(1);
1243        buf.extend(val.as_bytes());
1244        Ok(())
1245    }
1246}
1247
1248impl Codec for PgTextJson {
1249    fn decode(&self, buf: &[u8]) -> Result<Value, DecodeError> {
1250        let val = str::from_utf8(buf).context(errors::InvalidUtf8)?.to_owned();
1251        let json = model::Json::new_unchecked(val);
1252        Ok(Value::Json(json))
1253    }
1254    fn encode(&self, buf: &mut BytesMut, val: &Value) -> Result<(), EncodeError> {
1255        let val = match val {
1256            Value::Json(val) => val,
1257            _ => Err(errors::invalid_value(type_name::<Self>(), val))?,
1258        };
1259        buf.reserve(val.len());
1260        buf.extend(val.as_bytes());
1261        Ok(())
1262    }
1263}
1264
1265impl Codec for Scalar {
1266    fn decode(&self, buf: &[u8]) -> Result<Value, DecodeError> {
1267        self.inner.decode(buf)
1268    }
1269    fn encode(&self, buf: &mut BytesMut, val: &Value) -> Result<(), EncodeError> {
1270        self.inner.encode(buf, val)
1271    }
1272}
1273
1274impl Codec for Tuple {
1275    fn decode(&self, buf: &[u8]) -> Result<Value, DecodeError> {
1276        let elements = DecodeTupleLike::new_object(buf, self.elements.len())?;
1277        let items = decode_tuple(elements, &self.elements)?;
1278        Ok(Value::Tuple(items))
1279    }
1280    fn encode(&self, buf: &mut BytesMut, val: &Value) -> Result<(), EncodeError> {
1281        let items = match val {
1282            Value::Tuple(items) => items,
1283            _ => Err(errors::invalid_value(type_name::<Self>(), val))?,
1284        };
1285        ensure!(
1286            self.elements.len() == items.len(),
1287            errors::TupleShapeMismatch
1288        );
1289        buf.reserve(4 + 8 * self.elements.len());
1290        buf.put_u32(
1291            self.elements
1292                .len()
1293                .try_into()
1294                .ok()
1295                .context(errors::TooManyElements)?,
1296        );
1297        for (codec, item) in self.elements.iter().zip(items) {
1298            buf.reserve(8);
1299            buf.put_u32(0);
1300            let pos = buf.len();
1301            buf.put_u32(0); // replaced after serializing a value
1302            codec.encode(buf, item)?;
1303            let len = buf.len() - pos - 4;
1304            buf[pos..pos + 4].copy_from_slice(
1305                &u32::try_from(len)
1306                    .ok()
1307                    .context(errors::ElementTooLong)?
1308                    .to_be_bytes(),
1309            );
1310        }
1311        Ok(())
1312    }
1313}
1314
1315impl Codec for NamedTuple {
1316    fn decode(&self, buf: &[u8]) -> Result<Value, DecodeError> {
1317        let elements = DecodeTupleLike::new_tuple(buf, self.codecs.len())?;
1318        let fields = decode_tuple(elements, &self.codecs)?;
1319        Ok(Value::NamedTuple {
1320            shape: self.shape.clone(),
1321            fields,
1322        })
1323    }
1324    fn encode(&self, buf: &mut BytesMut, val: &Value) -> Result<(), EncodeError> {
1325        let (shape, fields) = match val {
1326            Value::NamedTuple { shape, fields } => (shape, fields),
1327            _ => Err(errors::invalid_value(type_name::<Self>(), val))?,
1328        };
1329        ensure!(shape == &self.shape, errors::TupleShapeMismatch);
1330        ensure!(
1331            self.codecs.len() == fields.len(),
1332            errors::ObjectShapeMismatch
1333        );
1334        debug_assert_eq!(self.codecs.len(), shape.0.elements.len());
1335        buf.reserve(4 + 8 * self.codecs.len());
1336        buf.put_u32(
1337            self.codecs
1338                .len()
1339                .try_into()
1340                .ok()
1341                .context(errors::TooManyElements)?,
1342        );
1343        for (codec, field) in self.codecs.iter().zip(fields) {
1344            buf.reserve(8);
1345            buf.put_u32(0);
1346            let pos = buf.len();
1347            buf.put_u32(0); // replaced after serializing a value
1348            codec.encode(buf, field)?;
1349            let len = buf.len() - pos - 4;
1350            buf[pos..pos + 4].copy_from_slice(
1351                &u32::try_from(len)
1352                    .ok()
1353                    .context(errors::ElementTooLong)?
1354                    .to_be_bytes(),
1355            );
1356        }
1357        Ok(())
1358    }
1359}
1360
1361impl Codec for SQLRow {
1362    fn decode(&self, buf: &[u8]) -> Result<Value, DecodeError> {
1363        let elements = DecodeTupleLike::new_object(buf, self.codecs.len())?;
1364        let fields = decode_object(elements, &self.codecs)?;
1365        Ok(Value::SQLRow {
1366            shape: self.shape.clone(),
1367            fields,
1368        })
1369    }
1370    fn encode(&self, _buf: &mut BytesMut, _val: &Value) -> Result<(), EncodeError> {
1371        errors::UnknownMessageCantBeEncoded.fail()?
1372    }
1373}
1374
1375impl Codec for Array {
1376    fn decode(&self, buf: &[u8]) -> Result<Value, DecodeError> {
1377        let elements = DecodeArrayLike::new_array(buf)?;
1378        let items = decode_array_like(elements, &*self.element)?;
1379        Ok(Value::Array(items))
1380    }
1381    fn encode(&self, buf: &mut BytesMut, val: &Value) -> Result<(), EncodeError> {
1382        let items = match val {
1383            Value::Array(items) => items,
1384            _ => Err(errors::invalid_value(type_name::<Self>(), val))?,
1385        };
1386        if items.is_empty() {
1387            // Encoding with the short form causes errors in server < 7
1388            buf.reserve(20);
1389            buf.put_u32(1); // ndims
1390            buf.put_u32(0); // reserved0
1391            buf.put_u32(0); // reserved1
1392            buf.put_u32(0);
1393            buf.put_u32(1);
1394            return Ok(());
1395        }
1396        buf.reserve(20);
1397        buf.put_u32(1); // ndims
1398        buf.put_u32(0); // reserved0
1399        buf.put_u32(0); // reserved1
1400        buf.put_u32(items.len().try_into().ok().context(errors::ArrayTooLong)?);
1401        buf.put_u32(1); // lower
1402        for item in items {
1403            buf.reserve(4);
1404            let pos = buf.len();
1405            buf.put_u32(0); // replaced after serializing a value
1406            self.element.encode(buf, item)?;
1407            let len = buf.len() - pos - 4;
1408            buf[pos..pos + 4].copy_from_slice(
1409                &u32::try_from(len)
1410                    .ok()
1411                    .context(errors::ElementTooLong)?
1412                    .to_be_bytes(),
1413            );
1414        }
1415        Ok(())
1416    }
1417}
1418
1419impl Codec for Vector {
1420    fn decode(&self, mut buf: &[u8]) -> Result<Value, DecodeError> {
1421        ensure!(buf.remaining() >= 4, errors::Underflow);
1422        let length = buf.get_u16() as usize;
1423        let _reserved = buf.get_u16();
1424        ensure!(buf.remaining() >= length * 4, errors::Underflow);
1425        let vec = (0..length).map(|_| f32::from_bits(buf.get_u32())).collect();
1426        Ok(Value::Vector(vec))
1427    }
1428    fn encode(&self, buf: &mut BytesMut, val: &Value) -> Result<(), EncodeError> {
1429        let items = match val {
1430            Value::Vector(items) => items,
1431            _ => Err(errors::invalid_value(type_name::<Self>(), val))?,
1432        };
1433        if items.is_empty() {
1434            buf.reserve(4);
1435            buf.put_i16(0); // length
1436            buf.put_i16(0); // reserved
1437            return Ok(());
1438        }
1439        buf.reserve(4 + items.len() * 4);
1440        buf.put_i16(items.len().try_into().ok().context(errors::ArrayTooLong)?);
1441        buf.put_i16(0); // reserved
1442        for item in items {
1443            buf.put_u32(item.to_bits());
1444        }
1445        Ok(())
1446    }
1447}
1448
1449impl Codec for Range {
1450    fn decode(&self, mut buf: &[u8]) -> Result<Value, DecodeError> {
1451        ensure!(buf.remaining() >= 1, errors::Underflow);
1452        let flags = buf.get_u8() as usize;
1453
1454        let empty = (flags & range::EMPTY) != 0;
1455        let inc_lower = (flags & range::LB_INC) != 0;
1456        let inc_upper = (flags & range::UB_INC) != 0;
1457        let has_lower = (flags & (range::EMPTY | range::LB_INF)) == 0;
1458        let has_upper = (flags & (range::EMPTY | range::UB_INF)) == 0;
1459
1460        let mut range = DecodeRange::new(buf)?;
1461
1462        let lower = if has_lower {
1463            Some(Box::new(self.element.decode(range.read()?)?))
1464        } else {
1465            None
1466        };
1467        let upper = if has_upper {
1468            Some(Box::new(self.element.decode(range.read()?)?))
1469        } else {
1470            None
1471        };
1472
1473        Ok(Value::Range(model::Range {
1474            lower,
1475            upper,
1476            inc_lower,
1477            inc_upper,
1478            empty,
1479        }))
1480    }
1481    fn encode(&self, buf: &mut BytesMut, val: &Value) -> Result<(), EncodeError> {
1482        let rng = match val {
1483            Value::Range(rng) => rng,
1484            _ => Err(errors::invalid_value(type_name::<Self>(), val))?,
1485        };
1486
1487        let flags = if rng.empty {
1488            range::EMPTY
1489        } else {
1490            (if rng.inc_lower { range::LB_INC } else { 0 })
1491                | (if rng.inc_upper { range::UB_INC } else { 0 })
1492                | (if rng.lower.is_none() {
1493                    range::LB_INF
1494                } else {
1495                    0
1496                })
1497                | (if rng.upper.is_none() {
1498                    range::UB_INF
1499                } else {
1500                    0
1501                })
1502        };
1503        buf.reserve(1);
1504        buf.put_u8(flags as u8);
1505
1506        if let Some(lower) = &rng.lower {
1507            let pos = buf.len();
1508            buf.reserve(4);
1509            buf.put_u32(0); // replaced after serializing a value
1510            self.element.encode(buf, lower)?;
1511            let len = buf.len() - pos - 4;
1512            buf[pos..pos + 4].copy_from_slice(
1513                &u32::try_from(len)
1514                    .ok()
1515                    .context(errors::ElementTooLong)?
1516                    .to_be_bytes(),
1517            );
1518        }
1519
1520        if let Some(upper) = &rng.upper {
1521            let pos = buf.len();
1522            buf.reserve(4);
1523            buf.put_u32(0); // replaced after serializing a value
1524            self.element.encode(buf, upper)?;
1525            let len = buf.len() - pos - 4;
1526            buf[pos..pos + 4].copy_from_slice(
1527                &u32::try_from(len)
1528                    .ok()
1529                    .context(errors::ElementTooLong)?
1530                    .to_be_bytes(),
1531            );
1532        }
1533
1534        Ok(())
1535    }
1536}
1537
1538impl Codec for MultiRange {
1539    fn decode(&self, buf: &[u8]) -> Result<Value, DecodeError> {
1540        let elements = DecodeArrayLike::new_tuple_header(buf)?;
1541        let items = decode_array_like(elements, &*self.element)?;
1542        Ok(Value::Array(items))
1543    }
1544
1545    fn encode(&self, buf: &mut BytesMut, val: &Value) -> Result<(), EncodeError> {
1546        let items = match val {
1547            Value::Array(items) => items,
1548            _ => Err(errors::invalid_value(type_name::<Self>(), val))?,
1549        };
1550        buf.reserve(4);
1551        buf.put_u32(items.len().try_into().ok().context(errors::ArrayTooLong)?);
1552        for item in items {
1553            buf.reserve(4);
1554            let pos = buf.len();
1555            buf.put_u32(0); // replaced after serializing a value
1556            self.element.encode(buf, item)?;
1557            let len = buf.len() - pos - 4;
1558            buf[pos..pos + 4].copy_from_slice(
1559                &u32::try_from(len)
1560                    .ok()
1561                    .context(errors::ElementTooLong)?
1562                    .to_be_bytes(),
1563            );
1564        }
1565        Ok(())
1566    }
1567}
1568
1569impl Codec for Enum {
1570    fn decode(&self, buf: &[u8]) -> Result<Value, DecodeError> {
1571        let val: &str = RawCodec::decode(buf)?;
1572        let val = self.members.get(val).context(errors::ExtraEnumValue)?;
1573        Ok(Value::Enum(EnumValue(val.clone())))
1574    }
1575    fn encode(&self, buf: &mut BytesMut, val: &Value) -> Result<(), EncodeError> {
1576        let val = match val {
1577            Value::Enum(val) => val.0.as_ref(),
1578            Value::Str(val) => val.as_str(),
1579            _ => Err(errors::invalid_value(type_name::<Self>(), val))?,
1580        };
1581        ensure!(self.members.contains(val), errors::MissingEnumValue);
1582        buf.extend(val.as_bytes());
1583        Ok(())
1584    }
1585}
1586
1587impl Codec for PostGisGeometry {
1588    fn decode(&self, buf: &[u8]) -> Result<Value, DecodeError> {
1589        RawCodec::decode(buf).map(Value::PostGisGeometry)
1590    }
1591    fn encode(&self, buf: &mut BytesMut, val: &Value) -> Result<(), EncodeError> {
1592        let val = match val {
1593            Value::PostGisGeometry(val) => val,
1594            _ => Err(errors::invalid_value(type_name::<Self>(), val))?,
1595        };
1596        buf.extend(val);
1597        Ok(())
1598    }
1599}
1600
1601impl Codec for PostGisGeography {
1602    fn decode(&self, buf: &[u8]) -> Result<Value, DecodeError> {
1603        RawCodec::decode(buf).map(Value::PostGisGeography)
1604    }
1605    fn encode(&self, buf: &mut BytesMut, val: &Value) -> Result<(), EncodeError> {
1606        let val = match val {
1607            Value::PostGisGeography(val) => val,
1608            _ => Err(errors::invalid_value(type_name::<Self>(), val))?,
1609        };
1610        buf.extend(val);
1611        Ok(())
1612    }
1613}
1614
1615impl Codec for PostGisBox2d {
1616    fn decode(&self, buf: &[u8]) -> Result<Value, DecodeError> {
1617        RawCodec::decode(buf).map(Value::PostGisBox2d)
1618    }
1619    fn encode(&self, buf: &mut BytesMut, val: &Value) -> Result<(), EncodeError> {
1620        let val = match val {
1621            Value::PostGisBox2d(val) => val,
1622            _ => Err(errors::invalid_value(type_name::<Self>(), val))?,
1623        };
1624        buf.extend(val);
1625        Ok(())
1626    }
1627}
1628
1629impl Codec for PostGisBox3d {
1630    fn decode(&self, buf: &[u8]) -> Result<Value, DecodeError> {
1631        RawCodec::decode(buf).map(Value::PostGisBox3d)
1632    }
1633    fn encode(&self, buf: &mut BytesMut, val: &Value) -> Result<(), EncodeError> {
1634        let val = match val {
1635            Value::PostGisBox3d(val) => val,
1636            _ => Err(errors::invalid_value(type_name::<Self>(), val))?,
1637        };
1638        buf.extend(val);
1639        Ok(())
1640    }
1641}