1#[cfg(feature = "formatting")]
4use alloc::string::String;
5use core::cmp::Ordering;
6use core::fmt;
7use core::hash::{Hash, Hasher};
8use core::ops::Neg;
9#[cfg(feature = "formatting")]
10use std::io;
11
12use deranged::{RangedI32, RangedI8};
13use powerfmt::ext::FormatterExt;
14use powerfmt::smart_display::{self, FormatterOptions, Metadata, SmartDisplay};
15
16use crate::convert::*;
17use crate::error;
18#[cfg(feature = "formatting")]
19use crate::formatting::Formattable;
20use crate::internal_macros::ensure_ranged;
21#[cfg(feature = "parsing")]
22use crate::parsing::Parsable;
23#[cfg(feature = "local-offset")]
24use crate::sys::local_offset_at;
25#[cfg(feature = "local-offset")]
26use crate::OffsetDateTime;
27
28type Hours = RangedI8<-25, 25>;
30type Minutes = RangedI8<{ -(Minute::per_t::<i8>(Hour) - 1) }, { Minute::per_t::<i8>(Hour) - 1 }>;
32type Seconds =
34 RangedI8<{ -(Second::per_t::<i8>(Minute) - 1) }, { Second::per_t::<i8>(Minute) - 1 }>;
35type WholeSeconds = RangedI32<
37 {
38 Hours::MIN.get() as i32 * Second::per_t::<i32>(Hour)
39 + Minutes::MIN.get() as i32 * Second::per_t::<i32>(Minute)
40 + Seconds::MIN.get() as i32
41 },
42 {
43 Hours::MAX.get() as i32 * Second::per_t::<i32>(Hour)
44 + Minutes::MAX.get() as i32 * Second::per_t::<i32>(Minute)
45 + Seconds::MAX.get() as i32
46 },
47>;
48
49)]
55#[cfg_attr(not(docsrs), repr(C))]
56pub struct UtcOffset {
57 #[cfg(target_endian = "little")]
61 seconds: Seconds,
62 #[cfg(target_endian = "little")]
63 minutes: Minutes,
64 #[cfg(target_endian = "little")]
65 hours: Hours,
66
67 #[cfg(target_endian = "big")]
69 hours: Hours,
70 #[cfg(target_endian = "big")]
71 minutes: Minutes,
72 #[cfg(target_endian = "big")]
73 seconds: Seconds,
74}
75
76impl Hash for UtcOffset {
77 #[inline]
78 fn hash<H: Hasher>(&self, state: &mut H) {
79 state.write_u32(self.as_u32());
80 }
81}
82
83impl PartialEq for UtcOffset {
84 #[inline]
85 fn eq(&self, other: &Self) -> bool {
86 self.as_u32().eq(&other.as_u32())
87 }
88}
89
90impl PartialOrd for UtcOffset {
91 #[inline]
92 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
93 Some(self.cmp(other))
94 }
95}
96
97impl Ord for UtcOffset {
98 #[inline]
99 fn cmp(&self, other: &Self) -> Ordering {
100 self.as_u32().cmp(&other.as_u32())
101 }
102}
103
104impl UtcOffset {
105 #[inline]
108 pub(crate) const fn as_u32(self) -> u32 {
109 #[cfg(target_endian = "big")]
110 return u32::from_be_bytes([
111 self.seconds.get() as u8,
112 self.minutes.get() as u8,
113 self.hours.get() as u8,
114 0,
115 ]);
116
117 #[cfg(target_endian = "little")]
118 return u32::from_le_bytes([
119 self.seconds.get() as u8,
120 self.minutes.get() as u8,
121 self.hours.get() as u8,
122 0,
123 ]);
124 }
125
126 pub const UTC: Self = Self::from_whole_seconds_ranged(WholeSeconds::new_static::<0>());
134
135 #[doc(hidden)]
148 #[inline]
149 #[track_caller]
150 pub const unsafe fn __from_hms_unchecked(hours: i8, minutes: i8, seconds: i8) -> Self {
151 unsafe {
153 Self::from_hms_ranged_unchecked(
154 Hours::new_unchecked(hours),
155 Minutes::new_unchecked(minutes),
156 Seconds::new_unchecked(seconds),
157 )
158 }
159 }
160
161 #[inline]
174 pub const fn from_hms(
175 hours: i8,
176 minutes: i8,
177 seconds: i8,
178 ) -> Result<Self, error::ComponentRange> {
179 Ok(Self::from_hms_ranged(
180 match <Hours>::new(hours) {
Some(val) => val,
None => {
crate::hint::cold_path();
#[allow(trivial_numeric_casts)]
return Err(crate::error::ComponentRange {
name: "hours",
minimum: <Hours>::MIN.get() as i64,
maximum: <Hours>::MAX.get() as i64,
value: hours as i64,
conditional_message: None,
});
}
}ensure_ranged!(Hours: hours),
181 match <Minutes>::new(minutes) {
Some(val) => val,
None => {
crate::hint::cold_path();
#[allow(trivial_numeric_casts)]
return Err(crate::error::ComponentRange {
name: "minutes",
minimum: <Minutes>::MIN.get() as i64,
maximum: <Minutes>::MAX.get() as i64,
value: minutes as i64,
conditional_message: None,
});
}
}ensure_ranged!(Minutes: minutes),
182 match <Seconds>::new(seconds) {
Some(val) => val,
None => {
crate::hint::cold_path();
#[allow(trivial_numeric_casts)]
return Err(crate::error::ComponentRange {
name: "seconds",
minimum: <Seconds>::MIN.get() as i64,
maximum: <Seconds>::MAX.get() as i64,
value: seconds as i64,
conditional_message: None,
});
}
}ensure_ranged!(Seconds: seconds),
183 ))
184 }
185
186 #[inline]
191 #[track_caller]
192 pub(crate) const fn from_hms_ranged_unchecked(
193 hours: Hours,
194 minutes: Minutes,
195 seconds: Seconds,
196 ) -> Self {
197 if hours.get() < 0 {
198 if true {
if !(minutes.get() <= 0) {
::core::panicking::panic("assertion failed: minutes.get() <= 0")
};
};debug_assert!(minutes.get() <= 0);
199 if true {
if !(seconds.get() <= 0) {
::core::panicking::panic("assertion failed: seconds.get() <= 0")
};
};debug_assert!(seconds.get() <= 0);
200 } else if hours.get() > 0 {
201 if true {
if !(minutes.get() >= 0) {
::core::panicking::panic("assertion failed: minutes.get() >= 0")
};
};debug_assert!(minutes.get() >= 0);
202 if true {
if !(seconds.get() >= 0) {
::core::panicking::panic("assertion failed: seconds.get() >= 0")
};
};debug_assert!(seconds.get() >= 0);
203 }
204 if minutes.get() < 0 {
205 if true {
if !(seconds.get() <= 0) {
::core::panicking::panic("assertion failed: seconds.get() <= 0")
};
};debug_assert!(seconds.get() <= 0);
206 } else if minutes.get() > 0 {
207 if true {
if !(seconds.get() >= 0) {
::core::panicking::panic("assertion failed: seconds.get() >= 0")
};
};debug_assert!(seconds.get() >= 0);
208 }
209
210 Self {
211 hours,
212 minutes,
213 seconds,
214 }
215 }
216
217 #[inline]
223 pub(crate) const fn from_hms_ranged(
224 hours: Hours,
225 mut minutes: Minutes,
226 mut seconds: Seconds,
227 ) -> Self {
228 if (hours.get() > 0 && minutes.get() < 0) || (hours.get() < 0 && minutes.get() > 0) {
229 minutes = minutes.neg();
230 }
231 if (hours.get() > 0 && seconds.get() < 0)
232 || (hours.get() < 0 && seconds.get() > 0)
233 || (minutes.get() > 0 && seconds.get() < 0)
234 || (minutes.get() < 0 && seconds.get() > 0)
235 {
236 seconds = seconds.neg();
237 }
238
239 Self {
240 hours,
241 minutes,
242 seconds,
243 }
244 }
245
246 #[inline]
254 pub const fn from_whole_seconds(seconds: i32) -> Result<Self, error::ComponentRange> {
255 Ok(Self::from_whole_seconds_ranged(
256 match <WholeSeconds>::new(seconds) {
Some(val) => val,
None => {
crate::hint::cold_path();
#[allow(trivial_numeric_casts)]
return Err(crate::error::ComponentRange {
name: "seconds",
minimum: <WholeSeconds>::MIN.get() as i64,
maximum: <WholeSeconds>::MAX.get() as i64,
value: seconds as i64,
conditional_message: None,
});
}
}ensure_ranged!(WholeSeconds: seconds),
257 ))
258 }
259
260 #[inline]
272 pub(crate) const fn from_whole_seconds_ranged(seconds: WholeSeconds) -> Self {
273 unsafe {
275 Self::__from_hms_unchecked(
276 (seconds.get() / Second::per_t::<i32>(Hour)) as i8,
277 ((seconds.get() % Second::per_t::<i32>(Hour)) / Minute::per_t::<i32>(Hour)) as i8,
278 (seconds.get() % Second::per_t::<i32>(Minute)) as i8,
279 )
280 }
281 }
282
283 #[inline]
292 pub const fn as_hms(self) -> (i8, i8, i8) {
293 (self.hours.get(), self.minutes.get(), self.seconds.get())
294 }
295
296 #[cfg(feature = "quickcheck")]
299 #[inline]
300 pub(crate) const fn as_hms_ranged(self) -> (Hours, Minutes, Seconds) {
301 (self.hours, self.minutes, self.seconds)
302 }
303
304 #[inline]
313 pub const fn whole_hours(self) -> i8 {
314 self.hours.get()
315 }
316
317 #[inline]
326 pub const fn whole_minutes(self) -> i16 {
327 self.hours.get() as i16 * Minute::per_t::<i16>(Hour) + self.minutes.get() as i16
328 }
329
330 #[inline]
339 pub const fn minutes_past_hour(self) -> i8 {
340 self.minutes.get()
341 }
342
343 #[inline]
354 pub const fn whole_seconds(self) -> i32 {
355 self.hours.get() as i32 * Second::per_t::<i32>(Hour)
356 + self.minutes.get() as i32 * Second::per_t::<i32>(Minute)
357 + self.seconds.get() as i32
358 }
359
360 #[inline]
369 pub const fn seconds_past_minute(self) -> i8 {
370 self.seconds.get()
371 }
372
373 #[inline]
383 pub const fn is_utc(self) -> bool {
384 self.hours.get() == 0 && self.minutes.get() == 0 && self.seconds.get() == 0
385 }
386
387 #[inline]
396 pub const fn is_positive(self) -> bool {
397 self.hours.get() > 0 || self.minutes.get() > 0 || self.seconds.get() > 0
398 }
399
400 #[inline]
409 pub const fn is_negative(self) -> bool {
410 self.hours.get() < 0 || self.minutes.get() < 0 || self.seconds.get() < 0
411 }
412
413 #[cfg(feature = "local-offset")]
424 #[inline]
425 pub fn local_offset_at(datetime: OffsetDateTime) -> Result<Self, error::IndeterminateOffset> {
426 local_offset_at(datetime).ok_or(error::IndeterminateOffset)
427 }
428
429 #[cfg(feature = "local-offset")]
440 #[inline]
441 pub fn current_local_offset() -> Result<Self, error::IndeterminateOffset> {
442 let now = OffsetDateTime::now_utc();
443 local_offset_at(now).ok_or(error::IndeterminateOffset)
444 }
445}
446
447#[cfg(feature = "formatting")]
448impl UtcOffset {
449 #[inline]
451 pub fn format_into(
452 self,
453 output: &mut (impl io::Write + ?Sized),
454 format: &(impl Formattable + ?Sized),
455 ) -> Result<usize, error::Format> {
456 format.format_into(output, None, None, Some(self))
457 }
458
459 #[inline]
469 pub fn format(self, format: &(impl Formattable + ?Sized)) -> Result<String, error::Format> {
470 format.format(None, None, Some(self))
471 }
472}
473
474#[cfg(feature = "parsing")]
475impl UtcOffset {
476 #[inline]
487 pub fn parse(
488 input: &str,
489 description: &(impl Parsable + ?Sized),
490 ) -> Result<Self, error::Parse> {
491 description.parse_offset(input.as_bytes())
492 }
493}
494
495mod private {
496 #[non_exhaustive]
497 #[derive(#[automatically_derived]
impl ::core::fmt::Debug for UtcOffsetMetadata {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f, "UtcOffsetMetadata")
}
}Debug, #[automatically_derived]
impl ::core::clone::Clone for UtcOffsetMetadata {
#[inline]
fn clone(&self) -> UtcOffsetMetadata { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for UtcOffsetMetadata { }Copy)]
498 pub struct UtcOffsetMetadata;
499}
500use private::UtcOffsetMetadata;
501
502impl SmartDisplay for UtcOffset {
503 type Metadata = UtcOffsetMetadata;
504
505 #[inline]
506 fn metadata(&self, _: FormatterOptions) -> Metadata<'_, Self> {
507 let sign = if self.is_negative() { '-' } else { '+' };
508 let width = 0 +
::powerfmt::smart_display::Metadata::padded_width_of(&sign,
::powerfmt::smart_display::FormatterOptions::default()) +
::powerfmt::smart_display::Metadata::padded_width_of(&self.hours.abs(),
*::powerfmt::smart_display::FormatterOptions::default().with_width(Some(2)))
+
::powerfmt::smart_display::Metadata::padded_width_of(&":",
::powerfmt::smart_display::FormatterOptions::default()) +
::powerfmt::smart_display::Metadata::padded_width_of(&self.minutes.abs(),
*::powerfmt::smart_display::FormatterOptions::default().with_width(Some(2)))
+
::powerfmt::smart_display::Metadata::padded_width_of(&":",
::powerfmt::smart_display::FormatterOptions::default()) +
::powerfmt::smart_display::Metadata::padded_width_of(&self.seconds.abs(),
*::powerfmt::smart_display::FormatterOptions::default().with_width(Some(2)))smart_display::padded_width_of!(
509 sign,
510 self.hours.abs() => width(2),
511 ":",
512 self.minutes.abs() => width(2),
513 ":",
514 self.seconds.abs() => width(2),
515 );
516 Metadata::new(width, self, UtcOffsetMetadata)
517 }
518
519 #[inline]
520 fn fmt_with_metadata(
521 &self,
522 f: &mut fmt::Formatter<'_>,
523 metadata: Metadata<Self>,
524 ) -> fmt::Result {
525 f.pad_with_width(
526 metadata.unpadded_width(),
527 format_args!("{0}{1:02}:{2:02}:{3:02}",
if self.is_negative() { '-' } else { '+' }, self.hours.abs(),
self.minutes.abs(), self.seconds.abs())format_args!(
528 "{}{:02}:{:02}:{:02}",
529 if self.is_negative() { '-' } else { '+' },
530 self.hours.abs(),
531 self.minutes.abs(),
532 self.seconds.abs(),
533 ),
534 )
535 }
536}
537
538impl fmt::Display for UtcOffset {
539 #[inline]
540 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
541 SmartDisplay::fmt(self, f)
542 }
543}
544
545impl fmt::Debug for UtcOffset {
546 #[inline]
547 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
548 fmt::Display::fmt(self, f)
549 }
550}
551
552impl Neg for UtcOffset {
553 type Output = Self;
554
555 #[inline]
556 fn neg(self) -> Self::Output {
557 Self::from_hms_ranged(self.hours.neg(), self.minutes.neg(), self.seconds.neg())
558 }
559}