1use core::time::Duration;
2
3use jcore::tz::posix;
4
5use crate::{
6 SignedDuration, Timestamp, Unit, ZonedDateTime,
7 civil::{Date, DateTime, ISOWeekDate, Time},
8 error::{Error, fmt::temporal::Error as E},
9 fmt::{
10 Write,
11 buffer::{ArrayBuffer, BorrowedBuffer, BorrowedWriter},
12 temporal::{Pieces, PiecesOffset, TimeZoneAnnotationKind},
13 },
14 span::{Span, UnitSet},
15 tz::{Offset, TimeZone},
16};
17
18const REASONABLE_ZONED_LEN: usize = 72;
53
54const REASONABLE_PIECES_LEN: usize = 73;
67
68const REASONABLE_TIME_ZONE_LEN: usize = 32;
81
82const REASONABLE_POSIX_TIME_ZONE_LEN: usize = 20;
92
93const MAX_TIMESTAMP_ZULU_LEN: usize = 33;
98
99const MAX_TIMESTAMP_OFFSET_LEN: usize = 38;
104
105const MAX_DATETIME_LEN: usize = 32;
109
110const MAX_DATE_LEN: usize = 13;
114
115const MAX_TIME_LEN: usize = 18;
119
120const MAX_ISO_WEEK_DATE_LEN: usize = 13;
124
125const MAX_SPAN_LEN: usize = 78;
133
134const MAX_DURATION_LEN: usize = 36;
142
143#[derive(#[automatically_derived]impl ::core::clone::Clone for DateTimePrinter {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
DateTimePrinter {
lowercase: ::core::clone::Clone::clone(&self.lowercase),
separator: ::core::clone::Clone::clone(&self.separator),
precision: ::core::clone::Clone::clone(&self.precision),
}
}
}Clone, #[automatically_derived]impl ::core::fmt::Debug for DateTimePrinter {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f,
"DateTimePrinter lowercase separator precision", &self.lowercase,
&self.separator, &&self.precision)
}
}Debug)]
144pub(super) struct DateTimePrinter {
145 lowercase: bool,
146 separator: u8,
147 precision: Option<u8>,
148}
149
150impl DateTimePrinter {
151 pub(super) const fn new() -> DateTimePrinter {
152 DateTimePrinter { lowercase: false, separator: b'T', precision: None }
153 }
154
155 pub(super) const fn lowercase(self, yes: bool) -> DateTimePrinter {
156 DateTimePrinter { lowercase: yes, ..self }
157 }
158
159 pub(super) const fn separator(self, ascii_char: u8) -> DateTimePrinter {
160 if !ascii_char.is_ascii() {
{
::core::panicking::panic_fmt(format_args!("RFC3339 separator must be ASCII"));
}
};assert!(ascii_char.is_ascii(), "RFC3339 separator must be ASCII");
161 DateTimePrinter { separator: ascii_char, ..self }
162 }
163
164 pub(super) const fn precision(
165 self,
166 precision: Option<u8>,
167 ) -> DateTimePrinter {
168 DateTimePrinter { precision, ..self }
169 }
170
171 pub(super) fn print_zoned_datetime(
172 &self,
173 zdt: &ZonedDateTime,
174 wtr: &mut dyn Write,
175 ) -> Result<(), Error> {
176 const BASE: usize = 19 + 6 + 2;
195
196 let mut runtime_allocation = BASE
203 + zdt.time_zone().iana_name().map(|name| name.len()).unwrap_or(11);
204 if zdt.year() < 0 {
207 runtime_allocation += 3;
208 }
209 if zdt.subsec_nanosecond() != 0 || self.precision.is_some() {
213 runtime_allocation += 10;
214 }
215
216 if runtime_allocation <= REASONABLE_ZONED_LEN {
221 return BorrowedBuffer::with_writer::<REASONABLE_ZONED_LEN>(
222 wtr,
223 runtime_allocation,
224 |bbuf| Ok(self.print_zoned_datetime_buf(zdt, bbuf)),
225 );
226 }
227
228 let mut buf = ArrayBuffer::<REASONABLE_ZONED_LEN>::default();
231 let mut bbuf = buf.as_borrowed();
232 let mut wtr = BorrowedWriter::new(&mut bbuf, wtr);
233 self.print_zoned_datetime_wtr(zdt, &mut wtr)?;
234 wtr.finish()
235 }
236
237 fn print_zoned_datetime_buf(
238 &self,
239 zdt: &ZonedDateTime,
240 bbuf: &mut BorrowedBuffer<'_>,
241 ) {
242 self.print_datetime_buf(&zdt.datetime(), bbuf);
243 let tz = zdt.time_zone();
244 if tz.is_unknown() {
245 bbuf.write_str("Z[Etc/Unknown]");
246 } else {
247 self.print_offset_rounded_buf(&zdt.offset(), bbuf);
248 self.print_time_zone_annotation_buf(&tz, &zdt.offset(), bbuf);
249 }
250 }
251
252 fn print_zoned_datetime_wtr(
253 &self,
254 zdt: &ZonedDateTime,
255 wtr: &mut BorrowedWriter<'_, '_, '_>,
256 ) -> Result<(), Error> {
257 self.print_datetime_wtr(&zdt.datetime(), wtr)?;
258 let tz = zdt.time_zone();
259 if tz.is_unknown() {
260 wtr.write_str("Z[Etc/Unknown]")?;
261 } else {
262 self.print_offset_rounded_wtr(&zdt.offset(), wtr)?;
263 self.print_time_zone_annotation_wtr(&tz, &zdt.offset(), wtr)?;
264 }
265 Ok(())
266 }
267
268 pub(super) fn print_timestamp(
269 &self,
270 timestamp: &Timestamp,
271 wtr: &mut dyn Write,
272 ) -> Result<(), Error> {
273 let mut runtime_allocation = MAX_TIMESTAMP_ZULU_LEN;
274 if timestamp.subsec_nanosecond() == 0 && self.precision.is_none() {
276 runtime_allocation -= 10;
277 }
278 BorrowedBuffer::with_writer::<MAX_TIMESTAMP_ZULU_LEN>(
279 wtr,
280 runtime_allocation,
281 |bbuf| Ok(self.print_timestamp_buf(timestamp, bbuf)),
282 )
283 }
284
285 fn print_timestamp_buf(
286 &self,
287 timestamp: &Timestamp,
288 bbuf: &mut BorrowedBuffer<'_>,
289 ) {
290 let dt = Offset::UTC.to_datetime(*timestamp);
291 self.print_datetime_buf(&dt, bbuf);
292 self.print_zulu_buf(bbuf);
293 }
294
295 pub(super) fn print_timestamp_with_offset(
296 &self,
297 timestamp: &Timestamp,
298 offset: Offset,
299 wtr: &mut dyn Write,
300 ) -> Result<(), Error> {
301 let mut runtime_allocation = MAX_TIMESTAMP_OFFSET_LEN;
302 if timestamp.subsec_nanosecond() == 0 && self.precision.is_none() {
304 runtime_allocation -= 10;
305 }
306 BorrowedBuffer::with_writer::<MAX_TIMESTAMP_OFFSET_LEN>(
307 wtr,
308 runtime_allocation,
309 |bbuf| {
310 Ok(self
311 .print_timestamp_with_offset_buf(timestamp, offset, bbuf))
312 },
313 )
314 }
315
316 fn print_timestamp_with_offset_buf(
317 &self,
318 timestamp: &Timestamp,
319 offset: Offset,
320 bbuf: &mut BorrowedBuffer<'_>,
321 ) {
322 let dt = offset.to_datetime(*timestamp);
323 self.print_datetime_buf(&dt, bbuf);
324 self.print_offset_rounded_buf(&offset, bbuf);
325 }
326
327 pub(super) fn print_datetime(
328 &self,
329 dt: &DateTime,
330 wtr: &mut dyn Write,
331 ) -> Result<(), Error> {
332 let mut runtime_allocation = MAX_DATETIME_LEN;
333 if dt.subsec_nanosecond() == 0 && self.precision.is_none() {
335 runtime_allocation -= 10;
336 }
337 BorrowedBuffer::with_writer::<MAX_DATETIME_LEN>(
338 wtr,
339 runtime_allocation,
340 |bbuf| Ok(self.print_datetime_buf(dt, bbuf)),
341 )
342 }
343
344 fn print_datetime_buf(
345 &self,
346 dt: &DateTime,
347 bbuf: &mut BorrowedBuffer<'_>,
348 ) {
349 self.print_date_buf(&dt.date(), bbuf);
350 bbuf.write_ascii_char(if self.lowercase {
351 self.separator.to_ascii_lowercase()
352 } else {
353 self.separator
354 });
355 self.print_time_buf(&dt.time(), bbuf);
356 }
357
358 fn print_datetime_wtr(
359 &self,
360 dt: &DateTime,
361 wtr: &mut BorrowedWriter<'_, '_, '_>,
362 ) -> Result<(), Error> {
363 self.print_date_wtr(&dt.date(), wtr)?;
364 wtr.write_ascii_char(if self.lowercase {
365 self.separator.to_ascii_lowercase()
366 } else {
367 self.separator
368 })?;
369 self.print_time_wtr(&dt.time(), wtr)?;
370 Ok(())
371 }
372
373 pub(super) fn print_date(
374 &self,
375 date: &Date,
376 wtr: &mut dyn Write,
377 ) -> Result<(), Error> {
378 BorrowedBuffer::with_writer::<MAX_DATE_LEN>(
379 wtr,
380 MAX_DATE_LEN,
381 |bbuf| Ok(self.print_date_buf(date, bbuf)),
382 )
383 }
384
385 fn print_date_buf(&self, date: &Date, bbuf: &mut BorrowedBuffer<'_>) {
386 let year = date.year();
387 if year < 0 {
388 bbuf.write_str("-00");
389 }
390 bbuf.write_int_pad4(year.unsigned_abs());
391 bbuf.write_ascii_char(b'-');
392 bbuf.write_int_pad2(date.month().unsigned_abs());
393 bbuf.write_ascii_char(b'-');
394 bbuf.write_int_pad2(date.day().unsigned_abs());
395 }
396
397 fn print_date_wtr(
398 &self,
399 date: &Date,
400 wtr: &mut BorrowedWriter<'_, '_, '_>,
401 ) -> Result<(), Error> {
402 let year = date.year();
403 if year < 0 {
404 wtr.write_str("-00")?;
405 }
406 wtr.write_int_pad4(year.unsigned_abs())?;
407 wtr.write_ascii_char(b'-')?;
408 wtr.write_int_pad2(date.month().unsigned_abs())?;
409 wtr.write_ascii_char(b'-')?;
410 wtr.write_int_pad2(date.day().unsigned_abs())?;
411 Ok(())
412 }
413
414 pub(super) fn print_time(
415 &self,
416 time: &Time,
417 wtr: &mut dyn Write,
418 ) -> Result<(), Error> {
419 let mut runtime_allocation = MAX_TIME_LEN;
420 if time.subsec_nanosecond() == 0 && self.precision.is_none() {
422 runtime_allocation -= 10;
423 }
424 BorrowedBuffer::with_writer::<MAX_TIME_LEN>(
425 wtr,
426 runtime_allocation,
427 |bbuf| Ok(self.print_time_buf(time, bbuf)),
428 )
429 }
430
431 fn print_time_buf(&self, time: &Time, bbuf: &mut BorrowedBuffer<'_>) {
432 bbuf.write_int_pad2(time.hour().unsigned_abs());
433 bbuf.write_ascii_char(b':');
434 bbuf.write_int_pad2(time.minute().unsigned_abs());
435 bbuf.write_ascii_char(b':');
436 bbuf.write_int_pad2(time.second().unsigned_abs());
437 let fractional_nanosecond = time.subsec_nanosecond();
438 if self.precision.map_or(fractional_nanosecond != 0, |p| p > 0) {
439 bbuf.write_ascii_char(b'.');
440 bbuf.write_fraction(
441 self.precision,
442 fractional_nanosecond.unsigned_abs(),
443 );
444 }
445 }
446
447 fn print_time_wtr(
448 &self,
449 time: &Time,
450 wtr: &mut BorrowedWriter<'_, '_, '_>,
451 ) -> Result<(), Error> {
452 wtr.write_int_pad2(time.hour().unsigned_abs())?;
453 wtr.write_ascii_char(b':')?;
454 wtr.write_int_pad2(time.minute().unsigned_abs())?;
455 wtr.write_ascii_char(b':')?;
456 wtr.write_int_pad2(time.second().unsigned_abs())?;
457 let fractional_nanosecond = time.subsec_nanosecond();
458 if self.precision.map_or(fractional_nanosecond != 0, |p| p > 0) {
459 wtr.write_ascii_char(b'.')?;
460 wtr.write_fraction(
461 self.precision,
462 fractional_nanosecond.unsigned_abs(),
463 )?;
464 }
465 Ok(())
466 }
467
468 pub(super) fn print_time_zone(
469 &self,
470 tz: &TimeZone,
471 wtr: &mut dyn Write,
472 ) -> Result<(), Error> {
473 let mut buf = ArrayBuffer::<REASONABLE_TIME_ZONE_LEN>::default();
474 let mut bbuf = buf.as_borrowed();
475 let mut wtr = BorrowedWriter::new(&mut bbuf, wtr);
476 self.print_time_zone_wtr(tz, &mut wtr)?;
477 wtr.finish()
478 }
479
480 fn print_time_zone_wtr(
481 &self,
482 tz: &TimeZone,
483 wtr: &mut BorrowedWriter<'_, '_, '_>,
484 ) -> Result<(), Error> {
485 if let Some(iana_name) = tz.iana_name() {
486 return wtr.write_str(iana_name);
487 }
488 if tz.is_unknown() {
489 return wtr.write_str("Etc/Unknown");
490 }
491 if let Ok(offset) = tz.to_fixed_offset() {
492 return self.print_offset_full_precision(&offset, wtr);
493 }
494 if let Some(posix_tz) = tz.posix_tz() {
495 return self.print_posix_time_zone(posix_tz, wtr);
496 }
497 Err(Error::from(E::PrintTimeZoneFailure))
507 }
508
509 pub(super) fn print_posix_time_zone(
510 &self,
511 posix_tz: &posix::TimeZone,
512 wtr: &mut dyn Write,
513 ) -> Result<(), Error> {
514 let mut buf = ArrayBuffer::<REASONABLE_POSIX_TIME_ZONE_LEN>::default();
515 let mut bbuf = buf.as_borrowed();
516 let mut wtr = BorrowedWriter::new(&mut bbuf, wtr);
517 self.print_posix_time_zone_wtr(posix_tz, &mut wtr)?;
518 wtr.finish()
519 }
520
521 fn print_posix_time_zone_wtr(
522 &self,
523 tz: &posix::TimeZone,
524 wtr: &mut BorrowedWriter<'_, '_, '_>,
525 ) -> Result<(), Error> {
526 self.print_posix_abbreviation_wtr(tz.std_abbrev.as_str(), wtr)?;
527 self.print_posix_offset_wtr(&tz.std_offset, wtr)?;
528 if let Some(ref dst) = tz.dst {
529 self.print_posix_dst_wtr(dst, &tz.std_offset, wtr)?;
530 }
531 Ok(())
532 }
533
534 fn print_posix_dst_wtr(
535 &self,
536 dst: &posix::Dst,
537 std_offset: &jcore::tz::Offset,
538 wtr: &mut BorrowedWriter<'_, '_, '_>,
539 ) -> Result<(), Error> {
540 self.print_posix_abbreviation_wtr(dst.abbrev.as_ref(), wtr)?;
541 if Some(dst.offset) != std_offset.checked_add(3600).ok() {
545 self.print_posix_offset_wtr(&dst.offset, wtr)?;
546 }
547 wtr.write_ascii_char(b',')?;
548 self.print_posix_rule_wtr(&dst.rule, wtr)?;
549 Ok(())
550 }
551
552 fn print_posix_rule_wtr(
553 &self,
554 rule: &posix::Rule,
555 wtr: &mut BorrowedWriter<'_, '_, '_>,
556 ) -> Result<(), Error> {
557 self.print_posix_day_time_wtr(&rule.start, wtr)?;
558 wtr.write_ascii_char(b',')?;
559 self.print_posix_day_time_wtr(&rule.end, wtr)?;
560 Ok(())
561 }
562
563 fn print_posix_day_time_wtr(
564 &self,
565 day_time: &posix::DayTime,
566 wtr: &mut BorrowedWriter<'_, '_, '_>,
567 ) -> Result<(), Error> {
568 self.print_posix_day_wtr(&day_time.date, wtr)?;
569 if day_time.time != posix::TransitionCivilTime::DEFAULT {
571 wtr.write_ascii_char(b'/')?;
572 self.print_posix_time_wtr(&day_time.time, wtr)?;
573 }
574 Ok(())
575 }
576
577 fn print_posix_day_wtr(
578 &self,
579 day: &posix::Day,
580 wtr: &mut BorrowedWriter<'_, '_, '_>,
581 ) -> Result<(), Error> {
582 match *day {
583 posix::Day::JulianOne(n) => {
584 wtr.write_ascii_char(b'J')?;
585 wtr.write_int(n.unsigned_abs())?;
586 Ok(())
587 }
588 posix::Day::JulianZero(n) => wtr.write_int(n.unsigned_abs()),
589 posix::Day::WeekdayOfMonth { month, week, weekday } => {
590 wtr.write_ascii_char(b'M')?;
591 wtr.write_int(month.unsigned_abs())?;
592 wtr.write_ascii_char(b'.')?;
593 wtr.write_int1(week.unsigned_abs())?;
594 wtr.write_ascii_char(b'.')?;
595 wtr.write_int1(
596 weekday.to_sunday_zero_offset().unsigned_abs(),
597 )?;
598 Ok(())
599 }
600 }
601 }
602
603 fn print_posix_time_wtr(
604 &self,
605 time: &posix::TransitionCivilTime,
606 wtr: &mut BorrowedWriter<'_, '_, '_>,
607 ) -> Result<(), Error> {
608 if time.second.is_negative() {
609 wtr.write_ascii_char(b'-')?;
610 }
613 self.print_posix_time_offset_seconds_wtr(time.second, wtr)
614 }
615
616 fn print_posix_offset_wtr(
617 &self,
618 offset: &jcore::tz::Offset,
619 wtr: &mut BorrowedWriter<'_, '_, '_>,
620 ) -> Result<(), Error> {
621 if offset.seconds() > 0 {
625 wtr.write_ascii_char(b'-')?;
626 }
627 self.print_posix_time_offset_seconds_wtr(offset.seconds(), wtr)
628 }
629
630 fn print_posix_time_offset_seconds_wtr(
631 &self,
632 second: i32,
633 wtr: &mut BorrowedWriter<'_, '_, '_>,
634 ) -> Result<(), Error> {
635 let second = second.unsigned_abs();
636 let h = second / 3600;
637 let m = (second / 60) % 60;
638 let s = second % 60;
639 wtr.write_int(h)?;
640 if m != 0 || s != 0 {
641 wtr.write_ascii_char(b':')?;
642 wtr.write_int_pad2(m)?;
643 if s != 0 {
644 wtr.write_ascii_char(b':')?;
645 wtr.write_int_pad2(s)?;
646 }
647 }
648 Ok(())
649 }
650
651 fn print_posix_abbreviation_wtr(
652 &self,
653 abbreviation: &str,
654 wtr: &mut BorrowedWriter<'_, '_, '_>,
655 ) -> Result<(), Error> {
656 if abbreviation.chars().any(|ch| ch == '+' || ch == '-') {
657 wtr.write_ascii_char(b'<')?;
658 wtr.write_str(abbreviation)?;
659 wtr.write_ascii_char(b'>')?;
660 } else {
661 wtr.write_str(abbreviation)?;
662 }
663 Ok(())
664 }
665
666 pub(super) fn print_pieces(
667 &self,
668 pieces: &Pieces,
669 wtr: &mut dyn Write,
670 ) -> Result<(), Error> {
671 let mut buf = ArrayBuffer::<REASONABLE_PIECES_LEN>::default();
678 let mut bbuf = buf.as_borrowed();
679 let mut wtr = BorrowedWriter::new(&mut bbuf, wtr);
680 self.print_pieces_wtr(pieces, &mut wtr)?;
681 wtr.finish()
682 }
683
684 fn print_pieces_wtr(
685 &self,
686 pieces: &Pieces,
687 wtr: &mut BorrowedWriter<'_, '_, '_>,
688 ) -> Result<(), Error> {
689 if let Some(time) = pieces.time() {
690 let dt = DateTime::from_parts(pieces.date(), time);
691 self.print_datetime_wtr(&dt, wtr)?;
692 if let Some(poffset) = pieces.offset() {
693 self.print_pieces_offset(&poffset, wtr)?;
694 }
695 } else if let Some(poffset) = pieces.offset() {
696 let dt = DateTime::from_parts(pieces.date(), Time::midnight());
700 self.print_datetime_wtr(&dt, wtr)?;
701 self.print_pieces_offset(&poffset, wtr)?;
702 } else {
703 self.print_date_wtr(&pieces.date(), wtr)?;
707 }
708 if let Some(ann) = pieces.time_zone_annotation() {
713 wtr.write_ascii_char(b'[')?;
714 if ann.is_critical() {
715 wtr.write_ascii_char(b'!')?;
716 }
717 match *ann.kind() {
718 TimeZoneAnnotationKind::Named(ref name) => {
719 wtr.write_str(name.as_str())?;
720 }
721 TimeZoneAnnotationKind::Offset(offset) => {
722 self.print_offset_rounded_wtr(&offset, wtr)?;
723 }
724 }
725 wtr.write_ascii_char(b']')?;
726 }
727 Ok(())
728 }
729
730 pub(super) fn print_iso_week_date(
731 &self,
732 iso_week_date: &ISOWeekDate,
733 wtr: &mut dyn Write,
734 ) -> Result<(), Error> {
735 BorrowedBuffer::with_writer::<MAX_ISO_WEEK_DATE_LEN>(
736 wtr,
737 MAX_ISO_WEEK_DATE_LEN,
738 |bbuf| Ok(self.print_iso_week_date_buf(iso_week_date, bbuf)),
739 )
740 }
741
742 fn print_iso_week_date_buf(
743 &self,
744 iso_week_date: &ISOWeekDate,
745 bbuf: &mut BorrowedBuffer<'_>,
746 ) {
747 let year = iso_week_date.year();
748 if year < 0 {
749 bbuf.write_str("-00");
750 }
751 bbuf.write_int_pad4(year.unsigned_abs());
752 bbuf.write_ascii_char(b'-');
753 bbuf.write_ascii_char(if self.lowercase { b'w' } else { b'W' });
754 bbuf.write_int_pad2(iso_week_date.week().unsigned_abs());
755 bbuf.write_ascii_char(b'-');
756 bbuf.write_int1(
757 iso_week_date.weekday().to_monday_one_offset().unsigned_abs(),
758 );
759 }
760
761 fn print_pieces_offset(
762 &self,
763 poffset: &PiecesOffset,
764 wtr: &mut BorrowedWriter<'_, '_, '_>,
765 ) -> Result<(), Error> {
766 match *poffset {
767 PiecesOffset::Zulu => self.print_zulu_wtr(wtr),
768 PiecesOffset::Numeric(ref noffset) => {
769 if noffset.offset().is_zero() && noffset.is_negative() {
770 wtr.write_str("-00:00")
771 } else {
772 self.print_offset_rounded_wtr(&noffset.offset(), wtr)
773 }
774 }
775 }
776 }
777
778 fn print_offset_rounded_buf(
783 &self,
784 offset: &Offset,
785 bbuf: &mut BorrowedBuffer<'_>,
786 ) {
787 bbuf.write_ascii_char(if offset.is_negative() { b'-' } else { b'+' });
788 let (offset_hours, offset_minutes) = offset.round_to_nearest_minute();
789 bbuf.write_int_pad2(offset_hours);
790 bbuf.write_ascii_char(b':');
791 bbuf.write_int_pad2(offset_minutes);
792 }
793
794 fn print_offset_rounded_wtr(
799 &self,
800 offset: &Offset,
801 wtr: &mut BorrowedWriter<'_, '_, '_>,
802 ) -> Result<(), Error> {
803 wtr.write_ascii_char(if offset.is_negative() { b'-' } else { b'+' })?;
804 let (offset_hours, offset_minutes) = offset.round_to_nearest_minute();
805 wtr.write_int_pad2(offset_hours)?;
806 wtr.write_ascii_char(b':')?;
807 wtr.write_int_pad2(offset_minutes)?;
808 Ok(())
809 }
810
811 fn print_offset_full_precision(
817 &self,
818 offset: &Offset,
819 wtr: &mut BorrowedWriter<'_, '_, '_>,
820 ) -> Result<(), Error> {
821 wtr.write_ascii_char(if offset.is_negative() { b'-' } else { b'+' })?;
822 let hours = offset.part_hours().unsigned_abs();
823 let minutes = offset.part_minutes().unsigned_abs();
824 let seconds = offset.part_seconds().unsigned_abs();
825 wtr.write_int_pad2(hours)?;
826 wtr.write_ascii_char(b':')?;
827 wtr.write_int_pad2(minutes)?;
828 if seconds > 0 {
829 wtr.write_ascii_char(b':')?;
830 wtr.write_int_pad2(seconds)?;
831 }
832 Ok(())
833 }
834
835 fn print_zulu_buf(&self, bbuf: &mut BorrowedBuffer<'_>) {
840 bbuf.write_ascii_char(if self.lowercase { b'z' } else { b'Z' });
841 }
842
843 fn print_zulu_wtr(
848 &self,
849 wtr: &mut BorrowedWriter<'_, '_, '_>,
850 ) -> Result<(), Error> {
851 wtr.write_ascii_char(if self.lowercase { b'z' } else { b'Z' })
852 }
853
854 fn print_time_zone_annotation_buf(
862 &self,
863 time_zone: &TimeZone,
864 offset: &Offset,
865 bbuf: &mut BorrowedBuffer<'_>,
866 ) {
867 bbuf.write_ascii_char(b'[');
868 if let Some(iana_name) = time_zone.iana_name() {
869 bbuf.write_str(iana_name);
870 } else {
871 self.print_offset_rounded_buf(offset, bbuf);
872 }
873 bbuf.write_ascii_char(b']');
874 }
875
876 fn print_time_zone_annotation_wtr(
884 &self,
885 time_zone: &TimeZone,
886 offset: &Offset,
887 wtr: &mut BorrowedWriter<'_, '_, '_>,
888 ) -> Result<(), Error> {
889 wtr.write_ascii_char(b'[')?;
890 if let Some(iana_name) = time_zone.iana_name() {
891 wtr.write_str(iana_name)?;
892 } else {
893 self.print_offset_rounded_wtr(offset, wtr)?;
894 }
895 wtr.write_ascii_char(b']')?;
896 Ok(())
897 }
898}
899
900impl Default for DateTimePrinter {
901 fn default() -> DateTimePrinter {
902 DateTimePrinter::new()
903 }
904}
905
906#[derive(#[automatically_derived]impl ::core::fmt::Debug for SpanPrinter {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f,
"SpanPrinter designators", &&self.designators)
}
}Debug)]
910pub(super) struct SpanPrinter {
911 designators: &'static Designators,
913}
914
915impl SpanPrinter {
916 pub(super) const fn new() -> SpanPrinter {
918 SpanPrinter { designators: DESIGNATORS_UPPERCASE }
919 }
920
921 pub(super) const fn lowercase(self, yes: bool) -> SpanPrinter {
925 SpanPrinter {
926 designators: if yes {
927 DESIGNATORS_LOWERCASE
928 } else {
929 DESIGNATORS_UPPERCASE
930 },
931 }
932 }
933
934 pub(super) fn print_span(
938 &self,
939 span: &Span,
940 wtr: &mut dyn Write,
941 ) -> Result<(), Error> {
942 let mut buf = ArrayBuffer::<MAX_SPAN_LEN>::default();
943 let mut bbuf = buf.as_borrowed();
944 self.print_span_impl(span, &mut bbuf);
945 wtr.write_str(bbuf.filled())
946 }
947
948 fn print_span_impl(&self, span: &Span, bbuf: &mut BorrowedBuffer<'_>) {
949 static SUBSECOND: UnitSet = UnitSet::from_slice(&[
950 Unit::Millisecond,
951 Unit::Microsecond,
952 Unit::Nanosecond,
953 ]);
954
955 if span.is_negative() {
956 bbuf.write_ascii_char(b'-');
957 }
958 bbuf.write_ascii_char(b'P');
959
960 let units = span.units();
961 if units.contains(Unit::Year) {
962 bbuf.write_int(span.get_years_unsigned());
963 bbuf.write_ascii_char(self.label(Unit::Year));
964 }
965 if units.contains(Unit::Month) {
966 bbuf.write_int(span.get_months_unsigned());
967 bbuf.write_ascii_char(self.label(Unit::Month));
968 }
969 if units.contains(Unit::Week) {
970 bbuf.write_int(span.get_weeks_unsigned());
971 bbuf.write_ascii_char(self.label(Unit::Week));
972 }
973 if units.contains(Unit::Day) {
974 bbuf.write_int(span.get_days_unsigned());
975 bbuf.write_ascii_char(self.label(Unit::Day));
976 }
977
978 if units.only_time().is_empty() {
979 if units.only_calendar().is_empty() {
980 bbuf.write_ascii_char(b'T');
981 bbuf.write_ascii_char(b'0');
982 bbuf.write_ascii_char(self.label(Unit::Second));
983 }
984 return;
985 }
986
987 bbuf.write_ascii_char(b'T');
988
989 if units.contains(Unit::Hour) {
990 bbuf.write_int(span.get_hours_unsigned());
991 bbuf.write_ascii_char(self.label(Unit::Hour));
992 }
993 if units.contains(Unit::Minute) {
994 bbuf.write_int(span.get_minutes_unsigned());
995 bbuf.write_ascii_char(self.label(Unit::Minute));
996 }
997
998 let has_subsecond = !units.intersection(SUBSECOND).is_empty();
1003 if units.contains(Unit::Second) && !has_subsecond {
1004 bbuf.write_int(span.get_seconds_unsigned());
1005 bbuf.write_ascii_char(self.label(Unit::Second));
1006 } else if has_subsecond {
1007 let (seconds, millis, micros, nanos) = (
1013 Duration::from_secs(span.get_seconds_unsigned()),
1014 Duration::from_millis(span.get_milliseconds_unsigned()),
1015 Duration::from_micros(span.get_microseconds_unsigned()),
1016 Duration::from_nanos(span.get_nanoseconds_unsigned()),
1017 );
1018 let total = seconds + millis + micros + nanos;
1022 let (secs, subsecs) = (total.as_secs(), total.subsec_nanos());
1023 bbuf.write_int(secs);
1024 if subsecs != 0 {
1025 bbuf.write_ascii_char(b'.');
1026 bbuf.write_fraction(None, subsecs);
1027 }
1028 bbuf.write_ascii_char(self.label(Unit::Second));
1029 }
1030 }
1031
1032 pub(super) fn print_signed_duration(
1036 &self,
1037 dur: &SignedDuration,
1038 wtr: &mut dyn Write,
1039 ) -> Result<(), Error> {
1040 let mut buf = ArrayBuffer::<MAX_DURATION_LEN>::default();
1041 let mut bbuf = buf.as_borrowed();
1042 if dur.is_negative() {
1043 bbuf.write_ascii_char(b'-');
1044 }
1045 self.print_unsigned_duration_impl(&dur.unsigned_abs(), &mut bbuf);
1046 wtr.write_str(bbuf.filled())
1047 }
1048
1049 pub(super) fn print_unsigned_duration(
1053 &self,
1054 dur: &Duration,
1055 wtr: &mut dyn Write,
1056 ) -> Result<(), Error> {
1057 let mut buf = ArrayBuffer::<MAX_DURATION_LEN>::default();
1058 let mut bbuf = buf.as_borrowed();
1059 self.print_unsigned_duration_impl(dur, &mut bbuf);
1060 wtr.write_str(bbuf.filled())
1061 }
1062
1063 fn print_unsigned_duration_impl(
1064 &self,
1065 dur: &Duration,
1066 bbuf: &mut BorrowedBuffer<'_>,
1067 ) {
1068 bbuf.write_ascii_char(b'P');
1069 bbuf.write_ascii_char(b'T');
1070
1071 let (mut secs, nanos) = (dur.as_secs(), dur.subsec_nanos());
1072 let non_zero_greater_than_second = secs >= 60;
1073 if non_zero_greater_than_second {
1074 let hours = secs / (60 * 60);
1075 secs %= 60 * 60;
1076 let minutes = secs / 60;
1077 secs = secs % 60;
1078 if hours != 0 {
1079 bbuf.write_int(hours);
1080 bbuf.write_ascii_char(self.label(Unit::Hour));
1081 }
1082 if minutes != 0 {
1083 bbuf.write_int(minutes);
1084 bbuf.write_ascii_char(self.label(Unit::Minute));
1085 }
1086 }
1087 if !non_zero_greater_than_second || secs != 0 || nanos != 0 {
1088 bbuf.write_int(secs);
1089 if nanos != 0 {
1090 bbuf.write_ascii_char(b'.');
1091 bbuf.write_fraction(None, nanos);
1092 }
1093 bbuf.write_ascii_char(self.label(Unit::Second));
1094 }
1095 }
1096
1097 fn label(&self, unit: Unit) -> u8 {
1101 self.designators.designator(unit)
1102 }
1103}
1104
1105#[derive(#[automatically_derived]impl ::core::clone::Clone for Designators {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
Designators { map: ::core::clone::Clone::clone(&self.map) }
}
}Clone, #[automatically_derived]impl ::core::fmt::Debug for Designators {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Designators map", &&self.map)
}
}Debug)]
1106struct Designators {
1107 map: [u8; 10],
1109}
1110
1111const DESIGNATORS_UPPERCASE: &'static Designators = &Designators {
1112 map: [0, 0, 0, b'S', b'M', b'H', b'D', b'W', b'M', b'Y'],
1115};
1116
1117const DESIGNATORS_LOWERCASE: &'static Designators = &Designators {
1118 map: [0, 0, 0, b's', b'm', b'h', b'd', b'w', b'm', b'y'],
1121};
1122
1123impl Designators {
1124 fn designator(&self, unit: Unit) -> u8 {
1126 self.map[unit as usize]
1127 }
1128}
1129
1130#[cfg(feature = "alloc")]
1131#[cfg(test)]
1132mod tests {
1133 use alloc::string::{String, ToString};
1134
1135 use crate::{
1136 civil::{Weekday, date, time},
1137 fmt::StdFmtWrite,
1138 span::ToSpan,
1139 util::b,
1140 };
1141
1142 use super::*;
1143
1144 #[test]
1145 fn print_zoned_datetime() {
1146 if crate::tz::db().is_definitively_empty() {
1147 return;
1148 }
1149
1150 let p = || DateTimePrinter::new();
1151 let via_io = |dtp: DateTimePrinter, zdt| {
1152 let mut buf = String::new();
1153 dtp.print_zoned_datetime(&zdt, &mut StdFmtWrite(&mut buf))
1154 .unwrap();
1155 buf
1156 };
1157 let to_string = |dtp: DateTimePrinter, zdt| {
1158 let mut buf = String::new();
1159 dtp.print_zoned_datetime(&zdt, &mut buf).unwrap();
1160 let got_via_io = via_io(dtp, zdt);
1161 assert_eq!(
1162 buf, got_via_io,
1163 "expected writes to `&mut String` to match `&mut StdFmtWrite`"
1164 );
1165 buf
1166 };
1167
1168 let dt = date(2024, 3, 10).at(5, 34, 45, 0);
1169 let zdt = dt.in_tz("America/New_York").unwrap();
1170 let got = to_string(p(), zdt);
1171 assert_eq!(got, "2024-03-10T05:34:45-04:00[America/New_York]");
1172
1173 let dt = date(2024, 3, 10).at(5, 34, 45, 0);
1174 let zdt = dt.in_tz("America/New_York").unwrap();
1175 let zdt = zdt.with_time_zone(TimeZone::UTC);
1176 let got = to_string(p(), zdt);
1177 assert_eq!(got, "2024-03-10T09:34:45+00:00[UTC]");
1178
1179 let dt = date(2024, 3, 10).at(5, 34, 45, 0);
1180 let zdt = dt.to_zoned_datetime(TimeZone::fixed(Offset::MIN)).unwrap();
1181 let got = to_string(p(), zdt);
1182 assert_eq!(got, "2024-03-10T05:34:45-25:59[-25:59]");
1183
1184 let dt = date(2024, 3, 10).at(5, 34, 45, 0);
1185 let zdt = dt.to_zoned_datetime(TimeZone::fixed(Offset::MAX)).unwrap();
1186 let got = to_string(p(), zdt);
1187 assert_eq!(got, "2024-03-10T05:34:45+25:59[+25:59]");
1188
1189 let dt = date(2024, 3, 10).at(5, 34, 45, 123_456_789);
1190 let zdt = dt.in_tz("America/New_York").unwrap();
1191 let got = to_string(p(), zdt);
1192 assert_eq!(
1193 got,
1194 "2024-03-10T05:34:45.123456789-04:00[America/New_York]"
1195 );
1196
1197 let dt = date(2024, 3, 10).at(5, 34, 45, 0);
1198 let zdt = dt.in_tz("America/New_York").unwrap();
1199 let got = to_string(p().precision(Some(9)), zdt);
1200 assert_eq!(
1201 got,
1202 "2024-03-10T05:34:45.000000000-04:00[America/New_York]"
1203 );
1204
1205 let dt = date(-9999, 3, 1).at(23, 59, 59, 999_999_999);
1206 let zdt = dt.in_tz("America/Argentina/Buenos_Aires").unwrap();
1207 let got = to_string(p().precision(Some(9)), zdt);
1208 assert_eq!(
1209 got,
1210 "-009999-03-01T23:59:59.999999999-03:54[America/Argentina/Buenos_Aires]",
1211 );
1212
1213 let tz = TimeZone::tzif(
1216 "Abc/Def/Ghi/Jkl/Mno/Pqr/Stu/Vwx/Yzz/Abc/Def/Ghi/Jkl/Mno/Pqr/Stu/Vwx/Yzz/Abc/Def/Ghi/Jkl/Mno/Pqr/Stu/Vwx/Yzz",
1217 crate::tz::testdata::TzifTestFile::get("America/New_York").data,
1218 ).unwrap();
1219 let dt = date(-9999, 3, 1).at(23, 59, 59, 999_999_999);
1220 let zdt = dt.to_zoned_datetime(tz).unwrap();
1221 let got = to_string(p().precision(Some(9)), zdt);
1222 assert_eq!(
1223 got,
1224 "-009999-03-01T23:59:59.999999999-04:56[Abc/Def/Ghi/Jkl/Mno/Pqr/Stu/Vwx/Yzz/Abc/Def/Ghi/Jkl/Mno/Pqr/Stu/Vwx/Yzz/Abc/Def/Ghi/Jkl/Mno/Pqr/Stu/Vwx/Yzz]",
1225 );
1226 }
1227
1228 #[test]
1229 fn print_timestamp_zulu() {
1230 let p = || DateTimePrinter::new();
1231 let via_io = |dtp: DateTimePrinter, ts| {
1232 let mut buf = String::new();
1233 dtp.print_timestamp(&ts, &mut StdFmtWrite(&mut buf)).unwrap();
1234 buf
1235 };
1236 let to_string = |dtp: DateTimePrinter, ts| {
1237 let mut buf = String::new();
1238 dtp.print_timestamp(&ts, &mut buf).unwrap();
1239 let got_via_io = via_io(dtp, ts);
1240 assert_eq!(
1241 buf, got_via_io,
1242 "expected writes to `&mut String` to match `&mut StdFmtWrite`"
1243 );
1244 buf
1245 };
1246
1247 let tz = TimeZone::fixed(-Offset::constant(4));
1248
1249 let dt = date(2024, 3, 10).at(5, 34, 45, 0);
1250 let zoned: ZonedDateTime = dt.to_zoned_datetime(tz.clone()).unwrap();
1251 let got = to_string(p(), zoned.timestamp());
1252 assert_eq!(got, "2024-03-10T09:34:45Z");
1253
1254 let dt = date(-2024, 3, 10).at(5, 34, 45, 0);
1255 let zoned: ZonedDateTime = dt.to_zoned_datetime(tz.clone()).unwrap();
1256 let got = to_string(p(), zoned.timestamp());
1257 assert_eq!(got, "-002024-03-10T09:34:45Z");
1258
1259 let dt = date(2024, 3, 10).at(5, 34, 45, 123_456_789);
1260 let zoned: ZonedDateTime = dt.to_zoned_datetime(tz.clone()).unwrap();
1261 let got = to_string(p(), zoned.timestamp());
1262 assert_eq!(got, "2024-03-10T09:34:45.123456789Z");
1263
1264 let dt = date(2024, 3, 10).at(5, 34, 45, 0);
1265 let zoned: ZonedDateTime = dt.to_zoned_datetime(tz.clone()).unwrap();
1266 let got = to_string(p().precision(Some(9)), zoned.timestamp());
1267 assert_eq!(got, "2024-03-10T09:34:45.000000000Z");
1268 }
1269
1270 #[test]
1271 fn print_timestamp_with_offset() {
1272 let p = || DateTimePrinter::new();
1273 let via_io = |dtp: DateTimePrinter, ts, offset| {
1274 let mut buf = String::new();
1275 dtp.print_timestamp_with_offset(
1276 &ts,
1277 offset,
1278 &mut StdFmtWrite(&mut buf),
1279 )
1280 .unwrap();
1281 buf
1282 };
1283 let to_string = |dtp: DateTimePrinter, ts, offset| {
1284 let mut buf = String::new();
1285 dtp.print_timestamp_with_offset(&ts, offset, &mut buf).unwrap();
1286 let got_via_io = via_io(dtp, ts, offset);
1287 assert_eq!(
1288 buf, got_via_io,
1289 "expected writes to `&mut String` to match `&mut StdFmtWrite`"
1290 );
1291 buf
1292 };
1293
1294 let tz = TimeZone::fixed(-Offset::constant(4));
1295
1296 let dt = date(2024, 3, 10).at(5, 34, 45, 0);
1297 let zoned: ZonedDateTime = dt.to_zoned_datetime(tz.clone()).unwrap();
1298 let got = to_string(p(), zoned.timestamp(), zoned.offset());
1299 assert_eq!(got, "2024-03-10T05:34:45-04:00");
1300
1301 let dt = date(-2024, 3, 10).at(5, 34, 45, 0);
1302 let zoned: ZonedDateTime = dt.to_zoned_datetime(tz.clone()).unwrap();
1303 let got = to_string(p(), zoned.timestamp(), zoned.offset());
1304 assert_eq!(got, "-002024-03-10T05:34:45-04:00");
1305
1306 let dt = date(2024, 3, 10).at(5, 34, 45, 123_456_789);
1307 let zoned: ZonedDateTime = dt.to_zoned_datetime(tz.clone()).unwrap();
1308 let got = to_string(p(), zoned.timestamp(), zoned.offset());
1309 assert_eq!(got, "2024-03-10T05:34:45.123456789-04:00");
1310
1311 let dt = date(2024, 3, 10).at(5, 34, 45, 0);
1312 let zoned: ZonedDateTime = dt.to_zoned_datetime(tz.clone()).unwrap();
1313 let got = to_string(
1314 p().precision(Some(9)),
1315 zoned.timestamp(),
1316 zoned.offset(),
1317 );
1318 assert_eq!(got, "2024-03-10T05:34:45.000000000-04:00");
1319
1320 let dt = DateTime::MIN;
1321 let zoned: ZonedDateTime =
1322 dt.to_zoned_datetime(TimeZone::fixed(Offset::MIN)).unwrap();
1323 let got = to_string(
1324 p().precision(Some(9)),
1325 zoned.timestamp(),
1326 zoned.offset(),
1327 );
1328 assert_eq!(got, "-009999-01-01T00:00:00.000000000-25:59");
1329 }
1330
1331 #[test]
1332 fn print_datetime() {
1333 let p = || DateTimePrinter::new();
1334 let via_io = |dtp: DateTimePrinter, dt| {
1335 let mut buf = String::new();
1336 dtp.print_datetime(&dt, &mut StdFmtWrite(&mut buf)).unwrap();
1337 buf
1338 };
1339 let to_string = |dtp: DateTimePrinter, dt| {
1340 let mut buf = String::new();
1341 dtp.print_datetime(&dt, &mut buf).unwrap();
1342 let got_via_io = via_io(dtp, dt);
1343 assert_eq!(
1344 buf, got_via_io,
1345 "expected writes to `&mut String` to match `&mut StdFmtWrite`"
1346 );
1347 buf
1348 };
1349
1350 let dt = date(2024, 3, 10).at(5, 34, 45, 0);
1351 let got = to_string(p(), dt);
1352 assert_eq!(got, "2024-03-10T05:34:45");
1353
1354 let dt = date(-2024, 3, 10).at(5, 34, 45, 0);
1355 let got = to_string(p(), dt);
1356 assert_eq!(got, "-002024-03-10T05:34:45");
1357
1358 let dt = date(2024, 3, 10).at(5, 34, 45, 123_456_789);
1359 let got = to_string(p(), dt);
1360 assert_eq!(got, "2024-03-10T05:34:45.123456789");
1361
1362 let dt = date(2024, 3, 10).at(5, 34, 45, 0);
1363 let got = to_string(p().precision(Some(9)), dt);
1364 assert_eq!(got, "2024-03-10T05:34:45.000000000");
1365
1366 let dt = DateTime::MIN;
1367 let got = to_string(p().precision(Some(9)), dt);
1368 assert_eq!(got, "-009999-01-01T00:00:00.000000000");
1369 }
1370
1371 #[test]
1372 fn print_date() {
1373 let p = || DateTimePrinter::new();
1374 let via_io = |dtp: DateTimePrinter, date| {
1375 let mut buf = String::new();
1376 dtp.print_date(&date, &mut StdFmtWrite(&mut buf)).unwrap();
1377 buf
1378 };
1379 let to_string = |dtp: DateTimePrinter, date| {
1380 let mut buf = String::new();
1381 dtp.print_date(&date, &mut buf).unwrap();
1382 let got_via_io = via_io(dtp, date);
1383 assert_eq!(
1384 buf, got_via_io,
1385 "expected writes to `&mut String` to match `&mut StdFmtWrite`"
1386 );
1387 buf
1388 };
1389
1390 let d = date(2024, 3, 10);
1391 let got = to_string(p(), d);
1392 assert_eq!(got, "2024-03-10");
1393
1394 let d = date(-2024, 3, 10);
1395 let got = to_string(p(), d);
1396 assert_eq!(got, "-002024-03-10");
1397
1398 let d = date(2024, 3, 10);
1399 let got = to_string(p(), d);
1400 assert_eq!(got, "2024-03-10");
1401
1402 let d = Date::MIN;
1403 let got = to_string(p().precision(Some(9)), d);
1404 assert_eq!(got, "-009999-01-01");
1405 }
1406
1407 #[test]
1408 fn print_time() {
1409 let p = || DateTimePrinter::new();
1410 let via_io = |dtp: DateTimePrinter, time| {
1411 let mut buf = String::new();
1412 dtp.print_time(&time, &mut StdFmtWrite(&mut buf)).unwrap();
1413 buf
1414 };
1415 let to_string = |dtp: DateTimePrinter, time| {
1416 let mut buf = String::new();
1417 dtp.print_time(&time, &mut buf).unwrap();
1418 let got_via_io = via_io(dtp, time);
1419 assert_eq!(
1420 buf, got_via_io,
1421 "expected writes to `&mut String` to match `&mut StdFmtWrite`"
1422 );
1423 buf
1424 };
1425
1426 let t = time(5, 34, 45, 0);
1427 let got = to_string(p(), t);
1428 assert_eq!(got, "05:34:45");
1429
1430 let t = time(5, 34, 45, 0);
1431 let got = to_string(p(), t);
1432 assert_eq!(got, "05:34:45");
1433
1434 let t = time(5, 34, 45, 123_456_789);
1435 let got = to_string(p(), t);
1436 assert_eq!(got, "05:34:45.123456789");
1437
1438 let t = time(5, 34, 45, 0);
1439 let got = to_string(p().precision(Some(9)), t);
1440 assert_eq!(got, "05:34:45.000000000");
1441
1442 let t = Time::MIN;
1443 let got = to_string(p().precision(Some(9)), t);
1444 assert_eq!(got, "00:00:00.000000000");
1445
1446 let t = Time::MAX;
1447 let got = to_string(p().precision(Some(9)), t);
1448 assert_eq!(got, "23:59:59.999999999");
1449 }
1450
1451 #[test]
1452 fn print_iso_week_date() {
1453 let p = || DateTimePrinter::new();
1454 let via_io = |dtp: DateTimePrinter, date| {
1455 let mut buf = String::new();
1456 dtp.print_iso_week_date(&date, &mut StdFmtWrite(&mut buf))
1457 .unwrap();
1458 buf
1459 };
1460 let to_string = |dtp: DateTimePrinter, date| {
1461 let mut buf = String::new();
1462 dtp.print_iso_week_date(&date, &mut buf).unwrap();
1463 let got_via_io = via_io(dtp, date);
1464 assert_eq!(
1465 buf, got_via_io,
1466 "expected writes to `&mut String` to match `&mut StdFmtWrite`"
1467 );
1468 buf
1469 };
1470
1471 let d = ISOWeekDate::new(2024, 52, Weekday::Monday).unwrap();
1472 let got = to_string(p(), d);
1473 assert_eq!(got, "2024-W52-1");
1474
1475 let d = ISOWeekDate::new(2004, 1, Weekday::Sunday).unwrap();
1476 let got = to_string(p(), d);
1477 assert_eq!(got, "2004-W01-7");
1478
1479 let d = ISOWeekDate::MIN;
1480 let got = to_string(p(), d);
1481 assert_eq!(got, "-009999-W01-1");
1482
1483 let d = ISOWeekDate::MAX;
1484 let got = to_string(p(), d);
1485 assert_eq!(got, "9999-W52-5");
1486 }
1487
1488 #[test]
1489 fn print_pieces() {
1490 let p = || DateTimePrinter::new();
1491 let via_io = |dtp: DateTimePrinter, pieces| {
1492 let mut buf = String::new();
1493 dtp.print_pieces(&pieces, &mut StdFmtWrite(&mut buf)).unwrap();
1494 buf
1495 };
1496 let to_string = |dtp: DateTimePrinter, pieces| {
1497 let mut buf = String::new();
1498 dtp.print_pieces(&pieces, &mut buf).unwrap();
1499 let got_via_io = via_io(dtp, pieces);
1500 assert_eq!(
1501 buf, got_via_io,
1502 "expected writes to `&mut String` to match `&mut StdFmtWrite`"
1503 );
1504 buf
1505 };
1506
1507 let pieces = Pieces::from(date(2024, 3, 10).at(5, 34, 45, 0))
1508 .with_offset(Offset::constant(-4))
1509 .with_time_zone_name("America/New_York");
1510 let got = to_string(p(), pieces);
1511 assert_eq!(got, "2024-03-10T05:34:45-04:00[America/New_York]");
1512
1513 let pieces = Pieces::from(date(2024, 3, 10).at(5, 34, 45, 0))
1514 .with_offset(Offset::UTC)
1515 .with_time_zone_name("UTC");
1516 let got = to_string(p(), pieces);
1517 assert_eq!(got, "2024-03-10T05:34:45+00:00[UTC]");
1518
1519 let pieces = Pieces::from(date(2024, 3, 10).at(5, 34, 45, 0))
1520 .with_offset(Offset::MIN)
1521 .with_time_zone_offset(Offset::MIN);
1522 let got = to_string(p(), pieces);
1523 assert_eq!(got, "2024-03-10T05:34:45-25:59[-25:59]");
1524
1525 let pieces = Pieces::from(date(2024, 3, 10).at(5, 34, 45, 0))
1526 .with_offset(Offset::MAX)
1527 .with_time_zone_offset(Offset::MAX);
1528 let got = to_string(p(), pieces);
1529 assert_eq!(got, "2024-03-10T05:34:45+25:59[+25:59]");
1530
1531 let pieces =
1532 Pieces::from(date(2024, 3, 10).at(5, 34, 45, 123_456_789))
1533 .with_offset(Offset::constant(-4))
1534 .with_time_zone_name("America/New_York");
1535 let got = to_string(p(), pieces);
1536 assert_eq!(
1537 got,
1538 "2024-03-10T05:34:45.123456789-04:00[America/New_York]"
1539 );
1540
1541 let pieces = Pieces::from(date(2024, 3, 10).at(5, 34, 45, 0))
1542 .with_offset(Offset::constant(-4))
1543 .with_time_zone_name("America/New_York");
1544 let got = to_string(p().precision(Some(9)), pieces);
1545 assert_eq!(
1546 got,
1547 "2024-03-10T05:34:45.000000000-04:00[America/New_York]"
1548 );
1549
1550 let pieces =
1551 Pieces::from(date(-9999, 3, 1).at(23, 59, 59, 999_999_999))
1552 .with_offset(Offset::constant(-4))
1553 .with_time_zone_name("America/Argentina/ComodRivadavia");
1554 let got = to_string(p().precision(Some(9)), pieces);
1555 assert_eq!(
1556 got,
1557 "-009999-03-01T23:59:59.999999999-04:00[America/Argentina/ComodRivadavia]",
1558 );
1559
1560 let pieces =
1561 Pieces::parse(
1562 "-009999-03-01T23:59:59.999999999-04:00[!America/Argentina/ComodRivadavia]",
1563 ).unwrap();
1564 let got = to_string(p().precision(Some(9)), pieces);
1565 assert_eq!(
1566 got,
1567 "-009999-03-01T23:59:59.999999999-04:00[!America/Argentina/ComodRivadavia]",
1568 );
1569
1570 let name = "Abc/Def/Ghi/Jkl/Mno/Pqr/Stu/Vwx/Yzz/Abc/Def/Ghi/Jkl/Mno/Pqr/Stu/Vwx/Yzz/Abc/Def/Ghi/Jkl/Mno/Pqr/Stu/Vwx/Yzz";
1572 let pieces =
1573 Pieces::from(date(-9999, 3, 1).at(23, 59, 59, 999_999_999))
1574 .with_offset(Offset::constant(-4))
1575 .with_time_zone_name(name);
1576 let got = to_string(p().precision(Some(9)), pieces);
1577 assert_eq!(
1578 got,
1579 "-009999-03-01T23:59:59.999999999-04:00[Abc/Def/Ghi/Jkl/Mno/Pqr/Stu/Vwx/Yzz/Abc/Def/Ghi/Jkl/Mno/Pqr/Stu/Vwx/Yzz/Abc/Def/Ghi/Jkl/Mno/Pqr/Stu/Vwx/Yzz]",
1580 );
1581 }
1582
1583 #[test]
1584 fn print_time_zone() {
1585 let p = || DateTimePrinter::new();
1586 let via_io = |dtp: DateTimePrinter, tz| {
1587 let mut buf = String::new();
1588 dtp.print_time_zone(&tz, &mut StdFmtWrite(&mut buf)).unwrap();
1589 buf
1590 };
1591 let to_string = |dtp: DateTimePrinter, tz| {
1592 let mut buf = String::new();
1593 dtp.print_time_zone(&tz, &mut buf).unwrap();
1594 let got_via_io = via_io(dtp, tz);
1595 assert_eq!(
1596 buf, got_via_io,
1597 "expected writes to `&mut String` to match `&mut StdFmtWrite`"
1598 );
1599 buf
1600 };
1601
1602 let tztest =
1603 crate::tz::testdata::TzifTestFile::get("America/New_York");
1604 let tz = TimeZone::tzif(tztest.name, tztest.data).unwrap();
1605 let got = to_string(p(), tz);
1606 assert_eq!(got, "America/New_York");
1607
1608 let tz = TimeZone::tzif(
1611 "Abc/Def/Ghi/Jkl/Mno/Pqr/Stu/Vwx/Yzz/Abc/Def/Ghi/Jkl/Mno/Pqr/Stu/Vwx/Yzz/Abc/Def/Ghi/Jkl/Mno/Pqr/Stu/Vwx/Yzz",
1612 tztest.data,
1613 ).unwrap();
1614 let got = to_string(p(), tz);
1615 assert_eq!(
1616 got,
1617 "Abc/Def/Ghi/Jkl/Mno/Pqr/Stu/Vwx/Yzz/Abc/Def/Ghi/Jkl/Mno/Pqr/Stu/Vwx/Yzz/Abc/Def/Ghi/Jkl/Mno/Pqr/Stu/Vwx/Yzz",
1618 );
1619
1620 let tz = TimeZone::UTC;
1621 let got = to_string(p(), tz);
1622 assert_eq!(got, "UTC");
1623
1624 let tz = TimeZone::unknown();
1625 let got = to_string(p(), tz);
1626 assert_eq!(got, "Etc/Unknown");
1627
1628 let tz = TimeZone::fixed(Offset::MIN);
1629 let got = to_string(p(), tz);
1630 assert_eq!(got, "-25:59:59");
1631
1632 let tz = TimeZone::fixed(Offset::MAX);
1633 let got = to_string(p(), tz);
1634 assert_eq!(got, "+25:59:59");
1635
1636 let tz = TimeZone::posix("EST5EDT,M3.2.0,M11.1.0").unwrap();
1637 let got = to_string(p(), tz);
1638 assert_eq!(got, "EST5EDT,M3.2.0,M11.1.0");
1639
1640 let tz = TimeZone::posix("EST5EDT5,M3.2.0,M11.1.0").unwrap();
1641 let got = to_string(p(), tz);
1642 assert_eq!(got, "EST5EDT5,M3.2.0,M11.1.0");
1643
1644 let tz = TimeZone::posix("EST5EDT,J1,J365/5:12:34").unwrap();
1645 let got = to_string(p(), tz);
1646 assert_eq!(got, "EST5EDT,J1,J365/5:12:34");
1647
1648 let tz =
1649 TimeZone::posix("<+09>-9<-10>-10,M3.2.0/1:23:45,J365/-1").unwrap();
1650 let got = to_string(p(), tz);
1651 assert_eq!(got, "<+09>-9<-10>,M3.2.0/1:23:45,J365/-1");
1652
1653 let tz = TimeZone::posix(
1654 "ABCDEFGHIJKLMNOPQRSTUVWXY5ABCDEFGHIJKLMNOPQRSTUVWXYT,M3.2.0,M11.1.0",
1655 ).unwrap();
1656 let got = to_string(p(), tz);
1657 assert_eq!(
1658 got,
1659 "ABCDEFGHIJKLMNOPQRSTUVWXY5ABCDEFGHIJKLMNOPQRSTUVWXYT,M3.2.0,M11.1.0",
1660 );
1661
1662 #[cfg(feature = "tz-system")]
1665 {
1666 let tz = TimeZone::tzif_system(tztest.data).unwrap();
1667 let mut buf = String::new();
1668 let err = p().print_time_zone(&tz, &mut buf).unwrap_err();
1669 assert_eq!(
1670 err.to_string(),
1671 "time zones without IANA identifiers that aren't \
1672 either fixed offsets or a POSIX time zone can't be \
1673 serialized (this typically occurs when this is a \
1674 system time zone derived from `/etc/localtime` on \
1675 Unix systems that isn't symlinked to an entry in \
1676 `/usr/share/zoneinfo`)",
1677 );
1678 }
1679 }
1680
1681 #[cfg(not(miri))]
1682 #[test]
1683 fn print_span_basic() {
1684 let p = |span: Span| -> String {
1685 let mut buf = String::new();
1686 SpanPrinter::new().print_span(&span, &mut buf).unwrap();
1687 buf
1688 };
1689
1690 insta::assert_snapshot!(p(Span::new()), @"PT0S");
1691 insta::assert_snapshot!(p(1.second()), @"PT1S");
1692 insta::assert_snapshot!(p(-1.second()), @"-PT1S");
1693 insta::assert_snapshot!(p(
1694 1.second().milliseconds(1).microseconds(1).nanoseconds(1),
1695 ), @"PT1.001001001S");
1696 insta::assert_snapshot!(p(
1697 0.second().milliseconds(999).microseconds(999).nanoseconds(999),
1698 ), @"PT0.999999999S");
1699 insta::assert_snapshot!(p(
1700 1.year().months(1).weeks(1).days(1)
1701 .hours(1).minutes(1).seconds(1)
1702 .milliseconds(1).microseconds(1).nanoseconds(1),
1703 ), @"P1Y1M1W1DT1H1M1.001001001S");
1704 insta::assert_snapshot!(p(
1705 -1.year().months(1).weeks(1).days(1)
1706 .hours(1).minutes(1).seconds(1)
1707 .milliseconds(1).microseconds(1).nanoseconds(1),
1708 ), @"-P1Y1M1W1DT1H1M1.001001001S");
1709 }
1710
1711 #[cfg(not(miri))]
1712 #[test]
1713 fn print_span_subsecond_positive() {
1714 let p = |span: Span| -> String {
1715 let mut buf = String::new();
1716 SpanPrinter::new().print_span(&span, &mut buf).unwrap();
1717 buf
1718 };
1719
1720 insta::assert_snapshot!(p(
1722 0.second().milliseconds(1000).microseconds(1000).nanoseconds(1000),
1723 ), @"PT1.001001S");
1724 insta::assert_snapshot!(p(
1725 1.second().milliseconds(1000).microseconds(1000).nanoseconds(1000),
1726 ), @"PT2.001001S");
1727 insta::assert_snapshot!(p(
1728 0.second()
1729 .milliseconds(b::SpanMilliseconds::MAX),
1730 ), @"PT631107417600S");
1731 insta::assert_snapshot!(p(
1732 0.second()
1733 .microseconds(b::SpanMicroseconds::MAX),
1734 ), @"PT631107417600S");
1735 insta::assert_snapshot!(p(
1736 0.second()
1737 .nanoseconds(b::SpanNanoseconds::MAX),
1738 ), @"PT9223372036.854775807S");
1739
1740 insta::assert_snapshot!(p(
1741 0.second()
1742 .milliseconds(b::SpanMilliseconds::MAX)
1743 .microseconds(999_999),
1744 ), @"PT631107417600.999999S");
1745 insta::assert_snapshot!(p(
1748 0.second()
1749 .milliseconds(b::SpanMilliseconds::MAX)
1750 .microseconds(1_000_000),
1751 ), @"PT631107417601S");
1752 insta::assert_snapshot!(p(
1753 0.second()
1754 .milliseconds(b::SpanMilliseconds::MAX)
1755 .microseconds(1_000_001),
1756 ), @"PT631107417601.000001S");
1757 insta::assert_snapshot!(p(
1760 0.second()
1761 .milliseconds(b::SpanMilliseconds::MAX)
1762 .nanoseconds(1_000_000_000),
1763 ), @"PT631107417601S");
1764 insta::assert_snapshot!(p(
1765 0.second()
1766 .milliseconds(b::SpanMilliseconds::MAX)
1767 .nanoseconds(1_000_000_001),
1768 ), @"PT631107417601.000000001S");
1769
1770 insta::assert_snapshot!(p(
1772 0.second()
1773 .milliseconds(b::SpanMilliseconds::MAX)
1774 .microseconds(b::SpanMicroseconds::MAX)
1775 .nanoseconds(b::SpanNanoseconds::MAX),
1776 ), @"PT1271438207236.854775807S");
1777 insta::assert_snapshot!(p(
1779 Span::new()
1780 .seconds(b::SpanSeconds::MAX)
1781 .milliseconds(b::SpanMilliseconds::MAX)
1782 .microseconds(b::SpanMicroseconds::MAX)
1783 .nanoseconds(b::SpanNanoseconds::MAX),
1784 ), @"PT1902545624836.854775807S");
1785 }
1786
1787 #[cfg(not(miri))]
1788 #[test]
1789 fn print_span_subsecond_negative() {
1790 let p = |span: Span| -> String {
1791 let mut buf = String::new();
1792 SpanPrinter::new().print_span(&span, &mut buf).unwrap();
1793 buf
1794 };
1795
1796 insta::assert_snapshot!(p(
1798 -0.second().milliseconds(1000).microseconds(1000).nanoseconds(1000),
1799 ), @"-PT1.001001S");
1800 insta::assert_snapshot!(p(
1801 -1.second().milliseconds(1000).microseconds(1000).nanoseconds(1000),
1802 ), @"-PT2.001001S");
1803 insta::assert_snapshot!(p(
1804 0.second()
1805 .milliseconds(b::SpanMilliseconds::MIN),
1806 ), @"-PT631107417600S");
1807 insta::assert_snapshot!(p(
1808 0.second()
1809 .microseconds(b::SpanMicroseconds::MIN),
1810 ), @"-PT631107417600S");
1811 insta::assert_snapshot!(p(
1812 0.second()
1813 .nanoseconds(b::SpanNanoseconds::MIN),
1814 ), @"-PT9223372036.854775807S");
1815
1816 insta::assert_snapshot!(p(
1817 0.second()
1818 .milliseconds(b::SpanMilliseconds::MIN)
1819 .microseconds(999_999),
1820 ), @"-PT631107417600.999999S");
1821 insta::assert_snapshot!(p(
1824 0.second()
1825 .milliseconds(b::SpanMilliseconds::MIN)
1826 .microseconds(1_000_000),
1827 ), @"-PT631107417601S");
1828 insta::assert_snapshot!(p(
1829 0.second()
1830 .milliseconds(b::SpanMilliseconds::MIN)
1831 .microseconds(1_000_001),
1832 ), @"-PT631107417601.000001S");
1833 insta::assert_snapshot!(p(
1836 0.second()
1837 .milliseconds(b::SpanMilliseconds::MIN)
1838 .nanoseconds(1_000_000_000),
1839 ), @"-PT631107417601S");
1840 insta::assert_snapshot!(p(
1841 0.second()
1842 .milliseconds(b::SpanMilliseconds::MIN)
1843 .nanoseconds(1_000_000_001),
1844 ), @"-PT631107417601.000000001S");
1845
1846 insta::assert_snapshot!(p(
1848 0.second()
1849 .milliseconds(b::SpanMilliseconds::MIN)
1850 .microseconds(b::SpanMicroseconds::MIN)
1851 .nanoseconds(b::SpanNanoseconds::MIN),
1852 ), @"-PT1271438207236.854775807S");
1853 insta::assert_snapshot!(p(
1855 Span::new()
1856 .seconds(b::SpanSeconds::MIN)
1857 .milliseconds(b::SpanMilliseconds::MIN)
1858 .microseconds(b::SpanMicroseconds::MIN)
1859 .nanoseconds(b::SpanNanoseconds::MIN),
1860 ), @"-PT1902545624836.854775807S");
1861 }
1862
1863 #[cfg(not(miri))]
1864 #[test]
1865 fn print_signed_duration() {
1866 let p = |secs, nanos| -> String {
1867 let dur = SignedDuration::new(secs, nanos);
1868 let mut buf = String::new();
1869 SpanPrinter::new().print_signed_duration(&dur, &mut buf).unwrap();
1870 buf
1871 };
1872
1873 insta::assert_snapshot!(p(0, 0), @"PT0S");
1874 insta::assert_snapshot!(p(0, 1), @"PT0.000000001S");
1875 insta::assert_snapshot!(p(1, 0), @"PT1S");
1876 insta::assert_snapshot!(p(59, 0), @"PT59S");
1877 insta::assert_snapshot!(p(60, 0), @"PT1M");
1878 insta::assert_snapshot!(p(60, 1), @"PT1M0.000000001S");
1879 insta::assert_snapshot!(p(61, 1), @"PT1M1.000000001S");
1880 insta::assert_snapshot!(p(3_600, 0), @"PT1H");
1881 insta::assert_snapshot!(p(3_600, 1), @"PT1H0.000000001S");
1882 insta::assert_snapshot!(p(3_660, 0), @"PT1H1M");
1883 insta::assert_snapshot!(p(3_660, 1), @"PT1H1M0.000000001S");
1884 insta::assert_snapshot!(p(3_661, 0), @"PT1H1M1S");
1885 insta::assert_snapshot!(p(3_661, 1), @"PT1H1M1.000000001S");
1886
1887 insta::assert_snapshot!(p(0, -1), @"-PT0.000000001S");
1888 insta::assert_snapshot!(p(-1, 0), @"-PT1S");
1889 insta::assert_snapshot!(p(-59, 0), @"-PT59S");
1890 insta::assert_snapshot!(p(-60, 0), @"-PT1M");
1891 insta::assert_snapshot!(p(-60, -1), @"-PT1M0.000000001S");
1892 insta::assert_snapshot!(p(-61, -1), @"-PT1M1.000000001S");
1893 insta::assert_snapshot!(p(-3_600, 0), @"-PT1H");
1894 insta::assert_snapshot!(p(-3_600, -1), @"-PT1H0.000000001S");
1895 insta::assert_snapshot!(p(-3_660, 0), @"-PT1H1M");
1896 insta::assert_snapshot!(p(-3_660, -1), @"-PT1H1M0.000000001S");
1897 insta::assert_snapshot!(p(-3_661, 0), @"-PT1H1M1S");
1898 insta::assert_snapshot!(p(-3_661, -1), @"-PT1H1M1.000000001S");
1899
1900 insta::assert_snapshot!(
1901 p(i64::MIN, -999_999_999),
1902 @"-PT2562047788015215H30M8.999999999S",
1903 );
1904 insta::assert_snapshot!(
1905 p(i64::MAX, 999_999_999),
1906 @"PT2562047788015215H30M7.999999999S",
1907 );
1908
1909 insta::assert_snapshot!(
1910 p(-(2_562_047_788_015_214 * 3_600 + 3_599), -999_999_999),
1911 @"-PT2562047788015214H59M59.999999999S",
1912 );
1913 insta::assert_snapshot!(
1914 p(2_562_047_788_015_214 * 3_600 + 3_599, 999_999_999),
1915 @"PT2562047788015214H59M59.999999999S",
1916 );
1917 }
1918
1919 #[cfg(not(miri))]
1920 #[test]
1921 fn print_unsigned_duration() {
1922 let p = |secs, nanos| -> String {
1923 let dur = Duration::new(secs, nanos);
1924 let mut buf = String::new();
1925 SpanPrinter::new()
1926 .print_unsigned_duration(&dur, &mut buf)
1927 .unwrap();
1928 buf
1929 };
1930
1931 insta::assert_snapshot!(p(0, 0), @"PT0S");
1932 insta::assert_snapshot!(p(0, 1), @"PT0.000000001S");
1933 insta::assert_snapshot!(p(1, 0), @"PT1S");
1934 insta::assert_snapshot!(p(59, 0), @"PT59S");
1935 insta::assert_snapshot!(p(60, 0), @"PT1M");
1936 insta::assert_snapshot!(p(60, 1), @"PT1M0.000000001S");
1937 insta::assert_snapshot!(p(61, 1), @"PT1M1.000000001S");
1938 insta::assert_snapshot!(p(3_600, 0), @"PT1H");
1939 insta::assert_snapshot!(p(3_600, 1), @"PT1H0.000000001S");
1940 insta::assert_snapshot!(p(3_660, 0), @"PT1H1M");
1941 insta::assert_snapshot!(p(3_660, 1), @"PT1H1M0.000000001S");
1942 insta::assert_snapshot!(p(3_661, 0), @"PT1H1M1S");
1943 insta::assert_snapshot!(p(3_661, 1), @"PT1H1M1.000000001S");
1944
1945 insta::assert_snapshot!(
1946 p(u64::MAX, 999_999_999),
1947 @"PT5124095576030431H15.999999999S",
1948 );
1949 insta::assert_snapshot!(
1950 p(5_124_095_576_030_430 * 3_600 + 3_599, 999_999_999),
1951 @"PT5124095576030430H59M59.999999999S",
1952 );
1953 }
1954}