Debian Codegraph @

src/types/time/time.rs

raw symbols SCIP
1 use crate::decode::Decode;
2 use crate::encode::{Encode, IsNull};
3 use crate::error::BoxDynError;
4 use crate::types::Type;
5 use crate::{PgArgumentBuffer, PgHasArrayType, PgTypeInfo, PgValueFormat, PgValueRef, Postgres};
6 use std::mem;
7 use time::macros::format_description;
8 use time::{Duration, Time};
9
10 impl Type<Postgres> for Time {
11 fn type_info() -> PgTypeInfo {
12 PgTypeInfo::TIME
13 }
14 }
15
16 impl PgHasArrayType for Time {
17 fn array_type_info() -> PgTypeInfo {
18 PgTypeInfo::TIME_ARRAY
19 }
20 }
21
22 impl Encode<'_, Postgres> for Time {
23 fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> Result<IsNull, BoxDynError> {
24 // TIME is encoded as the microseconds since midnight.
25 //
26 // A truncating cast is fine because `self - Time::MIDNIGHT` cannot exceed a span of 24 hours.
27 #[allow(clippy::cast_possible_truncation)]
28 let micros: i64 = (*self - Time::MIDNIGHT).whole_microseconds() as i64;
29 Encode::<Postgres>::encode(micros, buf)
30 }
31
32 fn size_hint(&self) -> usize {
33 mem::size_of::<u64>()
34 }
35 }
36
37 impl<'r> Decode<'r, Postgres> for Time {
38 fn decode(value: PgValueRef<'r>) -> Result<Self, BoxDynError> {
39 Ok(match value.format() {
40 PgValueFormat::Binary => {
41 // TIME is encoded as the microseconds since midnight
42 let us = Decode::<Postgres>::decode(value)?;
43 Time::MIDNIGHT + Duration::microseconds(us)
44 }
45
46 PgValueFormat::Text => Time::parse(
47 value.as_str()?,
48 // Postgres will not include the subsecond part if it's zero.
49 &format_description!("[hour]:[minute]:[second][optional [.[subsecond]]]"),
50 )?,
51 })
52 }
53 }