Skip to main content

einvoice_xpath_eval/
context.rs

1//! The static context an expression is compiled in and the dynamic context it is
2//! evaluated in, with the hooks the XSLT layer provides: variables, user functions,
3//! `current()`, `document()` and `system-property()`.
4
5use std::cell::RefCell;
6use std::collections::HashMap;
7use std::rc::Rc;
8use std::sync::{Arc, Mutex, PoisonError};
9
10use einvoice_xdm::{Date, DateTime, XPathRegex};
11use einvoice_xpath::{NamespaceMap, Namespaces, QName};
12
13use crate::compile::ValueType;
14use crate::error::{ErrorCode, Result, err};
15use crate::eval::Argument;
16use crate::item::Item;
17use crate::limit::StackLimit;
18use crate::tree::Node;
19
20/// The identity of a variable declared by the host, given back to it at evaluation.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
22pub struct VariableId(pub u32);
23
24/// The identity of a function declared by the host (an `xsl:function`).
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
26pub struct FunctionId(pub u32);
27
28/// What is statically known of the number of items of a value.
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
30pub enum Cardinality {
31    /// At most one item.
32    AtMostOne,
33    /// Any number of items.
34    Any,
35}
36
37/// A variable in scope.
38#[derive(Debug, Clone)]
39pub struct VariableInfo {
40    /// Its identity at evaluation.
41    pub id: VariableId,
42    /// What is known of its value. It only affects the evaluation strategy (which side
43    /// of a general comparison is read first), never the result.
44    pub cardinality: Cardinality,
45    /// The static type Saxon-HE 12.10 gives its references, which decides some casts and
46    /// arithmetic ([`ValueType::unknown`] when nothing is known).
47    pub value_type: ValueType,
48}
49
50/// The static context of an expression (XPath 2.0 section 2.1.1), as far as the compiler
51/// needs it: names are already resolved by the parser.
52pub trait StaticContext {
53    /// The variable of that expanded name in scope, if any.
54    fn variable(&self, name: &QName) -> Option<VariableInfo>;
55
56    /// The variable a reference in the expression refers to, as [`Self::variable`]: the
57    /// compiler calls it once per reference, telling whether the reference is in an
58    /// operand evaluated repeatedly (a predicate, a path step after the first, the body
59    /// of `for`, `some` or `every`), as Saxon's `isLoopingReference` tells it. By
60    /// default, [`Self::variable`].
61    fn variable_reference(&self, name: &QName, in_loop: bool) -> Option<VariableInfo> {
62        let _ = in_loop;
63        self.variable(name)
64    }
65
66    /// The host function of that expanded name and arity, if any.
67    fn function(&self, name: &QName, arity: usize) -> Option<FunctionId>;
68
69    /// The static type of what a host function returns, once its call is type-checked:
70    /// [`ValueType::declared`] with the declared result type of an `xsl:function`. By
71    /// default, nothing is known.
72    fn function_type(&self, id: FunctionId) -> ValueType {
73        let _ = id;
74        ValueType::unknown()
75    }
76
77    /// Whether the XSLT functions `current()`, `document()` and `system-property()` are
78    /// available.
79    fn xslt_functions(&self) -> bool;
80
81    /// The namespace bound to a prefix, for the `QName` argument of `system-property()`.
82    fn namespace_uri(&self, prefix: &str) -> Option<String>;
83
84    /// The answer of `element-available()` for the element of that expanded name, if
85    /// known. By default, unknown (the call is refused).
86    fn element_available(&self, name: &QName) -> Option<bool> {
87        let _ = name;
88        None
89    }
90
91    /// The static base URI of the expression, against which `document()` resolves the
92    /// relative URIs given as strings. By default, none: the host's.
93    fn static_base_uri(&self) -> Option<String> {
94        None
95    }
96}
97
98/// A static context built by hand: namespaces, variables and functions declared one by
99/// one.
100#[derive(Debug, Clone, Default)]
101pub struct SimpleStaticContext {
102    namespaces: NamespaceMap,
103    variables: Vec<(QName, VariableInfo)>,
104    functions: Vec<(QName, usize, FunctionId, ValueType)>,
105    xslt: bool,
106}
107
108impl SimpleStaticContext {
109    /// An empty context: no namespaces, variables or functions, no XSLT functions.
110    #[must_use]
111    pub fn new() -> Self {
112        Self::default()
113    }
114
115    /// Uses these prefix bindings for `system-property()`.
116    #[must_use]
117    pub fn with_namespaces(mut self, namespaces: NamespaceMap) -> Self {
118        self.namespaces = namespaces;
119        self
120    }
121
122    /// Makes the XSLT functions available.
123    #[must_use]
124    pub const fn with_xslt_functions(mut self) -> Self {
125        self.xslt = true;
126        self
127    }
128
129    /// Declares a variable of unknown type (a later declaration of the same name hides
130    /// the earlier one) and returns its identity: the declaration order, from 0.
131    pub fn declare_variable(&mut self, name: QName, cardinality: Cardinality) -> VariableId {
132        self.declare_typed_variable(name, cardinality, ValueType::unknown())
133    }
134
135    /// Declares a variable of that static type, as [`Self::declare_variable`].
136    pub fn declare_typed_variable(
137        &mut self,
138        name: QName,
139        cardinality: Cardinality,
140        value_type: ValueType,
141    ) -> VariableId {
142        let id = VariableId(u32::try_from(self.variables.len()).unwrap_or(u32::MAX));
143        self.variables.push((
144            name,
145            VariableInfo {
146                id,
147                cardinality,
148                value_type,
149            },
150        ));
151        id
152    }
153
154    /// Declares a host function whose result is of unknown type and returns its
155    /// identity: the declaration order, from 0.
156    pub fn declare_function(&mut self, name: QName, arity: usize) -> FunctionId {
157        self.declare_typed_function(name, arity, ValueType::unknown())
158    }
159
160    /// Declares a host function whose result is of that static type, as
161    /// [`Self::declare_function`].
162    pub fn declare_typed_function(
163        &mut self,
164        name: QName,
165        arity: usize,
166        result: ValueType,
167    ) -> FunctionId {
168        let id = FunctionId(u32::try_from(self.functions.len()).unwrap_or(u32::MAX));
169        self.functions.push((name, arity, id, result));
170        id
171    }
172}
173
174impl StaticContext for SimpleStaticContext {
175    fn variable(&self, name: &QName) -> Option<VariableInfo> {
176        self.variables
177            .iter()
178            .rev()
179            .find(|(n, _)| n.same_expanded_name(name))
180            .map(|(_, info)| info.clone())
181    }
182
183    fn function(&self, name: &QName, arity: usize) -> Option<FunctionId> {
184        self.functions
185            .iter()
186            .find(|(n, a, _, _)| *a == arity && n.same_expanded_name(name))
187            .map(|(_, _, id, _)| *id)
188    }
189
190    fn function_type(&self, id: FunctionId) -> ValueType {
191        self.functions
192            .iter()
193            .find(|(_, _, i, _)| *i == id)
194            .map_or_else(ValueType::unknown, |(_, _, _, result)| result.clone())
195    }
196
197    fn xslt_functions(&self) -> bool {
198        self.xslt
199    }
200
201    fn namespace_uri(&self, prefix: &str) -> Option<String> {
202        self.namespaces.namespace_uri(prefix)
203    }
204}
205
206/// What the host (the XSLT layer) provides at evaluation. The compiler only lets
207/// through references to variables and functions the static context declared, so a
208/// host is only asked for those.
209pub trait Host {
210    /// The value of a variable.
211    ///
212    /// # Errors
213    ///
214    /// Whatever evaluating the variable raises.
215    fn variable(&self, id: VariableId) -> Result<Rc<[Item]>>;
216
217    /// Calls a host function, from an evaluation in the dynamic context `dc`. Its
218    /// arguments are evaluated or not yet: the host computes each one when it needs it
219    /// ([`Argument::evaluate`], with `dc`), as Saxon evaluates the arguments of a
220    /// stylesheet function lazily.
221    ///
222    /// # Errors
223    ///
224    /// Whatever the function raises.
225    fn call_function(
226        &self,
227        id: FunctionId,
228        args: Vec<Argument>,
229        dc: &DynamicContext<'_>,
230    ) -> Result<Vec<Item>>;
231
232    /// `document()`: the document node of the resource at `uri`, resolved against `base`
233    /// (the base URI of the node the URI came from, `None` for the static base URI). The
234    /// same URI must give the same document node, parsed with
235    /// [`Document::parse_loaded`](crate::Document::parse_loaded)
236    /// so that `fn:document-uri` gives its absolute URI, as in Saxon.
237    ///
238    /// # Errors
239    ///
240    /// The resource cannot be retrieved or parsed.
241    fn document(&self, uri: &str, base: Option<&str>) -> Result<Node>;
242
243    /// `system-property()`: the value of the property (the empty string for an unknown
244    /// one).
245    fn system_property(&self, name: &QName) -> String;
246}
247
248/// A host for plain XPath: no variables, functions or documents.
249#[derive(Debug, Clone, Copy, Default)]
250pub struct NoHost;
251
252impl Host for NoHost {
253    fn variable(&self, id: VariableId) -> Result<Rc<[Item]>> {
254        err(ErrorCode::Host, format!("no variable {}", id.0))
255    }
256
257    fn call_function(
258        &self,
259        id: FunctionId,
260        _args: Vec<Argument>,
261        _dc: &DynamicContext<'_>,
262    ) -> Result<Vec<Item>> {
263        err(ErrorCode::Host, format!("no function {}", id.0))
264    }
265
266    fn document(&self, uri: &str, _base: Option<&str>) -> Result<Node> {
267        err(ErrorCode::Host, format!("no document {uri}"))
268    }
269
270    fn system_property(&self, _name: &QName) -> String {
271        String::new()
272    }
273}
274
275/// The clock of an evaluation: the implicit timezone and the value of
276/// `fn:current-dateTime()`. Both are inputs: the evaluator never reads a clock itself, and
277/// the current date and time stays the same for every evaluation made with the clock, as
278/// Saxon reads its clock once per transformation.
279///
280/// [`Clock::system`] reads the system clock on the targets that have one; elsewhere, such
281/// as `wasm32-unknown-unknown`, the host gives the time it reads, for instance with
282/// [`Clock::from_unix_millis`] and JavaScript's `Date.now()`.
283#[derive(Debug, Clone, Copy, PartialEq, Eq)]
284pub struct Clock {
285    implicit_timezone: i16,
286    current_date_time: DateTime,
287}
288
289impl Clock {
290    /// The implicit timezone, in minutes east of UTC (Saxon takes the JVM's), and the value
291    /// of `fn:current-dateTime()`, returned as given.
292    ///
293    /// # Errors
294    ///
295    /// An offset beyond ±14:00, or a date and time without a timezone (the current date
296    /// and time always has one).
297    pub fn new(implicit_timezone: i16, current_date_time: DateTime) -> Result<Self> {
298        check_timezone(implicit_timezone)?;
299        if current_date_time.timezone().is_none() {
300            return err(
301                ErrorCode::Unsupported,
302                "the current date and time has no timezone",
303            );
304        }
305        Ok(Self {
306            implicit_timezone,
307            current_date_time,
308        })
309    }
310
311    /// The implicit timezone, in minutes east of UTC, and the instant `millis`
312    /// milliseconds after the Unix epoch (1970-01-01T00:00:00Z) as the current date and
313    /// time, expressed in that timezone.
314    ///
315    /// # Errors
316    ///
317    /// An offset beyond ±14:00, or an instant beyond the supported dates.
318    pub fn from_unix_millis(implicit_timezone: i16, millis: i64) -> Result<Self> {
319        check_timezone(implicit_timezone)?;
320        Ok(Self {
321            implicit_timezone,
322            current_date_time: date_time_from_millis(millis, implicit_timezone)?,
323        })
324    }
325
326    /// The implicit timezone, in minutes east of UTC, and the current reading of the
327    /// system clock, expressed in that timezone. Not available on
328    /// `wasm32-unknown-unknown`, which has no clock.
329    ///
330    /// # Errors
331    ///
332    /// An offset beyond ±14:00, or a system clock beyond the supported dates.
333    #[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
334    pub fn system(implicit_timezone: i16) -> Result<Self> {
335        use std::time::{SystemTime, UNIX_EPOCH};
336        let millis = match SystemTime::now().duration_since(UNIX_EPOCH) {
337            Ok(after) => i64::try_from(after.as_millis()),
338            Err(before) => i64::try_from(before.duration().as_millis()).map(|m| -m),
339        }
340        .map_err(|_| crate::error::Error::new(ErrorCode::Fodt0001, "system clock out of range"))?;
341        Self::from_unix_millis(implicit_timezone, millis)
342    }
343
344    /// The implicit timezone in minutes.
345    #[must_use]
346    pub const fn implicit_timezone(&self) -> i16 {
347        self.implicit_timezone
348    }
349
350    /// The value of `fn:current-dateTime()`.
351    #[must_use]
352    pub const fn current_date_time(&self) -> DateTime {
353        self.current_date_time
354    }
355}
356
357fn check_timezone(minutes: i16) -> Result<()> {
358    if (-840..=840).contains(&minutes) {
359        Ok(())
360    } else {
361        err(ErrorCode::Unsupported, "timezone offset out of range")
362    }
363}
364
365/// The regular expressions compiled at evaluation (a pattern or flags that are not
366/// literals), kept for the evaluations of any number of dynamic contexts, on any thread
367/// ([`DynamicContext::with_regex_cache`]): the transformations of a stylesheet compile each
368/// one once. At most [`RegexCache::MAX_ENTRIES`] are kept; the others are compiled each
369/// time a dynamic context first needs them.
370#[derive(Debug, Default)]
371pub struct RegexCache {
372    entries: Mutex<HashMap<(String, String), Arc<XPathRegex>>>,
373}
374
375impl RegexCache {
376    /// The most regular expressions a cache keeps.
377    pub const MAX_ENTRIES: usize = 1024;
378
379    /// An empty cache.
380    #[must_use]
381    pub fn new() -> Self {
382        Self::default()
383    }
384
385    fn get(&self, key: &(String, String)) -> Option<Arc<XPathRegex>> {
386        self.entries
387            .lock()
388            .unwrap_or_else(PoisonError::into_inner)
389            .get(key)
390            .cloned()
391    }
392
393    fn insert(&self, key: (String, String), regex: &Arc<XPathRegex>) {
394        let mut entries = self.entries.lock().unwrap_or_else(PoisonError::into_inner);
395        if entries.len() < Self::MAX_ENTRIES {
396            entries.entry(key).or_insert_with(|| Arc::clone(regex));
397        }
398    }
399}
400
401/// The dynamic context shared by evaluations: the host, the [`Clock`] (implicit timezone
402/// and current date and time), a cache of compiled regular expressions (shared with
403/// other contexts when the host gives one, [`DynamicContext::with_regex_cache`]) and, if
404/// the host sets one, the bound of the call stack ([`DynamicContext::with_stack_limit`]).
405pub struct DynamicContext<'h> {
406    pub(crate) host: &'h dyn Host,
407    pub(crate) implicit_timezone: i16,
408    pub(crate) current_date_time: DateTime,
409    pub(crate) regex_cache: RefCell<HashMap<(String, String), Arc<XPathRegex>>>,
410    pub(crate) shared_regexes: Option<&'h RegexCache>,
411    pub(crate) stack_limit: Option<StackLimit>,
412}
413
414impl std::fmt::Debug for DynamicContext<'_> {
415    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
416        f.debug_struct("DynamicContext")
417            .field("implicit_timezone", &self.implicit_timezone)
418            .field("current_date_time", &self.current_date_time)
419            .field("stack_limit", &self.stack_limit)
420            .finish_non_exhaustive()
421    }
422}
423
424impl<'h> DynamicContext<'h> {
425    /// A context with this host and clock.
426    #[must_use]
427    pub fn new(host: &'h dyn Host, clock: Clock) -> Self {
428        Self {
429            host,
430            implicit_timezone: clock.implicit_timezone,
431            current_date_time: clock.current_date_time,
432            regex_cache: RefCell::new(HashMap::new()),
433            shared_regexes: None,
434            stack_limit: None,
435        }
436    }
437
438    /// Bounds the call stack of the evaluations: every level of an expression evaluated
439    /// one inside another checks `limit`, and the evaluation ends with a
440    /// [`LimitExceeded::Stack`](crate::LimitExceeded::Stack) error
441    /// ([`Error::limit`](crate::Error::limit)) when the stack used is beyond it. For a
442    /// host that evaluates expressions inside a recursion of its own, measured from where
443    /// that recursion starts. Without it, an evaluation needs a stack in proportion to
444    /// the depth of the expression ([`einvoice_xpath::MAX_DEPTH`] at most).
445    #[must_use]
446    pub const fn with_stack_limit(mut self, limit: StackLimit) -> Self {
447        self.stack_limit = Some(limit);
448        self
449    }
450
451    /// Keeps the regular expressions compiled at evaluation in `cache`, and takes from it
452    /// those compiled before, by this context or another.
453    #[must_use]
454    pub const fn with_regex_cache(mut self, cache: &'h RegexCache) -> Self {
455        self.shared_regexes = Some(cache);
456        self
457    }
458
459    /// A [`LimitExceeded::Stack`](crate::LimitExceeded::Stack) error when the stack used
460    /// is beyond the bound set by [`DynamicContext::with_stack_limit`].
461    pub(crate) fn check_stack(&self) -> Result<()> {
462        match self.stack_limit {
463            Some(limit) => limit.check().map_err(crate::error::Error::limit_exceeded),
464            None => Ok(()),
465        }
466    }
467
468    /// The clock: implicit timezone and current date and time.
469    #[must_use]
470    pub const fn clock(&self) -> Clock {
471        Clock {
472            implicit_timezone: self.implicit_timezone,
473            current_date_time: self.current_date_time,
474        }
475    }
476
477    /// The implicit timezone in minutes.
478    #[must_use]
479    pub const fn implicit_timezone(&self) -> i16 {
480        self.implicit_timezone
481    }
482
483    /// The value of `fn:current-dateTime()`.
484    #[must_use]
485    pub const fn current_date_time(&self) -> DateTime {
486        self.current_date_time
487    }
488
489    pub(crate) fn regex(&self, pattern: &str, flags: &str) -> Result<Arc<XPathRegex>> {
490        let key = (pattern.to_owned(), flags.to_owned());
491        if let Some(regex) = self.regex_cache.borrow().get(&key) {
492            return Ok(Arc::clone(regex));
493        }
494        let shared = self.shared_regexes.and_then(|cache| cache.get(&key));
495        let regex = if let Some(regex) = shared {
496            regex
497        } else {
498            let regex = Arc::new(XPathRegex::new(pattern, flags)?);
499            if let Some(cache) = self.shared_regexes {
500                cache.insert(key.clone(), &regex);
501            }
502            regex
503        };
504        self.regex_cache
505            .borrow_mut()
506            .insert(key, Arc::clone(&regex));
507        Ok(regex)
508    }
509}
510
511/// The date-time `millis` after the epoch, in the timezone `offset` (minutes).
512fn date_time_from_millis(millis: i64, offset: i16) -> Result<DateTime> {
513    let local = millis
514        .checked_add(i64::from(offset) * 60_000)
515        .ok_or_else(|| crate::error::Error::new(ErrorCode::Fodt0001, "instant out of range"))?;
516    let days = local.div_euclid(86_400_000);
517    let in_day = local.rem_euclid(86_400_000);
518    // Civil date from days since 1970-01-01 (proleptic Gregorian).
519    let z = days + 719_468;
520    let era = z.div_euclid(146_097);
521    let doe = z - era * 146_097;
522    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
523    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
524    let mp = (5 * doy + 2) / 153;
525    let day = doy - (153 * mp + 2) / 5 + 1;
526    let month = if mp < 10 { mp + 3 } else { mp - 9 };
527    let year = yoe + era * 400 + i64::from(month <= 2);
528    let narrow = |v: i64| u8::try_from(v).unwrap_or(u8::MAX);
529    let year = i32::try_from(year)
530        .map_err(|_| crate::error::Error::new(ErrorCode::Fodt0001, "year out of range"))?;
531    let date = Date::new(year, narrow(month), narrow(day), Some(offset))?;
532    let seconds = in_day / 1000;
533    let nanos = u32::try_from((in_day % 1000) * 1_000_000).unwrap_or(0);
534    Ok(DateTime::new(
535        date,
536        narrow(seconds / 3600),
537        narrow(seconds / 60 % 60),
538        narrow(seconds % 60),
539        nanos,
540    )?)
541}
542
543/// The focus of an evaluation: the context item, position and size.
544#[derive(Debug, Clone)]
545pub struct Focus {
546    /// The context item.
547    pub item: Item,
548    /// The context position, from 1.
549    pub position: usize,
550    /// The context size.
551    pub size: usize,
552}
553
554/// Where an expression is evaluated: its focus, and the item `current()` returns.
555#[derive(Debug, Clone, Default)]
556pub struct Context {
557    /// The focus; `None` when the context item is absent.
558    pub focus: Option<Focus>,
559    /// The current item of XSLT (`current()`); `None` where it is absent.
560    pub current: Option<Item>,
561}
562
563impl Context {
564    /// No focus and no current item.
565    #[must_use]
566    pub fn new() -> Self {
567        Self::default()
568    }
569
570    /// The item as context item (position and size 1) and as current item, as for an
571    /// expression of an XSLT instruction evaluated with that item as context.
572    #[must_use]
573    pub fn for_item(item: Item) -> Self {
574        Self {
575            focus: Some(Focus {
576                item: item.clone(),
577                position: 1,
578                size: 1,
579            }),
580            current: Some(item),
581        }
582    }
583
584    /// The item as context and current item, at a given position in a sequence of `size`
585    /// items.
586    #[must_use]
587    pub fn at(item: Item, position: usize, size: usize) -> Self {
588        Self {
589            focus: Some(Focus {
590                item: item.clone(),
591                position,
592                size,
593            }),
594            current: Some(item),
595        }
596    }
597}
598
599#[cfg(test)]
600mod tests {
601    use super::*;
602
603    #[test]
604    fn a_regex_cache_is_shared_by_contexts() {
605        let cache = RegexCache::new();
606        let ns = einvoice_xpath::NamespaceMap::new();
607        let expr = einvoice_xpath::parse_expr(
608            "matches('abc', concat('^a', 'b')) and not(matches('x', concat('[', ']')))",
609            &ns,
610        );
611        // The second pattern is invalid, and is never cached.
612        let expr = crate::compile(&expr.unwrap(), &SimpleStaticContext::new()).unwrap();
613        for _ in 0..2 {
614            let dc = DynamicContext::new(&NoHost, Clock::from_unix_millis(0, 0).unwrap())
615                .with_regex_cache(&cache);
616            let error = expr
617                .effective_boolean_value(&dc, &Context::new())
618                .unwrap_err();
619            assert_eq!(error.code(), ErrorCode::Forx0002);
620            assert_eq!(dc.regex_cache.borrow().len(), 1);
621            assert_eq!(cache.entries.lock().unwrap().len(), 1);
622        }
623        let dc = DynamicContext::new(&NoHost, Clock::from_unix_millis(0, 0).unwrap())
624            .with_regex_cache(&cache);
625        let regex = dc.regex("^ab", "").unwrap();
626        assert!(Arc::ptr_eq(
627            &regex,
628            cache
629                .get(&("^ab".to_owned(), String::new()))
630                .as_ref()
631                .unwrap()
632        ));
633    }
634
635    #[test]
636    fn clock_conversions() {
637        let dt = date_time_from_millis(0, 0).unwrap();
638        assert_eq!(dt.to_string(), "1970-01-01T00:00:00Z");
639        let dt = date_time_from_millis(1_789_000_123_456, 60).unwrap();
640        assert_eq!(dt.to_string(), "2026-09-10T01:28:43.456+01:00");
641        let dt = date_time_from_millis(-1, -300).unwrap();
642        assert_eq!(dt.to_string(), "1969-12-31T18:59:59.999-05:00");
643        // An offset that takes the instant beyond i64: an error, never an overflow.
644        for (millis, offset) in [(i64::MAX, 840), (i64::MIN, -840)] {
645            assert_eq!(
646                date_time_from_millis(millis, offset).unwrap_err().code(),
647                ErrorCode::Fodt0001
648            );
649        }
650        let dt = date_time_from_millis(i64::MAX, 0).unwrap();
651        assert_eq!(dt.to_string(), "292278994-08-17T07:12:55.807Z");
652    }
653}