• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

zbraniecki / icu4x / 12020603084

23 Nov 2024 08:43PM UTC coverage: 75.71% (+0.2%) from 75.477%
12020603084

push

github

sffc
Touch Cargo.lock

55589 of 73424 relevant lines covered (75.71%)

644270.14 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

73.33
/components/timezone/src/zone_offset.rs
1
// This file is part of ICU4X. For terms of use, please see the file
2
// called LICENSE at the top level of the ICU4X source tree
3
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
4

5
use crate::provider::{ZoneOffsetPeriodV1Marker, EPOCH};
6
use crate::{TimeZoneBcp47Id, UtcOffset};
7
use icu_calendar::Iso;
8
use icu_calendar::{Date, Time};
9
use icu_provider::prelude::*;
10

11
/// [`ZoneOffsetCalculator`] uses data from the [data provider] to calculate time zone offsets.
12
///
13
/// [data provider]: icu_provider
14
#[derive(Debug)]
×
15
pub struct ZoneOffsetCalculator {
16
    pub(super) offset_period: DataPayload<ZoneOffsetPeriodV1Marker>,
×
17
}
18

19
#[cfg(feature = "compiled_data")]
20
impl Default for ZoneOffsetCalculator {
21
    fn default() -> Self {
×
22
        Self::new()
×
23
    }
×
24
}
25

26
impl ZoneOffsetCalculator {
27
    /// Constructs a `ZoneOffsetCalculator` using compiled data.
28
    ///
29
    /// ✨ *Enabled with the `compiled_data` Cargo feature.*
30
    ///
31
    /// [📚 Help choosing a constructor](icu_provider::constructors)
32
    #[cfg(feature = "compiled_data")]
33
    #[inline]
34
    pub const fn new() -> Self {
85✔
35
        ZoneOffsetCalculator {
85✔
36
            offset_period: DataPayload::from_static_ref(
85✔
37
                crate::provider::Baked::SINGLETON_ZONE_OFFSET_PERIOD_V1_MARKER,
38
            ),
39
        }
40
    }
85✔
41

42
    icu_provider::gen_any_buffer_data_constructors!(() -> error: DataError,
43
        functions: [
44
            new: skip,
45
            try_new_with_any_provider,
46
            try_new_with_buffer_provider,
47
            try_new_unstable,
48
            Self,
49
        ]
50
    );
51

52
    #[doc = icu_provider::gen_any_buffer_unstable_docs!(UNSTABLE, Self::new)]
53
    pub fn try_new_unstable(
54
        provider: &(impl DataProvider<ZoneOffsetPeriodV1Marker> + ?Sized),
55
    ) -> Result<Self, DataError> {
56
        let metazone_period = provider.load(Default::default())?.payload;
57
        Ok(Self {
58
            offset_period: metazone_period,
59
        })
60
    }
61

62
    /// Calculate zone offsets from timezone and local datetime.
63
    ///
64
    /// # Examples
65
    ///
66
    /// ```
67
    /// use icu::calendar::{Date, Time};
68
    /// use icu::timezone::TimeZoneBcp47Id;
69
    /// use icu::timezone::UtcOffset;
70
    /// use icu::timezone::ZoneOffsetCalculator;
71
    /// use tinystr::tinystr;
72
    ///
73
    /// let zoc = ZoneOffsetCalculator::new();
74
    ///
75
    /// // America/Denver observes DST
76
    /// let offsets = zoc
77
    ///     .compute_offsets_from_time_zone(
78
    ///         TimeZoneBcp47Id(tinystr!(8, "usden")),
79
    ///         (Date::try_new_iso(2024, 1, 1).unwrap(), Time::midnight()),
80
    ///     )
81
    ///     .unwrap();
82
    /// assert_eq!(
83
    ///     offsets.standard,
84
    ///     UtcOffset::try_from_seconds(-7 * 3600).unwrap()
85
    /// );
86
    /// assert_eq!(
87
    ///     offsets.daylight,
88
    ///     Some(UtcOffset::try_from_seconds(-6 * 3600).unwrap())
89
    /// );
90
    ///
91
    /// // America/Phoenix does not
92
    /// let offsets = zoc
93
    ///     .compute_offsets_from_time_zone(
94
    ///         TimeZoneBcp47Id(tinystr!(8, "usphx")),
95
    ///         (Date::try_new_iso(2024, 1, 1).unwrap(), Time::midnight()),
96
    ///     )
97
    ///     .unwrap();
98
    /// assert_eq!(
99
    ///     offsets.standard,
100
    ///     UtcOffset::try_from_seconds(-7 * 3600).unwrap()
101
    /// );
102
    /// assert_eq!(offsets.daylight, None);
103
    /// ```
104
    pub fn compute_offsets_from_time_zone(
45✔
105
        &self,
106
        time_zone_id: TimeZoneBcp47Id,
107
        (date, time): (Date<Iso>, Time),
45✔
108
    ) -> Option<ZoneOffsets> {
109
        use zerovec::ule::AsULE;
110
        match self.offset_period.get().0.get0(&time_zone_id) {
45✔
111
            Some(cursor) => {
43✔
112
                let mut offsets = None;
43✔
113
                let minutes_since_epoch_walltime = (date.to_fixed() - EPOCH) as i32 * 24 * 60
86✔
114
                    + (time.hour.number() as i32 * 60 + time.minute.number() as i32);
43✔
115
                for (minutes, id) in cursor.iter1_copied().rev() {
86✔
116
                    if minutes_since_epoch_walltime <= i32::from_unaligned(*minutes) {
71✔
117
                        offsets = Some(id);
43✔
118
                    } else {
119
                        break;
120
                    }
121
                }
122
                let offsets = offsets?;
88✔
123
                Some(ZoneOffsets {
43✔
124
                    standard: UtcOffset::from_eighths_of_hour(offsets.0),
43✔
125
                    daylight: (offsets.1 != 0)
86✔
126
                        .then_some(UtcOffset::from_eighths_of_hour(offsets.0 + offsets.1)),
43✔
127
                })
128
            }
43✔
129
            None => None,
2✔
130
        }
131
    }
45✔
132
}
133

134
/// Represents the different offsets in use for a time zone
135
#[non_exhaustive]
136
#[derive(Debug, Clone, Copy)]
×
137
pub struct ZoneOffsets {
138
    /// The standard offset.
139
    pub standard: UtcOffset,
×
140
    /// The daylight-saving offset, if used.
141
    pub daylight: Option<UtcOffset>,
×
142
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc