fix: audit sqlx_postgres::types::time for overflowing casts

This commit is contained in:
Austin Bonander 2024-08-15 03:32:14 -07:00
parent fa5039d6aa
commit 112b4a84b5
3 changed files with 13 additions and 5 deletions

View File

@ -22,8 +22,11 @@ impl PgHasArrayType for Date {
impl Encode<'_, Postgres> for Date {
fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> Result<IsNull, BoxDynError> {
// DATE is encoded as the days since epoch
let days = (*self - PG_EPOCH).whole_days() as i32;
// DATE is encoded as number of days since epoch (2000-01-01)
let days: i32 = (*self - PG_EPOCH)
.whole_days()
.try_into()
.map_err(|_| format!("value {self:?} would overflow binary encoding for Postgres DATE"))?;
Encode::<Postgres>::encode(days, buf)
}

View File

@ -37,7 +37,9 @@ impl PgHasArrayType for OffsetDateTime {
impl Encode<'_, Postgres> for PrimitiveDateTime {
fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> Result<IsNull, BoxDynError> {
// TIMESTAMP is encoded as the microseconds since the epoch
let micros = (*self - PG_EPOCH.midnight()).whole_microseconds() as i64;
let micros: i64 = (*self - PG_EPOCH.midnight()).whole_microseconds()
.try_into()
.map_err(|_| format!("value {self:?} would overflow binary encoding for Postgres TIME"))?;
Encode::<Postgres>::encode(micros, buf)
}

View File

@ -21,8 +21,11 @@ impl PgHasArrayType for Time {
impl Encode<'_, Postgres> for Time {
fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> Result<IsNull, BoxDynError> {
// TIME is encoded as the microseconds since midnight
let micros = (*self - Time::MIDNIGHT).whole_microseconds() as i64;
// TIME is encoded as the microseconds since midnight.
//
// A truncating cast is fine because `self - Time::MIDNIGHT` cannot exceed a span of 24 hours.
#[allow(clippy::cast_possible_truncation)]
let micros: i64 = (*self - Time::MIDNIGHT).whole_microseconds() as i64;
Encode::<Postgres>::encode(micros, buf)
}