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::{RangedI8, RangedI32};
13use powerfmt::ext::FormatterExt;
14use powerfmt::smart_display::{self, FormatterOptions, Metadata, SmartDisplay};
15
16#[cfg(feature = "local-offset")]
17use crate::OffsetDateTime;
18use crate::convert::*;
19use crate::error;
20#[cfg(feature = "formatting")]
21use crate::formatting::Formattable;
22use crate::internal_macros::ensure_ranged;
23#[cfg(feature = "parsing")]
24use crate::parsing::Parsable;
25#[cfg(feature = "local-offset")]
26use crate::sys::local_offset_at;
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#[derive(#[automatically_derived]
impl ::core::clone::Clone for UtcOffset {
#[inline]
fn clone(&self) -> UtcOffset {
let _: ::core::clone::AssertParamIsClone<Seconds>;
let _: ::core::clone::AssertParamIsClone<Minutes>;
let _: ::core::clone::AssertParamIsClone<Hours>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for UtcOffset { }Copy, #[automatically_derived]
impl ::core::cmp::Eq for UtcOffset {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Seconds>;
let _: ::core::cmp::AssertParamIsEq<Minutes>;
let _: ::core::cmp::AssertParamIsEq<Hours>;
}
}Eq)]
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>(&self, state: &mut H)
79 where
80 H: Hasher,
81 {
82 state.write_u32(self.as_u32_for_equality());
83 }
84}
85
86impl PartialEq for UtcOffset {
87 #[inline]
88 fn eq(&self, other: &Self) -> bool {
89 self.as_u32_for_equality().eq(&other.as_u32_for_equality())
90 }
91}
92
93impl PartialOrd for UtcOffset {
94 #[inline]
95 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
96 Some(self.cmp(other))
97 }
98}
99
100impl Ord for UtcOffset {
101 #[inline]
102 fn cmp(&self, other: &Self) -> Ordering {
103 self.as_i32_for_comparison()
104 .cmp(&other.as_i32_for_comparison())
105 }
106}
107
108impl UtcOffset {
109 #[inline]
112 pub(crate) const fn as_u32_for_equality(self) -> u32 {
113 unsafe {
116 if const { truecfg!(target_endian = "little") } {
117 core::mem::transmute::<[i8; 4], u32>([
118 self.seconds.get(),
119 self.minutes.get(),
120 self.hours.get(),
121 0,
122 ])
123 } else {
124 core::mem::transmute::<[i8; 4], u32>([
125 self.hours.get(),
126 self.minutes.get(),
127 self.seconds.get(),
128 0,
129 ])
130 }
131 }
132 }
133
134 #[inline]
138 const fn as_i32_for_comparison(self) -> i32 {
139 (self.hours.get() as i32) << 16
140 | (self.minutes.get() as i32) << 8
141 | (self.seconds.get() as i32)
142 }
143
144 pub const UTC: Self = Self::from_whole_seconds_ranged(WholeSeconds::new_static::<0>());
152
153 #[doc(hidden)]
166 #[inline]
167 #[track_caller]
168 pub const unsafe fn __from_hms_unchecked(hours: i8, minutes: i8, seconds: i8) -> Self {
169 unsafe {
171 Self::from_hms_ranged_unchecked(
172 Hours::new_unchecked(hours),
173 Minutes::new_unchecked(minutes),
174 Seconds::new_unchecked(seconds),
175 )
176 }
177 }
178
179 #[inline]
192 pub const fn from_hms(
193 hours: i8,
194 minutes: i8,
195 seconds: i8,
196 ) -> Result<Self, error::ComponentRange> {
197 Ok(Self::from_hms_ranged(
198 match <Hours>::new(hours) {
Some(val) => val,
None => {
crate::hint::cold_path();
return Err(crate::error::ComponentRange::unconditional("offset hour"));
}
}ensure_ranged!(Hours: hours("offset hour")),
199 match <Minutes>::new(minutes) {
Some(val) => val,
None => {
crate::hint::cold_path();
return Err(crate::error::ComponentRange::unconditional("offset minute"));
}
}ensure_ranged!(Minutes: minutes("offset minute")),
200 match <Seconds>::new(seconds) {
Some(val) => val,
None => {
crate::hint::cold_path();
return Err(crate::error::ComponentRange::unconditional("offset second"));
}
}ensure_ranged!(Seconds: seconds("offset second")),
201 ))
202 }
203
204 #[inline]
209 #[track_caller]
210 pub(crate) const fn from_hms_ranged_unchecked(
211 hours: Hours,
212 minutes: Minutes,
213 seconds: Seconds,
214 ) -> Self {
215 if hours.get() < 0 {
216 if true {
if !(minutes.get() <= 0) {
::core::panicking::panic("assertion failed: minutes.get() <= 0")
};
};debug_assert!(minutes.get() <= 0);
217 if true {
if !(seconds.get() <= 0) {
::core::panicking::panic("assertion failed: seconds.get() <= 0")
};
};debug_assert!(seconds.get() <= 0);
218 } else if hours.get() > 0 {
219 if true {
if !(minutes.get() >= 0) {
::core::panicking::panic("assertion failed: minutes.get() >= 0")
};
};debug_assert!(minutes.get() >= 0);
220 if true {
if !(seconds.get() >= 0) {
::core::panicking::panic("assertion failed: seconds.get() >= 0")
};
};debug_assert!(seconds.get() >= 0);
221 }
222 if minutes.get() < 0 {
223 if true {
if !(seconds.get() <= 0) {
::core::panicking::panic("assertion failed: seconds.get() <= 0")
};
};debug_assert!(seconds.get() <= 0);
224 } else if minutes.get() > 0 {
225 if true {
if !(seconds.get() >= 0) {
::core::panicking::panic("assertion failed: seconds.get() >= 0")
};
};debug_assert!(seconds.get() >= 0);
226 }
227
228 Self {
229 hours,
230 minutes,
231 seconds,
232 }
233 }
234
235 #[inline]
241 pub(crate) const fn from_hms_ranged(
242 hours: Hours,
243 mut minutes: Minutes,
244 mut seconds: Seconds,
245 ) -> Self {
246 if (hours.get() > 0 && minutes.get() < 0) || (hours.get() < 0 && minutes.get() > 0) {
247 minutes = minutes.neg();
248 }
249 if (hours.get() > 0 && seconds.get() < 0)
250 || (hours.get() < 0 && seconds.get() > 0)
251 || (minutes.get() > 0 && seconds.get() < 0)
252 || (minutes.get() < 0 && seconds.get() > 0)
253 {
254 seconds = seconds.neg();
255 }
256
257 Self {
258 hours,
259 minutes,
260 seconds,
261 }
262 }
263
264 #[inline]
272 pub const fn from_whole_seconds(seconds: i32) -> Result<Self, error::ComponentRange> {
273 Ok(Self::from_whole_seconds_ranged(
274 match <WholeSeconds>::new(seconds) {
Some(val) => val,
None => {
crate::hint::cold_path();
return Err(crate::error::ComponentRange::unconditional("seconds"));
}
}ensure_ranged!(WholeSeconds: seconds),
275 ))
276 }
277
278 #[inline]
290 pub(crate) const fn from_whole_seconds_ranged(seconds: WholeSeconds) -> Self {
291 unsafe {
293 Self::__from_hms_unchecked(
294 (seconds.get() / Second::per_t::<i32>(Hour)) as i8,
295 ((seconds.get() % Second::per_t::<i32>(Hour)) / Minute::per_t::<i32>(Hour)) as i8,
296 (seconds.get() % Second::per_t::<i32>(Minute)) as i8,
297 )
298 }
299 }
300
301 #[inline]
310 pub const fn as_hms(self) -> (i8, i8, i8) {
311 (self.hours.get(), self.minutes.get(), self.seconds.get())
312 }
313
314 #[cfg(feature = "quickcheck")]
317 #[inline]
318 pub(crate) const fn as_hms_ranged(self) -> (Hours, Minutes, Seconds) {
319 (self.hours, self.minutes, self.seconds)
320 }
321
322 #[inline]
331 pub const fn whole_hours(self) -> i8 {
332 self.hours.get()
333 }
334
335 #[inline]
344 pub const fn whole_minutes(self) -> i16 {
345 self.hours.get() as i16 * Minute::per_t::<i16>(Hour) + self.minutes.get() as i16
346 }
347
348 #[inline]
357 pub const fn minutes_past_hour(self) -> i8 {
358 self.minutes.get()
359 }
360
361 #[inline]
372 pub const fn whole_seconds(self) -> i32 {
373 self.hours.get() as i32 * Second::per_t::<i32>(Hour)
374 + self.minutes.get() as i32 * Second::per_t::<i32>(Minute)
375 + self.seconds.get() as i32
376 }
377
378 #[inline]
387 pub const fn seconds_past_minute(self) -> i8 {
388 self.seconds.get()
389 }
390
391 #[inline]
401 pub const fn is_utc(self) -> bool {
402 self.as_u32_for_equality() == Self::UTC.as_u32_for_equality()
403 }
404
405 #[inline]
414 pub const fn is_positive(self) -> bool {
415 self.as_i32_for_comparison() > Self::UTC.as_i32_for_comparison()
416 }
417
418 #[inline]
427 pub const fn is_negative(self) -> bool {
428 self.as_i32_for_comparison() < Self::UTC.as_i32_for_comparison()
429 }
430
431 #[cfg(feature = "local-offset")]
442 #[inline]
443 pub fn local_offset_at(datetime: OffsetDateTime) -> Result<Self, error::IndeterminateOffset> {
444 local_offset_at(datetime).ok_or(error::IndeterminateOffset)
445 }
446
447 #[cfg(feature = "local-offset")]
458 #[inline]
459 pub fn current_local_offset() -> Result<Self, error::IndeterminateOffset> {
460 let now = OffsetDateTime::now_utc();
461 local_offset_at(now).ok_or(error::IndeterminateOffset)
462 }
463}
464
465#[cfg(feature = "formatting")]
466impl UtcOffset {
467 #[inline]
469 pub fn format_into(
470 self,
471 output: &mut (impl io::Write + ?Sized),
472 format: &(impl Formattable + ?Sized),
473 ) -> Result<usize, error::Format> {
474 format.format_into(output, None, None, Some(self))
475 }
476
477 #[inline]
487 pub fn format(self, format: &(impl Formattable + ?Sized)) -> Result<String, error::Format> {
488 format.format(None, None, Some(self))
489 }
490}
491
492#[cfg(feature = "parsing")]
493impl UtcOffset {
494 #[inline]
505 pub fn parse(
506 input: &str,
507 description: &(impl Parsable + ?Sized),
508 ) -> Result<Self, error::Parse> {
509 description.parse_offset(input.as_bytes())
510 }
511}
512
513mod private {
514 #[non_exhaustive]
516 #[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)]
517 pub struct UtcOffsetMetadata;
518}
519use private::UtcOffsetMetadata;
520
521impl SmartDisplay for UtcOffset {
522 type Metadata = UtcOffsetMetadata;
523
524 #[inline]
525 fn metadata(&self, _: FormatterOptions) -> Metadata<'_, Self> {
526 let sign = if self.is_negative() { '-' } else { '+' };
527 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!(
528 sign,
529 self.hours.abs() => width(2),
530 ":",
531 self.minutes.abs() => width(2),
532 ":",
533 self.seconds.abs() => width(2),
534 );
535 Metadata::new(width, self, UtcOffsetMetadata)
536 }
537
538 #[inline]
539 fn fmt_with_metadata(
540 &self,
541 f: &mut fmt::Formatter<'_>,
542 metadata: Metadata<Self>,
543 ) -> fmt::Result {
544 f.pad_with_width(
545 metadata.unpadded_width(),
546 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!(
547 "{}{:02}:{:02}:{:02}",
548 if self.is_negative() { '-' } else { '+' },
549 self.hours.abs(),
550 self.minutes.abs(),
551 self.seconds.abs(),
552 ),
553 )
554 }
555}
556
557impl fmt::Display for UtcOffset {
558 #[inline]
559 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
560 SmartDisplay::fmt(self, f)
561 }
562}
563
564impl fmt::Debug for UtcOffset {
565 #[inline]
566 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
567 fmt::Display::fmt(self, f)
568 }
569}
570
571impl Neg for UtcOffset {
572 type Output = Self;
573
574 #[inline]
575 fn neg(self) -> Self::Output {
576 Self::from_hms_ranged(self.hours.neg(), self.minutes.neg(), self.seconds.neg())
577 }
578}