gel_protocol/serialization/decode/
raw_scalar.rs

1use std::convert::TryInto;
2use std::mem::size_of;
3use std::str;
4use std::time::SystemTime;
5
6use bytes::{Buf, BufMut, Bytes};
7use gel_errors::{ClientEncodingError, Error, ErrorKind};
8use snafu::{ensure, ResultExt};
9
10use crate::codec;
11use crate::descriptors::{Descriptor, TypePos};
12use crate::errors::{self, DecodeError};
13use crate::model::{range, Vector, VectorRef};
14use crate::model::{BigInt, Decimal};
15use crate::model::{ConfigMemory, Range};
16use crate::model::{DateDuration, RelativeDuration};
17use crate::model::{Datetime, Duration, LocalDate, LocalDatetime, LocalTime};
18use crate::model::{Json, Uuid};
19use crate::query_arg::{DescriptorContext, Encoder, ScalarArg};
20use crate::serialization::decode::queryable::scalars::DecodeScalar;
21use crate::value::{EnumValue, Value};
22
23pub trait RawCodec<'t>: Sized {
24    fn decode(buf: &'t [u8]) -> Result<Self, DecodeError>;
25}
26
27fn ensure_exact_size(buf: &[u8], expected_size: usize) -> Result<(), DecodeError> {
28    if buf.len() != expected_size {
29        if buf.len() < expected_size {
30            return errors::Underflow.fail();
31        } else {
32            return errors::ExtraData.fail();
33        }
34    }
35    Ok(())
36}
37
38impl RawCodec<'_> for String {
39    fn decode(buf: &[u8]) -> Result<Self, DecodeError> {
40        <&str>::decode(buf).map(|s| s.to_owned())
41    }
42}
43
44fn check_scalar(
45    ctx: &DescriptorContext,
46    type_pos: TypePos,
47    type_id: Uuid,
48    name: &str,
49) -> Result<(), Error> {
50    use crate::descriptors::Descriptor::{BaseScalar, Scalar};
51    let desc = ctx.get(type_pos)?;
52    match desc {
53        Scalar(scalar) if scalar.base_type_pos.is_some() => {
54            return check_scalar(ctx, scalar.base_type_pos.unwrap(), type_id, name);
55        }
56        Scalar(scalar) if ctx.proto.is_2() && *scalar.id == type_id => {
57            return Ok(());
58        }
59        BaseScalar(base) if *base.id == type_id => {
60            return Ok(());
61        }
62        _ => {}
63    }
64    Err(ctx.wrong_type(desc, name))
65}
66
67impl ScalarArg for String {
68    fn encode(&self, encoder: &mut Encoder) -> Result<(), Error> {
69        encoder.buf.extend(self.as_bytes());
70        Ok(())
71    }
72    fn check_descriptor(ctx: &DescriptorContext, pos: TypePos) -> Result<(), Error> {
73        check_scalar(ctx, pos, Self::uuid(), Self::typename())
74    }
75    fn to_value(&self) -> Result<Value, Error> {
76        Ok(Value::Str(self.clone()))
77    }
78}
79
80impl ScalarArg for &'_ str {
81    fn encode(&self, encoder: &mut Encoder) -> Result<(), Error> {
82        encoder.buf.extend(self.as_bytes());
83        Ok(())
84    }
85    fn check_descriptor(ctx: &DescriptorContext, pos: TypePos) -> Result<(), Error> {
86        // special case: &str can express an enum variant
87        if let Descriptor::Enumeration(_) = ctx.get(pos)? {
88            return Ok(());
89        }
90
91        check_scalar(ctx, pos, String::uuid(), String::typename())
92    }
93    fn to_value(&self) -> Result<Value, Error> {
94        Ok(Value::Str(self.to_string()))
95    }
96}
97
98impl<'t> RawCodec<'t> for &'t str {
99    fn decode(buf: &'t [u8]) -> Result<Self, DecodeError> {
100        let val = str::from_utf8(buf).context(errors::InvalidUtf8)?;
101        Ok(val)
102    }
103}
104
105impl ScalarArg for Json {
106    fn encode(&self, encoder: &mut Encoder) -> Result<(), Error> {
107        encoder.buf.reserve(self.len() + 1);
108        encoder.buf.put_u8(1);
109        encoder.buf.extend(self.as_bytes());
110        Ok(())
111    }
112    fn check_descriptor(ctx: &DescriptorContext, pos: TypePos) -> Result<(), Error> {
113        check_scalar(ctx, pos, Json::uuid(), Json::typename())
114    }
115    fn to_value(&self) -> Result<Value, Error> {
116        Ok(Value::Json(self.clone()))
117    }
118}
119
120impl RawCodec<'_> for Json {
121    fn decode(mut buf: &[u8]) -> Result<Self, DecodeError> {
122        ensure!(buf.remaining() >= 1, errors::Underflow);
123        let format = buf.get_u8();
124        ensure!(format == 1, errors::InvalidJsonFormat);
125        let val = str::from_utf8(buf).context(errors::InvalidUtf8)?.to_owned();
126        Ok(Json::new_unchecked(val))
127    }
128}
129
130impl RawCodec<'_> for Uuid {
131    fn decode(buf: &[u8]) -> Result<Self, DecodeError> {
132        ensure_exact_size(buf, 16)?;
133        let uuid = Uuid::from_slice(buf).unwrap();
134        Ok(uuid)
135    }
136}
137
138impl ScalarArg for Uuid {
139    fn encode(&self, encoder: &mut Encoder) -> Result<(), Error> {
140        encoder.buf.reserve(16);
141        encoder.buf.extend(self.as_bytes());
142        Ok(())
143    }
144    fn check_descriptor(ctx: &DescriptorContext, pos: TypePos) -> Result<(), Error> {
145        check_scalar(ctx, pos, Self::uuid(), Self::typename())
146    }
147    fn to_value(&self) -> Result<Value, Error> {
148        Ok(Value::Uuid(*self))
149    }
150}
151
152impl RawCodec<'_> for bool {
153    fn decode(buf: &[u8]) -> Result<Self, DecodeError> {
154        ensure_exact_size(buf, 1)?;
155        let res = match buf[0] {
156            0x00 => false,
157            0x01 => true,
158            v => errors::InvalidBool { val: v }.fail()?,
159        };
160        Ok(res)
161    }
162}
163
164impl ScalarArg for bool {
165    fn encode(&self, encoder: &mut Encoder) -> Result<(), Error> {
166        encoder.buf.reserve(1);
167        encoder.buf.put_u8(match self {
168            false => 0x00,
169            true => 0x01,
170        });
171        Ok(())
172    }
173    fn check_descriptor(ctx: &DescriptorContext, pos: TypePos) -> Result<(), Error> {
174        check_scalar(ctx, pos, Self::uuid(), Self::typename())
175    }
176    fn to_value(&self) -> Result<Value, Error> {
177        Ok(Value::Bool(*self))
178    }
179}
180
181impl RawCodec<'_> for i16 {
182    fn decode(mut buf: &[u8]) -> Result<Self, DecodeError> {
183        ensure_exact_size(buf, size_of::<Self>())?;
184        Ok(buf.get_i16())
185    }
186}
187
188impl ScalarArg for i16 {
189    fn encode(&self, encoder: &mut Encoder) -> Result<(), Error> {
190        encoder.buf.reserve(2);
191        encoder.buf.put_i16(*self);
192        Ok(())
193    }
194    fn check_descriptor(ctx: &DescriptorContext, pos: TypePos) -> Result<(), Error> {
195        check_scalar(ctx, pos, Self::uuid(), Self::typename())
196    }
197    fn to_value(&self) -> Result<Value, Error> {
198        Ok(Value::Int16(*self))
199    }
200}
201
202impl RawCodec<'_> for i32 {
203    fn decode(mut buf: &[u8]) -> Result<Self, DecodeError> {
204        ensure_exact_size(buf, size_of::<Self>())?;
205        Ok(buf.get_i32())
206    }
207}
208
209impl ScalarArg for i32 {
210    fn encode(&self, encoder: &mut Encoder) -> Result<(), Error> {
211        encoder.buf.reserve(4);
212        encoder.buf.put_i32(*self);
213        Ok(())
214    }
215    fn check_descriptor(ctx: &DescriptorContext, pos: TypePos) -> Result<(), Error> {
216        check_scalar(ctx, pos, Self::uuid(), Self::typename())
217    }
218    fn to_value(&self) -> Result<Value, Error> {
219        Ok(Value::Int32(*self))
220    }
221}
222
223impl RawCodec<'_> for i64 {
224    fn decode(mut buf: &[u8]) -> Result<Self, DecodeError> {
225        ensure_exact_size(buf, size_of::<Self>())?;
226        Ok(buf.get_i64())
227    }
228}
229
230impl RawCodec<'_> for ConfigMemory {
231    fn decode(mut buf: &[u8]) -> Result<Self, DecodeError> {
232        ensure_exact_size(buf, size_of::<Self>())?;
233        Ok(ConfigMemory(buf.get_i64()))
234    }
235}
236
237impl ScalarArg for i64 {
238    fn encode(&self, encoder: &mut Encoder) -> Result<(), Error> {
239        encoder.buf.reserve(8);
240        encoder.buf.put_i64(*self);
241        Ok(())
242    }
243    fn check_descriptor(ctx: &DescriptorContext, pos: TypePos) -> Result<(), Error> {
244        check_scalar(ctx, pos, Self::uuid(), Self::typename())
245    }
246    fn to_value(&self) -> Result<Value, Error> {
247        Ok(Value::Int64(*self))
248    }
249}
250
251impl RawCodec<'_> for f32 {
252    fn decode(mut buf: &[u8]) -> Result<Self, DecodeError> {
253        ensure_exact_size(buf, size_of::<Self>())?;
254        Ok(buf.get_f32())
255    }
256}
257
258impl ScalarArg for f32 {
259    fn encode(&self, encoder: &mut Encoder) -> Result<(), Error> {
260        encoder.buf.reserve(4);
261        encoder.buf.put_f32(*self);
262        Ok(())
263    }
264    fn check_descriptor(ctx: &DescriptorContext, pos: TypePos) -> Result<(), Error> {
265        check_scalar(ctx, pos, Self::uuid(), Self::typename())
266    }
267    fn to_value(&self) -> Result<Value, Error> {
268        Ok(Value::Float32(*self))
269    }
270}
271
272impl RawCodec<'_> for f64 {
273    fn decode(mut buf: &[u8]) -> Result<Self, DecodeError> {
274        ensure_exact_size(buf, size_of::<Self>())?;
275        Ok(buf.get_f64())
276    }
277}
278
279impl ScalarArg for f64 {
280    fn encode(&self, encoder: &mut Encoder) -> Result<(), Error> {
281        encoder.buf.reserve(8);
282        encoder.buf.put_f64(*self);
283        Ok(())
284    }
285    fn check_descriptor(ctx: &DescriptorContext, pos: TypePos) -> Result<(), Error> {
286        check_scalar(ctx, pos, Self::uuid(), Self::typename())
287    }
288    fn to_value(&self) -> Result<Value, Error> {
289        Ok(Value::Float64(*self))
290    }
291}
292
293impl<'t> RawCodec<'t> for &'t [u8] {
294    fn decode(buf: &'t [u8]) -> Result<Self, DecodeError> {
295        Ok(buf)
296    }
297}
298
299impl ScalarArg for &'_ [u8] {
300    fn encode(&self, encoder: &mut Encoder) -> Result<(), Error> {
301        encoder.buf.extend(*self);
302        Ok(())
303    }
304    fn check_descriptor(ctx: &DescriptorContext, pos: TypePos) -> Result<(), Error> {
305        check_scalar(ctx, pos, codec::STD_BYTES, "std::bytes")
306    }
307    fn to_value(&self) -> Result<Value, Error> {
308        Ok(Value::Bytes(Bytes::copy_from_slice(self)))
309    }
310}
311
312impl RawCodec<'_> for Bytes {
313    fn decode(buf: &[u8]) -> Result<Self, DecodeError> {
314        Ok(Bytes::copy_from_slice(buf))
315    }
316}
317
318impl ScalarArg for Bytes {
319    fn encode(&self, encoder: &mut Encoder) -> Result<(), Error> {
320        encoder.buf.extend(&self[..]);
321        Ok(())
322    }
323    fn check_descriptor(ctx: &DescriptorContext, pos: TypePos) -> Result<(), Error> {
324        check_scalar(ctx, pos, codec::STD_BYTES, "std::bytes")
325    }
326    fn to_value(&self) -> Result<Value, Error> {
327        Ok(Value::Bytes(self.clone()))
328    }
329}
330
331impl ScalarArg for ConfigMemory {
332    fn encode(&self, encoder: &mut Encoder) -> Result<(), Error> {
333        encoder.buf.reserve(8);
334        encoder.buf.put_i64(self.0);
335        Ok(())
336    }
337    fn check_descriptor(ctx: &DescriptorContext, pos: TypePos) -> Result<(), Error> {
338        check_scalar(ctx, pos, Self::uuid(), Self::typename())
339    }
340    fn to_value(&self) -> Result<Value, Error> {
341        Ok(Value::ConfigMemory(*self))
342    }
343}
344
345impl RawCodec<'_> for Decimal {
346    fn decode(mut buf: &[u8]) -> Result<Self, DecodeError> {
347        ensure!(buf.remaining() >= 8, errors::Underflow);
348        let ndigits = buf.get_u16() as usize;
349        let weight = buf.get_i16();
350        let negative = match buf.get_u16() {
351            0x0000 => false,
352            0x4000 => true,
353            _ => errors::BadSign.fail()?,
354        };
355        let decimal_digits = buf.get_u16();
356        ensure_exact_size(buf, ndigits * 2)?;
357        let mut digits = Vec::with_capacity(ndigits);
358        for _ in 0..ndigits {
359            digits.push(buf.get_u16());
360        }
361        Ok(Decimal {
362            negative,
363            weight,
364            decimal_digits,
365            digits,
366        })
367    }
368}
369
370#[cfg(feature = "bigdecimal")]
371impl RawCodec<'_> for bigdecimal::BigDecimal {
372    fn decode(buf: &[u8]) -> Result<Self, DecodeError> {
373        let dec: Decimal = RawCodec::decode(buf)?;
374        Ok(dec.into())
375    }
376}
377
378impl ScalarArg for Decimal {
379    fn encode(&self, encoder: &mut Encoder) -> Result<(), Error> {
380        codec::encode_decimal(encoder.buf, self).map_err(ClientEncodingError::with_source)
381    }
382    fn check_descriptor(ctx: &DescriptorContext, pos: TypePos) -> Result<(), Error> {
383        check_scalar(ctx, pos, Self::uuid(), Self::typename())
384    }
385    fn to_value(&self) -> Result<Value, Error> {
386        Ok(Value::Decimal(self.clone()))
387    }
388}
389
390#[cfg(feature = "num-bigint")]
391impl RawCodec<'_> for num_bigint::BigInt {
392    fn decode(buf: &[u8]) -> Result<Self, DecodeError> {
393        let dec: BigInt = RawCodec::decode(buf)?;
394        Ok(dec.into())
395    }
396}
397
398#[cfg(feature = "bigdecimal")]
399impl ScalarArg for bigdecimal::BigDecimal {
400    fn encode(&self, encoder: &mut Encoder) -> Result<(), Error> {
401        let val = self.clone().try_into().map_err(|e| {
402            ClientEncodingError::with_source(e).context("cannot serialize BigDecimal value")
403        })?;
404        codec::encode_decimal(encoder.buf, &val).map_err(ClientEncodingError::with_source)
405    }
406    fn check_descriptor(ctx: &DescriptorContext, pos: TypePos) -> Result<(), Error> {
407        check_scalar(ctx, pos, Self::uuid(), Self::typename())
408    }
409    fn to_value(&self) -> Result<Value, Error> {
410        Ok(Value::Decimal(
411            self.clone()
412                .try_into()
413                .map_err(ClientEncodingError::with_source)?,
414        ))
415    }
416}
417
418impl RawCodec<'_> for BigInt {
419    fn decode(mut buf: &[u8]) -> Result<Self, DecodeError> {
420        ensure!(buf.remaining() >= 8, errors::Underflow);
421        let ndigits = buf.get_u16() as usize;
422        let weight = buf.get_i16();
423        let negative = match buf.get_u16() {
424            0x0000 => false,
425            0x4000 => true,
426            _ => errors::BadSign.fail()?,
427        };
428        let decimal_digits = buf.get_u16();
429        ensure!(decimal_digits == 0, errors::NonZeroReservedBytes);
430        let mut digits = Vec::with_capacity(ndigits);
431        ensure_exact_size(buf, ndigits * 2)?;
432        for _ in 0..ndigits {
433            digits.push(buf.get_u16());
434        }
435        Ok(BigInt {
436            negative,
437            weight,
438            digits,
439        })
440    }
441}
442
443impl ScalarArg for BigInt {
444    fn encode(&self, encoder: &mut Encoder) -> Result<(), Error> {
445        codec::encode_big_int(encoder.buf, self).map_err(ClientEncodingError::with_source)
446    }
447    fn check_descriptor(ctx: &DescriptorContext, pos: TypePos) -> Result<(), Error> {
448        check_scalar(ctx, pos, Self::uuid(), Self::typename())
449    }
450    fn to_value(&self) -> Result<Value, Error> {
451        Ok(Value::BigInt(self.clone()))
452    }
453}
454
455#[cfg(feature = "bigdecimal")]
456impl ScalarArg for num_bigint::BigInt {
457    fn encode(&self, encoder: &mut Encoder) -> Result<(), Error> {
458        let val = self.clone().try_into().map_err(|e| {
459            ClientEncodingError::with_source(e).context("cannot serialize BigInt value")
460        })?;
461        codec::encode_big_int(encoder.buf, &val).map_err(ClientEncodingError::with_source)
462    }
463    fn check_descriptor(ctx: &DescriptorContext, pos: TypePos) -> Result<(), Error> {
464        check_scalar(ctx, pos, Self::uuid(), Self::typename())
465    }
466    fn to_value(&self) -> Result<Value, Error> {
467        let val = self.clone().try_into().map_err(|e| {
468            ClientEncodingError::with_source(e).context("cannot serialize BigInt value")
469        })?;
470        Ok(Value::BigInt(val))
471    }
472}
473
474impl RawCodec<'_> for Duration {
475    fn decode(mut buf: &[u8]) -> Result<Self, DecodeError> {
476        ensure_exact_size(buf, 16)?;
477        let micros = buf.get_i64();
478        let days = buf.get_u32();
479        let months = buf.get_u32();
480        ensure!(months == 0 && days == 0, errors::NonZeroReservedBytes);
481        Ok(Duration { micros })
482    }
483}
484
485impl RawCodec<'_> for std::time::Duration {
486    fn decode(buf: &[u8]) -> Result<Self, DecodeError> {
487        let dur = Duration::decode(buf)?;
488        dur.try_into().map_err(|_| errors::InvalidDate.build())
489    }
490}
491
492impl ScalarArg for Duration {
493    fn encode(&self, encoder: &mut Encoder) -> Result<(), Error> {
494        codec::encode_duration(encoder.buf, self).map_err(ClientEncodingError::with_source)
495    }
496    fn check_descriptor(ctx: &DescriptorContext, pos: TypePos) -> Result<(), Error> {
497        check_scalar(ctx, pos, Self::uuid(), Self::typename())
498    }
499    fn to_value(&self) -> Result<Value, Error> {
500        Ok(Value::Duration(*self))
501    }
502}
503
504impl RawCodec<'_> for RelativeDuration {
505    fn decode(mut buf: &[u8]) -> Result<Self, DecodeError> {
506        ensure_exact_size(buf, 16)?;
507        let micros = buf.get_i64();
508        let days = buf.get_i32();
509        let months = buf.get_i32();
510        Ok(RelativeDuration {
511            micros,
512            days,
513            months,
514        })
515    }
516}
517
518impl RawCodec<'_> for DateDuration {
519    fn decode(mut buf: &[u8]) -> Result<Self, DecodeError> {
520        ensure_exact_size(buf, 16)?;
521        let micros = buf.get_i64();
522        let days = buf.get_i32();
523        let months = buf.get_i32();
524        ensure!(micros == 0, errors::NonZeroReservedBytes);
525        Ok(DateDuration { days, months })
526    }
527}
528
529impl ScalarArg for RelativeDuration {
530    fn encode(&self, encoder: &mut Encoder) -> Result<(), Error> {
531        codec::encode_relative_duration(encoder.buf, self).map_err(ClientEncodingError::with_source)
532    }
533    fn check_descriptor(ctx: &DescriptorContext, pos: TypePos) -> Result<(), Error> {
534        check_scalar(ctx, pos, Self::uuid(), Self::typename())
535    }
536    fn to_value(&self) -> Result<Value, Error> {
537        Ok(Value::RelativeDuration(*self))
538    }
539}
540
541impl RawCodec<'_> for SystemTime {
542    fn decode(buf: &[u8]) -> Result<Self, DecodeError> {
543        let dur = Datetime::decode(buf)?;
544        dur.try_into().map_err(|_| errors::InvalidDate.build())
545    }
546}
547
548impl ScalarArg for SystemTime {
549    fn encode(&self, encoder: &mut Encoder) -> Result<(), Error> {
550        let val = (*self).try_into().map_err(|e| {
551            ClientEncodingError::with_source(e).context("cannot serialize SystemTime value")
552        })?;
553        codec::encode_datetime(encoder.buf, &val).map_err(ClientEncodingError::with_source)
554    }
555    fn check_descriptor(ctx: &DescriptorContext, pos: TypePos) -> Result<(), Error> {
556        check_scalar(ctx, pos, Self::uuid(), Self::typename())
557    }
558    fn to_value(&self) -> Result<Value, Error> {
559        let val = (*self).try_into().map_err(|e| {
560            ClientEncodingError::with_source(e).context("cannot serialize SystemTime value")
561        })?;
562        Ok(Value::Datetime(val))
563    }
564}
565
566impl RawCodec<'_> for Datetime {
567    fn decode(buf: &[u8]) -> Result<Self, DecodeError> {
568        let micros = i64::decode(buf)?;
569        Datetime::from_postgres_micros(micros).map_err(|_| errors::InvalidDate.build())
570    }
571}
572
573impl ScalarArg for Datetime {
574    fn encode(&self, encoder: &mut Encoder) -> Result<(), Error> {
575        codec::encode_datetime(encoder.buf, self).map_err(ClientEncodingError::with_source)
576    }
577    fn check_descriptor(ctx: &DescriptorContext, pos: TypePos) -> Result<(), Error> {
578        check_scalar(ctx, pos, Self::uuid(), Self::typename())
579    }
580    fn to_value(&self) -> Result<Value, Error> {
581        Ok(Value::Datetime(*self))
582    }
583}
584
585impl RawCodec<'_> for LocalDatetime {
586    fn decode(buf: &[u8]) -> Result<Self, DecodeError> {
587        let micros = i64::decode(buf)?;
588        LocalDatetime::from_postgres_micros(micros).map_err(|_| errors::InvalidDate.build())
589    }
590}
591
592impl ScalarArg for LocalDatetime {
593    fn encode(&self, encoder: &mut Encoder) -> Result<(), Error> {
594        codec::encode_local_datetime(encoder.buf, self).map_err(ClientEncodingError::with_source)
595    }
596    fn check_descriptor(ctx: &DescriptorContext, pos: TypePos) -> Result<(), Error> {
597        check_scalar(ctx, pos, Self::uuid(), Self::typename())
598    }
599    fn to_value(&self) -> Result<Value, Error> {
600        Ok(Value::LocalDatetime(*self))
601    }
602}
603
604impl RawCodec<'_> for LocalDate {
605    fn decode(buf: &[u8]) -> Result<Self, DecodeError> {
606        let days = i32::decode(buf)?;
607        Ok(LocalDate { days })
608    }
609}
610
611impl ScalarArg for LocalDate {
612    fn encode(&self, encoder: &mut Encoder) -> Result<(), Error> {
613        codec::encode_local_date(encoder.buf, self).map_err(ClientEncodingError::with_source)
614    }
615    fn check_descriptor(ctx: &DescriptorContext, pos: TypePos) -> Result<(), Error> {
616        check_scalar(ctx, pos, Self::uuid(), Self::typename())
617    }
618    fn to_value(&self) -> Result<Value, Error> {
619        Ok(Value::LocalDate(*self))
620    }
621}
622
623impl RawCodec<'_> for LocalTime {
624    fn decode(buf: &[u8]) -> Result<Self, DecodeError> {
625        let micros = i64::decode(buf)?;
626        ensure!(
627            (0..86_400 * 1_000_000).contains(&micros),
628            errors::InvalidDate
629        );
630        Ok(LocalTime {
631            micros: micros as u64,
632        })
633    }
634}
635
636impl ScalarArg for DateDuration {
637    fn encode(&self, encoder: &mut Encoder) -> Result<(), Error> {
638        codec::encode_date_duration(encoder.buf, self).map_err(ClientEncodingError::with_source)
639    }
640    fn check_descriptor(ctx: &DescriptorContext, pos: TypePos) -> Result<(), Error> {
641        check_scalar(ctx, pos, Self::uuid(), Self::typename())
642    }
643    fn to_value(&self) -> Result<Value, Error> {
644        Ok(Value::DateDuration(*self))
645    }
646}
647
648impl ScalarArg for LocalTime {
649    fn encode(&self, encoder: &mut Encoder) -> Result<(), Error> {
650        codec::encode_local_time(encoder.buf, self).map_err(ClientEncodingError::with_source)
651    }
652    fn check_descriptor(ctx: &DescriptorContext, pos: TypePos) -> Result<(), Error> {
653        check_scalar(ctx, pos, Self::uuid(), Self::typename())
654    }
655    fn to_value(&self) -> Result<Value, Error> {
656        Ok(Value::LocalTime(*self))
657    }
658}
659
660impl ScalarArg for EnumValue {
661    fn encode(&self, encoder: &mut Encoder) -> Result<(), Error> {
662        encoder.buf.extend(self.as_bytes());
663        Ok(())
664    }
665    fn check_descriptor(ctx: &DescriptorContext, pos: TypePos) -> Result<(), Error> {
666        use crate::descriptors::Descriptor::Enumeration;
667
668        let desc = ctx.get(pos)?;
669        if let Enumeration(_) = desc {
670            // Should we check enum members?
671            // Should we override `QueryArg` check descriptor for that?
672            // Or maybe implement just `QueryArg` for enum?
673        }
674        Err(ctx.wrong_type(desc, "enum"))
675    }
676    fn to_value(&self) -> Result<Value, Error> {
677        Ok(Value::Enum(self.clone()))
678    }
679}
680
681impl<T: ScalarArg + Clone> ScalarArg for Range<T> {
682    fn encode(&self, encoder: &mut Encoder) -> Result<(), Error> {
683        let flags = if self.empty {
684            range::EMPTY
685        } else {
686            (if self.inc_lower { range::LB_INC } else { 0 })
687                | (if self.inc_upper { range::UB_INC } else { 0 })
688                | (if self.lower.is_none() {
689                    range::LB_INF
690                } else {
691                    0
692                })
693                | (if self.upper.is_none() {
694                    range::UB_INF
695                } else {
696                    0
697                })
698        };
699        encoder.buf.reserve(1);
700        encoder.buf.put_u8(flags as u8);
701
702        if let Some(lower) = &self.lower {
703            encoder.length_prefixed(|encoder| lower.encode(encoder))?
704        }
705
706        if let Some(upper) = &self.upper {
707            encoder.length_prefixed(|encoder| upper.encode(encoder))?;
708        }
709        Ok(())
710    }
711    fn check_descriptor(ctx: &DescriptorContext, pos: TypePos) -> Result<(), Error> {
712        let desc = ctx.get(pos)?;
713        if let Descriptor::Range(rng) = desc {
714            T::check_descriptor(ctx, rng.type_pos)
715        } else {
716            Err(ctx.wrong_type(desc, "range"))
717        }
718    }
719    fn to_value(&self) -> Result<Value, Error> {
720        Ok(Value::Range(Range {
721            lower: self
722                .lower
723                .as_ref()
724                .map(|v| v.to_value().map(Box::new))
725                .transpose()?,
726            upper: self
727                .upper
728                .as_ref()
729                .map(|v| v.to_value().map(Box::new))
730                .transpose()?,
731            inc_lower: self.inc_lower,
732            inc_upper: self.inc_upper,
733            empty: self.empty,
734        }))
735    }
736}
737
738impl ScalarArg for VectorRef<'_> {
739    fn encode(&self, encoder: &mut crate::query_arg::Encoder) -> Result<(), gel_errors::Error> {
740        encoder.buf.reserve(2 + 2 + self.0.len() * 4);
741        encoder.buf.put_u16(self.0.len() as u16); // len
742        encoder.buf.put_u16(0); // reserved
743        for v in self.0 {
744            encoder.buf.put_u32(v.to_bits());
745        }
746        Ok(())
747    }
748
749    fn check_descriptor(ctx: &DescriptorContext, type_pos: TypePos) -> Result<(), Error> {
750        check_scalar(
751            ctx,
752            type_pos,
753            codec::PGVECTOR_VECTOR,
754            "ext::pgvector::vector",
755        )
756    }
757
758    fn to_value(&self) -> Result<Value, gel_errors::Error> {
759        Ok(Value::Vector(self.0.to_vec()))
760    }
761}
762
763impl ScalarArg for Vector {
764    fn encode(&self, encoder: &mut crate::query_arg::Encoder) -> Result<(), gel_errors::Error> {
765        VectorRef(&self.0).encode(encoder)
766    }
767
768    fn check_descriptor(ctx: &DescriptorContext, type_pos: TypePos) -> Result<(), Error> {
769        VectorRef::check_descriptor(ctx, type_pos)
770    }
771
772    fn to_value(&self) -> Result<Value, gel_errors::Error> {
773        VectorRef(&self.0).to_value()
774    }
775}