google-cloud-bigquery 0.17.0-preview

Google Cloud Client Libraries for Rust - BigQuery
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
// Copyright 2026 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Custom data types for BigQuery.
//!
//! This module provides Rust representations of BigQuery data types such as
//! [`Interval`] and [`Range`].

use crate::error::ConvertError;
use crate::query::FromSql;
use crate::query::from_sql::SqlValueInner;

/// Represents a BigQuery time [INTERVAL] value.
///
/// [INTERVAL]: https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#interval_type
///
/// # Example
///
/// ```
/// # async fn sample() -> anyhow::Result<()> {
/// use google_cloud_bigquery::client::BigQuery;
/// use google_cloud_bigquery::datatypes::Interval;
///
/// let client = BigQuery::builder()
///     .with_project_id("my-project-id")
///     .build()
///     .await?;
/// let mut rows = client
///     .query("SELECT INTERVAL '1-2 15 5:30:00' YEAR TO SECOND AS duration")
///     .until_done()
///     .await?
///     .read();
///
/// if let Some(row) = rows.next().await.transpose()? {
///     let interval: Interval = row.get("duration")?;
///     println!("{} years, {} months, {} days", interval.years, interval.months, interval.days);
/// }
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug, Default, PartialEq)]
#[non_exhaustive]
pub struct Interval {
    /// Years component.
    pub years: i32,
    /// Months component.
    pub months: i32,
    /// Days component.
    pub days: i32,
    /// Hours component.
    pub hours: i32,
    /// Minutes component.
    pub minutes: i32,
    /// Seconds component.
    pub seconds: i32,
    /// Nanoseconds component.
    pub nanos: i32,
}

impl Interval {
    /// Creates a new zero-duration interval (`0-0 0 0:00:00`), with all components set to `0`.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the value of [years][Self::years].
    pub fn set_years(mut self, v: i32) -> Self {
        self.years = v;
        self
    }

    /// Sets the value of [months][Self::months].
    pub fn set_months(mut self, v: i32) -> Self {
        self.months = v;
        self
    }

    /// Sets the value of [days][Self::days].
    pub fn set_days(mut self, v: i32) -> Self {
        self.days = v;
        self
    }

    /// Sets the value of [hours][Self::hours].
    pub fn set_hours(mut self, v: i32) -> Self {
        self.hours = v;
        self
    }

    /// Sets the value of [minutes][Self::minutes].
    pub fn set_minutes(mut self, v: i32) -> Self {
        self.minutes = v;
        self
    }

    /// Sets the value of [seconds][Self::seconds].
    pub fn set_seconds(mut self, v: i32) -> Self {
        self.seconds = v;
        self
    }

    /// Sets the value of [nanos][Self::nanos].
    pub fn set_nanos(mut self, v: i32) -> Self {
        self.nanos = v;
        self
    }
}

impl FromSql for Interval {
    fn from_value(value: crate::query::SqlValue) -> Result<Self, ConvertError> {
        match value.inner {
            SqlValueInner::String(s) => {
                let mut parts = s.split_whitespace();
                let ym_str = parts.next();
                let days_str = parts.next();
                let time_str = parts.next();
                let extra = parts.next();

                let (ym_str, days_str, time_str) = match (ym_str, days_str, time_str, extra) {
                    (Some(ym), Some(d), Some(t), None) => (ym, d, t),
                    _ => {
                        return Err(ConvertError::Convert(
                            format!("invalid interval format: expected 3 parts, got `{s}`").into(),
                        ));
                    }
                };

                // Parse Y-M
                let ym_neg = ym_str.starts_with('-');
                let ym_content = if ym_neg { &ym_str[1..] } else { ym_str };
                let mut ym_parts = ym_content.split('-');
                let y_str = ym_parts.next();
                let m_str = ym_parts.next();
                let ym_extra = ym_parts.next();

                let (y_str, m_str) = match (y_str, m_str, ym_extra) {
                    (Some(y), Some(m), None) => (y, m),
                    _ => {
                        return Err(ConvertError::Convert(
                            "invalid interval year-month format".into(),
                        ));
                    }
                };
                let ym_sign = if ym_neg { -1 } else { 1 };
                let years = y_str
                    .parse::<i32>()
                    .map_err(|e| ConvertError::Convert(Box::new(e)))?
                    * ym_sign;
                let months = m_str
                    .parse::<i32>()
                    .map_err(|e| ConvertError::Convert(Box::new(e)))?
                    * ym_sign;

                // Parse Days
                let days = days_str
                    .parse::<i32>()
                    .map_err(|e| ConvertError::Convert(Box::new(e)))?;

                // Parse H:M:S.F. Hours are unbounded: BigQuery never spills
                // hours into days, so a timestamp difference of a month is
                // `0-0 0 744:0:0`.
                let time_neg = time_str.starts_with('-');
                let time_content = if time_neg { &time_str[1..] } else { time_str };
                let (hms, frac) = time_content.split_once('.').unwrap_or((time_content, "0"));
                let mut hms_parts = hms.split(':');
                let (h_str, m_str, s_str) = match (
                    hms_parts.next(),
                    hms_parts.next(),
                    hms_parts.next(),
                    hms_parts.next(),
                ) {
                    (Some(h), Some(m), Some(s), None) => (h, m, s),
                    _ => {
                        return Err(ConvertError::Convert("invalid interval time format".into()));
                    }
                };
                let time_sign = if time_neg { -1 } else { 1 };
                let hours = h_str
                    .parse::<i32>()
                    .map_err(|e| ConvertError::Convert(Box::new(e)))?
                    * time_sign;
                let minutes = m_str
                    .parse::<i32>()
                    .map_err(|e| ConvertError::Convert(Box::new(e)))?
                    * time_sign;
                let seconds = s_str
                    .parse::<i32>()
                    .map_err(|e| ConvertError::Convert(Box::new(e)))?
                    * time_sign;
                // The fraction has any number of digits; nanoseconds need exactly nine.
                let nanos = format!("{frac:0<9.9}")
                    .parse::<i32>()
                    .map_err(|e| ConvertError::Convert(Box::new(e)))?
                    * time_sign;

                Ok(Interval {
                    years,
                    months,
                    days,
                    hours,
                    minutes,
                    seconds,
                    nanos,
                })
            }
            SqlValueInner::Null => Err(ConvertError::NotNull),
            other => Err(ConvertError::type_mismatch("string", &other)),
        }
    }
}

mod sealed {
    /// A sealed trait to prevent external implementation of `RangeElement`.
    pub trait RangeElement {}

    impl RangeElement for google_cloud_type::model::Date {}
    impl RangeElement for google_cloud_type::model::DateTime {}
    impl RangeElement for wkt::Timestamp {}
}

/// A marker trait for types that can be elements of a BigQuery [`Range`].
///
/// BigQuery `RANGE<T>` values support [`Date`](google_cloud_type::model::Date),
/// [`DateTime`](google_cloud_type::model::DateTime), and [`Timestamp`](wkt::Timestamp)
/// element types.
///
/// This trait is sealed and cannot be implemented for types outside of this crate.
pub trait RangeElement: FromSql + sealed::RangeElement {}

impl RangeElement for google_cloud_type::model::Date {}
impl RangeElement for google_cloud_type::model::DateTime {}
impl RangeElement for wkt::Timestamp {}

/// Represents a BigQuery [RANGE] value.
///
/// [RANGE]: https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/data-types#range_type
///
/// # Example
///
/// ```
/// # async fn sample() -> anyhow::Result<()> {
/// use google_cloud_bigquery::client::BigQuery;
/// use google_cloud_bigquery::datatypes::Range;
/// use google_cloud_type::model::Date;
///
/// let client = BigQuery::builder()
///     .with_project_id("my-project-id")
///     .build()
///     .await?;
/// let mut rows = client
///     .query("SELECT RANGE(DATE '2024-01-01', DATE '2024-12-31') AS date_range")
///     .until_done()
///     .await?
///     .read();
///
/// if let Some(row) = rows.next().await.transpose()? {
///     let date_range: Range<Date> = row.get("date_range")?;
///     println!("Start: {:?}, End: {:?}", date_range.start, date_range.end);
/// }
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct Range<T: RangeElement> {
    /// The inclusive start of the range (or None if unbounded).
    pub start: Option<T>,
    /// The exclusive end of the range (or None if unbounded).
    pub end: Option<T>,
}

impl<T: RangeElement> Default for Range<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T: RangeElement> Range<T> {
    /// Creates a new unbounded range (`[UNBOUNDED, UNBOUNDED)`).
    pub fn new() -> Self {
        Self {
            start: None,
            end: None,
        }
    }

    /// Sets the value of [start][Self::start].
    pub fn set_start<V: Into<T>>(mut self, v: V) -> Self {
        self.start = Some(v.into());
        self
    }

    /// Sets or clears the value of [start][Self::start].
    pub fn set_or_clear_start(mut self, v: Option<T>) -> Self {
        self.start = v;
        self
    }

    /// Sets the value of [end][Self::end].
    pub fn set_end<V: Into<T>>(mut self, v: V) -> Self {
        self.end = Some(v.into());
        self
    }

    /// Sets or clears the value of [end][Self::end].
    pub fn set_or_clear_end(mut self, v: Option<T>) -> Self {
        self.end = v;
        self
    }
}

impl<T: RangeElement> FromSql for Range<T> {
    fn from_value(value: crate::query::SqlValue) -> Result<Self, ConvertError> {
        match value.inner {
            SqlValueInner::String(s) => {
                let trimmed = s.trim();
                // Strip leading [ and trailing )
                let content = trimmed
                    .strip_prefix('[')
                    .and_then(|c| c.strip_suffix(')'))
                    .ok_or_else(|| {
                        ConvertError::Convert(
                            "invalid range format: missing enclosing brackets".into(),
                        )
                    })?;

                // Split on the comma
                let parts: Vec<&str> = content.split(',').collect();
                if parts.len() != 2 {
                    return Err(ConvertError::Convert(
                        format!(
                            "invalid range format: expected 2 parts, got {}",
                            parts.len()
                        )
                        .into(),
                    ));
                }

                let start_str = parts[0].trim();
                let end_str = parts[1].trim();

                let start = if start_str.is_empty() || start_str == "UNBOUNDED" {
                    None
                } else {
                    Some(T::from_value(crate::query::SqlValue::from_inner(
                        SqlValueInner::String(start_str.to_string()),
                    ))?)
                };

                let end = if end_str.is_empty() || end_str == "UNBOUNDED" {
                    None
                } else {
                    Some(T::from_value(crate::query::SqlValue::from_inner(
                        SqlValueInner::String(end_str.to_string()),
                    ))?)
                };

                Ok(Range { start, end })
            }
            SqlValueInner::Null => Err(ConvertError::NotNull),
            other => Err(ConvertError::type_mismatch("string", &other)),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use test_case::test_case;

    #[derive(Debug, PartialEq)]
    enum TestConvertError {
        NotNull,
        TypeMismatch(String),
        Convert(String),
    }

    impl From<ConvertError> for TestConvertError {
        fn from(err: ConvertError) -> Self {
            match err {
                ConvertError::NotNull => Self::NotNull,
                ConvertError::TypeMismatch { expected, .. } => Self::TypeMismatch(expected),
                ConvertError::Convert(e) => Self::Convert(e.to_string()),
                ConvertError::MissingField(f) => Self::Convert(format!("missing field: {f}")),
            }
        }
    }

    #[test_case(wkt::Value::String("1-2 3 4:05:06.789123456".to_string()) => Ok(Interval { years: 1, months: 2, days: 3, hours: 4, minutes: 5, seconds: 6, nanos: 789_123_456 }) ; "valid interval with nanos")]
    #[test_case(wkt::Value::String("0-0 0 0:00:00".to_string()) => Ok(Interval { years: 0, months: 0, days: 0, hours: 0, minutes: 0, seconds: 0, nanos: 0 }) ; "zero interval")]
    #[test_case(wkt::Value::String("0-0 1 2:30:45.123456".to_string()) => Ok(Interval { years: 0, months: 0, days: 1, hours: 2, minutes: 30, seconds: 45, nanos: 123_456_000 }) ; "valid interval from integration test")]
    #[test_case(wkt::Value::String("1-2 3 4:5:6".to_string()) => Ok(Interval { years: 1, months: 2, days: 3, hours: 4, minutes: 5, seconds: 6, nanos: 0 }) ; "unpadded time without subseconds")]
    #[test_case(wkt::Value::String("1-2 3 4:5:6.5".to_string()) => Ok(Interval { years: 1, months: 2, days: 3, hours: 4, minutes: 5, seconds: 6, nanos: 500_000_000 }) ; "unpadded time with short subsecond")]
    #[test_case(wkt::Value::String("-1-2 3 -4:5:6.123".to_string()) => Ok(Interval { years: -1, months: -2, days: 3, hours: -4, minutes: -5, seconds: -6, nanos: -123_000_000 }) ; "mixed signs interval")]
    #[test_case(wkt::Value::String("0-0 0 1:1:1.000000001".to_string()) => Ok(Interval { years: 0, months: 0, days: 0, hours: 1, minutes: 1, seconds: 1, nanos: 1 }) ; "single nanosecond")]
    #[test_case(wkt::Value::String("-1-2 -3 -4:05:06.123".to_string()) => Ok(Interval { years: -1, months: -2, days: -3, hours: -4, minutes: -5, seconds: -6, nanos: -123_000_000 }) ; "all negative interval")]
    #[test_case(wkt::Value::String("0-0 0 0:00:00.1234567899".to_string()) => Ok(Interval { years: 0, months: 0, days: 0, hours: 0, minutes: 0, seconds: 0, nanos: 123_456_789 }) ; "truncated nanos")]
    #[test_case(wkt::Value::Null => Err(TestConvertError::NotNull) ; "null interval")]
    #[test_case(wkt::Value::Number(123.into()) => Err(TestConvertError::TypeMismatch("string".to_string())) ; "type mismatch interval")]
    #[test_case(wkt::Value::String("".to_string()) => Err(TestConvertError::Convert("invalid interval format: expected 3 parts, got ``".to_string())) ; "empty interval string")]
    #[test_case(wkt::Value::String("1-2 3".to_string()) => Err(TestConvertError::Convert("invalid interval format: expected 3 parts, got `1-2 3`".to_string())) ; "invalid interval parts count")]
    #[test_case(wkt::Value::String("1 3 4:05:06".to_string()) => Err(TestConvertError::Convert("invalid interval year-month format".to_string())) ; "invalid year-month format")]
    #[test_case(wkt::Value::String("0-0 0 744:0:0".to_string()) => Ok(Interval { years: 0, months: 0, days: 0, hours: 744, minutes: 0, seconds: 0, nanos: 0 }) ; "hours beyond a day")]
    #[test_case(wkt::Value::String("0-0 0 25:0:0".to_string()) => Ok(Interval { years: 0, months: 0, days: 0, hours: 25, minutes: 0, seconds: 0, nanos: 0 }) ; "interval 25 hour")]
    #[test_case(wkt::Value::String("0-0 0 -744:0:0".to_string()) => Ok(Interval { years: 0, months: 0, days: 0, hours: -744, minutes: 0, seconds: 0, nanos: 0 }) ; "negative hours beyond a day")]
    #[test_case(wkt::Value::String("1-2 3 4:05".to_string()) => Err(TestConvertError::Convert("invalid interval time format".to_string())) ; "invalid time format")]
    #[test_case(wkt::Value::String("1-2 3 4:05:06:07".to_string()) => Err(TestConvertError::Convert("invalid interval time format".to_string())) ; "too many time parts")]
    #[test_case(wkt::Value::String("1-2 3 4:05:06.x".to_string()) => Err(TestConvertError::Convert("invalid digit found in string".to_string())) ; "invalid subsecond")]
    fn test_from_sql_interval(value: wkt::Value) -> Result<Interval, TestConvertError> {
        FromSql::from_value(crate::query::SqlValue::new(value)).map_err(TestConvertError::from)
    }

    #[test_case(wkt::Value::String("[2026-05-28, 2026-05-29)".to_string()) => Ok(Range { start: Some(google_cloud_type::model::Date::new().set_year(2026).set_month(5).set_day(28)), end: Some(google_cloud_type::model::Date::new().set_year(2026).set_month(5).set_day(29)) }) ; "date range bounded")]
    #[test_case(wkt::Value::String("[2026-05-28, UNBOUNDED)".to_string()) => Ok(Range { start: Some(google_cloud_type::model::Date::new().set_year(2026).set_month(5).set_day(28)), end: None }) ; "date range unbounded end")]
    #[test_case(wkt::Value::String("[UNBOUNDED, 2026-05-29)".to_string()) => Ok(Range { start: None, end: Some(google_cloud_type::model::Date::new().set_year(2026).set_month(5).set_day(29)) }) ; "date range unbounded start")]
    #[test_case(wkt::Value::String("[UNBOUNDED, UNBOUNDED)".to_string()) => Ok(Range { start: None, end: None }) ; "date range unbounded both")]
    #[test_case(wkt::Value::Null => Err(TestConvertError::NotNull) ; "null range")]
    #[test_case(wkt::Value::Number(123.into()) => Err(TestConvertError::TypeMismatch("string".to_string())) ; "range type mismatch")]
    #[test_case(wkt::Value::String("[2026-05-28)".to_string()) => Err(TestConvertError::Convert("invalid range format: expected 2 parts, got 1".to_string())) ; "range invalid format one part")]
    #[test_case(wkt::Value::String("[2026-05-28, 2026-05-29, 2026-05-30)".to_string()) => Err(TestConvertError::Convert("invalid range format: expected 2 parts, got 3".to_string())) ; "range invalid format three parts")]
    #[test_case(wkt::Value::String("[".to_string()) => Err(TestConvertError::Convert("invalid range format: missing enclosing brackets".to_string())) ; "range too short")]
    #[test_case(wkt::Value::String("2026-05-28, 2026-05-29".to_string()) => Err(TestConvertError::Convert("invalid range format: missing enclosing brackets".to_string())) ; "range missing brackets")]
    #[test_case(wkt::Value::String("(2026-05-28, 2026-05-29)".to_string()) => Err(TestConvertError::Convert("invalid range format: missing enclosing brackets".to_string())) ; "range invalid leading parenthesis")]
    #[test_case(wkt::Value::String("[2026-05-28, 2026-05-29]".to_string()) => Err(TestConvertError::Convert("invalid range format: missing enclosing brackets".to_string())) ; "range invalid trailing square bracket")]
    #[test_case(wkt::Value::String("[invalid-start, 2026-05-29)".to_string()) => Err(TestConvertError::Convert("the 'year' component could not be parsed".to_string())) ; "range invalid start element")]
    #[test_case(wkt::Value::String("[2026-05-28, invalid-end)".to_string()) => Err(TestConvertError::Convert("the 'year' component could not be parsed".to_string())) ; "range invalid end element")]
    fn test_from_sql_range(
        value: wkt::Value,
    ) -> Result<Range<google_cloud_type::model::Date>, TestConvertError> {
        FromSql::from_value(crate::query::SqlValue::new(value)).map_err(TestConvertError::from)
    }

    #[test_case(wkt::Value::String("[2026-05-28T15:30:00, 2026-05-29T15:30:00)".to_string()) => Ok(Range { start: Some(google_cloud_type::model::DateTime::new().set_year(2026).set_month(5).set_day(28).set_hours(15).set_minutes(30).set_seconds(0).set_nanos(0)), end: Some(google_cloud_type::model::DateTime::new().set_year(2026).set_month(5).set_day(29).set_hours(15).set_minutes(30).set_seconds(0).set_nanos(0)) }) ; "datetime range bounded")]
    fn test_from_sql_datetime_range(
        value: wkt::Value,
    ) -> Result<Range<google_cloud_type::model::DateTime>, TestConvertError> {
        FromSql::from_value(crate::query::SqlValue::new(value)).map_err(TestConvertError::from)
    }

    #[test_case(wkt::Value::String("[1779982200000000, UNBOUNDED)".to_string()) => Ok(Range { start: Some(wkt::Timestamp::clamp(1779982200, 0)), end: None }) ; "timestamp range unbounded end")]
    fn test_from_sql_timestamp_range(
        value: wkt::Value,
    ) -> Result<Range<wkt::Timestamp>, TestConvertError> {
        FromSql::from_value(crate::query::SqlValue::new(value)).map_err(TestConvertError::from)
    }

    #[test]
    fn test_interval_setters() {
        let interval = Interval::new()
            .set_years(1)
            .set_months(2)
            .set_days(3)
            .set_hours(4)
            .set_minutes(5)
            .set_seconds(6)
            .set_nanos(789);
        assert_eq!(
            interval,
            Interval {
                years: 1,
                months: 2,
                days: 3,
                hours: 4,
                minutes: 5,
                seconds: 6,
                nanos: 789,
            }
        );
    }

    #[test]
    fn test_range_setters() {
        let d1 = google_cloud_type::model::Date::new()
            .set_year(2026)
            .set_month(5)
            .set_day(28);
        let d2 = google_cloud_type::model::Date::new()
            .set_year(2026)
            .set_month(5)
            .set_day(29);
        let d3 = google_cloud_type::model::Date::new()
            .set_year(2026)
            .set_month(5)
            .set_day(30);

        let range = Range::<google_cloud_type::model::Date>::new()
            .set_start(d1.clone())
            .set_end(d2.clone());
        assert_eq!(
            range,
            Range {
                start: Some(d1),
                end: Some(d2),
            }
        );

        let cleared = range
            .set_or_clear_start(None)
            .set_or_clear_end(Some(d3.clone()));
        assert_eq!(
            cleared,
            Range {
                start: None,
                end: Some(d3),
            }
        );
    }
}