]> git.proxmox.com Git - rustc.git/blob - src/test/run-pass/impl-trait/example-calendar.rs
New upstream version 1.23.0+dfsg1
[rustc.git] / src / test / run-pass / impl-trait / example-calendar.rs
1 // Copyright 2016-2017 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 #![feature(conservative_impl_trait,
12 universal_impl_trait,
13 fn_traits,
14 step_trait,
15 unboxed_closures
16 )]
17
18 //! Derived from: <https://raw.githubusercontent.com/quickfur/dcal/master/dcal.d>.
19 //!
20 //! Originally converted to Rust by [Daniel Keep](https://github.com/DanielKeep).
21
22 use std::fmt::Write;
23 use std::mem;
24
25 /// Date representation.
26 #[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
27 struct NaiveDate(i32, u32, u32);
28
29 impl NaiveDate {
30 pub fn from_ymd(y: i32, m: u32, d: u32) -> NaiveDate {
31 assert!(1 <= m && m <= 12, "m = {:?}", m);
32 assert!(1 <= d && d <= NaiveDate(y, m, 1).days_in_month(), "d = {:?}", d);
33 NaiveDate(y, m, d)
34 }
35
36 pub fn year(&self) -> i32 {
37 self.0
38 }
39
40 pub fn month(&self) -> u32 {
41 self.1
42 }
43
44 pub fn day(&self) -> u32 {
45 self.2
46 }
47
48 pub fn succ(&self) -> NaiveDate {
49 let (mut y, mut m, mut d, n) = (
50 self.year(), self.month(), self.day()+1, self.days_in_month());
51 if d > n {
52 d = 1;
53 m += 1;
54 }
55 if m > 12 {
56 m = 1;
57 y += 1;
58 }
59 NaiveDate::from_ymd(y, m, d)
60 }
61
62 pub fn weekday(&self) -> Weekday {
63 use Weekday::*;
64
65 // 0 = Sunday
66 let year = self.year();
67 let dow_jan_1 = (year*365 + ((year-1) / 4) - ((year-1) / 100) + ((year-1) / 400)) % 7;
68 let dow = (dow_jan_1 + (self.day_of_year() as i32 - 1)) % 7;
69 [Sun, Mon, Tue, Wed, Thu, Fri, Sat][dow as usize]
70 }
71
72 pub fn isoweekdate(&self) -> (i32, u32, Weekday) {
73 let first_dow_mon_0 = self.year_first_day_of_week().num_days_from_monday();
74
75 // Work out this date's DOtY and week number, not including year adjustment.
76 let doy_0 = self.day_of_year() - 1;
77 let mut week_mon_0: i32 = ((first_dow_mon_0 + doy_0) / 7) as i32;
78
79 if self.first_week_in_prev_year() {
80 week_mon_0 -= 1;
81 }
82
83 let weeks_in_year = self.last_week_number();
84
85 // Work out the final result.
86 // If the week is -1 or >= weeks_in_year, we will need to adjust the year.
87 let year = self.year();
88 let wd = self.weekday();
89
90 if week_mon_0 < 0 {
91 (year - 1, NaiveDate::from_ymd(year - 1, 1, 1).last_week_number(), wd)
92 } else if week_mon_0 >= weeks_in_year as i32 {
93 (year + 1, (week_mon_0 + 1 - weeks_in_year as i32) as u32, wd)
94 } else {
95 (year, (week_mon_0 + 1) as u32, wd)
96 }
97 }
98
99 fn first_week_in_prev_year(&self) -> bool {
100 let first_dow_mon_0 = self.year_first_day_of_week().num_days_from_monday();
101
102 // Any day in the year *before* the first Monday of that year
103 // is considered to be in the last week of the previous year,
104 // assuming the first week has *less* than four days in it.
105 // Adjust the week appropriately.
106 ((7 - first_dow_mon_0) % 7) < 4
107 }
108
109 fn year_first_day_of_week(&self) -> Weekday {
110 NaiveDate::from_ymd(self.year(), 1, 1).weekday()
111 }
112
113 fn weeks_in_year(&self) -> u32 {
114 let days_in_last_week = self.year_first_day_of_week().num_days_from_monday() + 1;
115 if days_in_last_week >= 4 { 53 } else { 52 }
116 }
117
118 fn last_week_number(&self) -> u32 {
119 let wiy = self.weeks_in_year();
120 if self.first_week_in_prev_year() { wiy - 1 } else { wiy }
121 }
122
123 fn day_of_year(&self) -> u32 {
124 (1..self.1).map(|m| NaiveDate::from_ymd(self.year(), m, 1).days_in_month())
125 .fold(0, |a,b| a+b) + self.day()
126 }
127
128 fn is_leap_year(&self) -> bool {
129 let year = self.year();
130 if year % 4 != 0 {
131 return false
132 } else if year % 100 != 0 {
133 return true
134 } else if year % 400 != 0 {
135 return false
136 } else {
137 return true
138 }
139 }
140
141 fn days_in_month(&self) -> u32 {
142 match self.month() {
143 /* Jan */ 1 => 31,
144 /* Feb */ 2 => if self.is_leap_year() { 29 } else { 28 },
145 /* Mar */ 3 => 31,
146 /* Apr */ 4 => 30,
147 /* May */ 5 => 31,
148 /* Jun */ 6 => 30,
149 /* Jul */ 7 => 31,
150 /* Aug */ 8 => 31,
151 /* Sep */ 9 => 30,
152 /* Oct */ 10 => 31,
153 /* Nov */ 11 => 30,
154 /* Dec */ 12 => 31,
155 _ => unreachable!()
156 }
157 }
158 }
159
160 impl<'a, 'b> std::ops::Add<&'b NaiveDate> for &'a NaiveDate {
161 type Output = NaiveDate;
162
163 fn add(self, other: &'b NaiveDate) -> NaiveDate {
164 assert_eq!(*other, NaiveDate(0, 0, 1));
165 self.succ()
166 }
167 }
168
169 impl std::iter::Step for NaiveDate {
170 fn steps_between(_: &Self, _: &Self) -> Option<usize> {
171 unimplemented!()
172 }
173
174 fn replace_one(&mut self) -> Self {
175 mem::replace(self, NaiveDate(0, 0, 1))
176 }
177
178 fn replace_zero(&mut self) -> Self {
179 mem::replace(self, NaiveDate(0, 0, 0))
180 }
181
182 fn add_one(&self) -> Self {
183 self.succ()
184 }
185
186 fn sub_one(&self) -> Self {
187 unimplemented!()
188 }
189
190 fn add_usize(&self, _: usize) -> Option<Self> {
191 unimplemented!()
192 }
193 }
194
195 #[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
196 pub enum Weekday {
197 Mon,
198 Tue,
199 Wed,
200 Thu,
201 Fri,
202 Sat,
203 Sun,
204 }
205
206 impl Weekday {
207 pub fn num_days_from_monday(&self) -> u32 {
208 use Weekday::*;
209 match *self {
210 Mon => 0,
211 Tue => 1,
212 Wed => 2,
213 Thu => 3,
214 Fri => 4,
215 Sat => 5,
216 Sun => 6,
217 }
218 }
219
220 pub fn num_days_from_sunday(&self) -> u32 {
221 use Weekday::*;
222 match *self {
223 Sun => 0,
224 Mon => 1,
225 Tue => 2,
226 Wed => 3,
227 Thu => 4,
228 Fri => 5,
229 Sat => 6,
230 }
231 }
232 }
233
234 /// Wrapper for zero-sized closures.
235 // HACK(eddyb) Only needed because closures can't implement Copy.
236 struct Fn0<F>(std::marker::PhantomData<F>);
237
238 impl<F> Copy for Fn0<F> {}
239 impl<F> Clone for Fn0<F> {
240 fn clone(&self) -> Self { *self }
241 }
242
243 impl<F: FnOnce<A>, A> FnOnce<A> for Fn0<F> {
244 type Output = F::Output;
245
246 extern "rust-call" fn call_once(self, args: A) -> Self::Output {
247 let f = unsafe { std::mem::uninitialized::<F>() };
248 f.call_once(args)
249 }
250 }
251
252 impl<F: FnMut<A>, A> FnMut<A> for Fn0<F> {
253 extern "rust-call" fn call_mut(&mut self, args: A) -> Self::Output {
254 let mut f = unsafe { std::mem::uninitialized::<F>() };
255 f.call_mut(args)
256 }
257 }
258
259 trait AsFn0<A>: Sized {
260 fn copyable(self) -> Fn0<Self>;
261 }
262
263 impl<F: FnMut<A>, A> AsFn0<A> for F {
264 fn copyable(self) -> Fn0<Self> {
265 assert_eq!(std::mem::size_of::<F>(), 0);
266 Fn0(std::marker::PhantomData)
267 }
268 }
269
270 /// GroupBy implementation.
271 struct GroupBy<It: Iterator, F> {
272 it: std::iter::Peekable<It>,
273 f: F,
274 }
275
276 impl<It, F> Clone for GroupBy<It, F>
277 where It: Iterator + Clone, It::Item: Clone, F: Clone {
278 fn clone(&self) -> GroupBy<It, F> {
279 GroupBy {
280 it: self.it.clone(),
281 f: self.f.clone()
282 }
283 }
284 }
285
286 impl<'a, G, It: 'a, F: 'a> Iterator for GroupBy<It, F>
287 where It: Iterator + Clone,
288 It::Item: Clone,
289 F: Clone + FnMut(&It::Item) -> G,
290 G: Eq + Clone
291 {
292 type Item = (G, InGroup<std::iter::Peekable<It>, F, G>);
293
294 fn next(&mut self) -> Option<Self::Item> {
295 self.it.peek().map(&mut self.f).map(|key| {
296 let start = self.it.clone();
297 while let Some(k) = self.it.peek().map(&mut self.f) {
298 if key != k {
299 break;
300 }
301 self.it.next();
302 }
303
304 (key.clone(), InGroup {
305 it: start,
306 f: self.f.clone(),
307 g: key
308 })
309 })
310 }
311 }
312
313 #[derive(Copy, Clone)]
314 struct InGroup<It, F, G> {
315 it: It,
316 f: F,
317 g: G
318 }
319
320 impl<It: Iterator, F: FnMut(&It::Item) -> G, G: Eq> Iterator for InGroup<It, F, G> {
321 type Item = It::Item;
322
323 fn next(&mut self) -> Option<It::Item> {
324 self.it.next().and_then(|x| {
325 if (self.f)(&x) == self.g { Some(x) } else { None }
326 })
327 }
328 }
329
330 trait IteratorExt: Iterator + Sized {
331 fn group_by<G, F>(self, f: F) -> GroupBy<Self, Fn0<F>>
332 where F: FnMut(&Self::Item) -> G,
333 G: Eq
334 {
335 GroupBy {
336 it: self.peekable(),
337 f: f.copyable(),
338 }
339 }
340
341 fn join(mut self, sep: &str) -> String
342 where Self::Item: std::fmt::Display {
343 let mut s = String::new();
344 if let Some(e) = self.next() {
345 write!(s, "{}", e);
346 for e in self {
347 s.push_str(sep);
348 write!(s, "{}", e);
349 }
350 }
351 s
352 }
353
354 // HACK(eddyb) Only needed because `impl Trait` can't be
355 // used with trait methods: `.foo()` becomes `.__(foo)`.
356 fn __<F, R>(self, f: F) -> R
357 where F: FnOnce(Self) -> R {
358 f(self)
359 }
360 }
361
362 impl<It> IteratorExt for It where It: Iterator {}
363
364 ///
365 /// Generates an iterator that yields exactly n spaces.
366 ///
367 fn spaces(n: usize) -> std::iter::Take<std::iter::Repeat<char>> {
368 std::iter::repeat(' ').take(n)
369 }
370
371 fn test_spaces() {
372 assert_eq!(spaces(0).collect::<String>(), "");
373 assert_eq!(spaces(10).collect::<String>(), " ")
374 }
375
376 ///
377 /// Returns an iterator of dates in a given year.
378 ///
379 fn dates_in_year(year: i32) -> impl Iterator<Item=NaiveDate>+Clone {
380 InGroup {
381 it: NaiveDate::from_ymd(year, 1, 1)..,
382 f: (|d: &NaiveDate| d.year()).copyable(),
383 g: year
384 }
385 }
386
387 fn test_dates_in_year() {
388 {
389 let mut dates = dates_in_year(2013);
390 assert_eq!(dates.next(), Some(NaiveDate::from_ymd(2013, 1, 1)));
391
392 // Check increment
393 assert_eq!(dates.next(), Some(NaiveDate::from_ymd(2013, 1, 2)));
394
395 // Check monthly rollover
396 for _ in 3..31 {
397 assert!(dates.next() != None);
398 }
399
400 assert_eq!(dates.next(), Some(NaiveDate::from_ymd(2013, 1, 31)));
401 assert_eq!(dates.next(), Some(NaiveDate::from_ymd(2013, 2, 1)));
402 }
403
404 {
405 // Check length of year
406 let mut dates = dates_in_year(2013);
407 for _ in 0..365 {
408 assert!(dates.next() != None);
409 }
410 assert_eq!(dates.next(), None);
411 }
412
413 {
414 // Check length of leap year
415 let mut dates = dates_in_year(1984);
416 for _ in 0..366 {
417 assert!(dates.next() != None);
418 }
419 assert_eq!(dates.next(), None);
420 }
421 }
422
423 ///
424 /// Convenience trait for verifying that a given type iterates over
425 /// `NaiveDate`s.
426 ///
427 trait DateIterator: Iterator<Item=NaiveDate> + Clone {}
428 impl<It> DateIterator for It where It: Iterator<Item=NaiveDate> + Clone {}
429
430 fn test_group_by() {
431 let input = [
432 [1, 1],
433 [1, 1],
434 [1, 2],
435 [2, 2],
436 [2, 3],
437 [2, 3],
438 [3, 3]
439 ];
440
441 let by_x = input.iter().cloned().group_by(|a| a[0]);
442 let expected_1: &[&[[i32; 2]]] = &[
443 &[[1, 1], [1, 1], [1, 2]],
444 &[[2, 2], [2, 3], [2, 3]],
445 &[[3, 3]]
446 ];
447 for ((_, a), b) in by_x.zip(expected_1.iter().cloned()) {
448 assert_eq!(&a.collect::<Vec<_>>()[..], b);
449 }
450
451 let by_y = input.iter().cloned().group_by(|a| a[1]);
452 let expected_2: &[&[[i32; 2]]] = &[
453 &[[1, 1], [1, 1]],
454 &[[1, 2], [2, 2]],
455 &[[2, 3], [2, 3], [3, 3]]
456 ];
457 for ((_, a), b) in by_y.zip(expected_2.iter().cloned()) {
458 assert_eq!(&a.collect::<Vec<_>>()[..], b);
459 }
460 }
461
462 ///
463 /// Groups an iterator of dates by month.
464 ///
465 fn by_month(it: impl Iterator<Item=NaiveDate> + Clone)
466 -> impl Iterator<Item=(u32, impl Iterator<Item=NaiveDate> + Clone)> + Clone
467 {
468 it.group_by(|d| d.month())
469 }
470
471 fn test_by_month() {
472 let mut months = dates_in_year(2013).__(by_month);
473 for (month, (_, mut date)) in (1..13).zip(&mut months) {
474 assert_eq!(date.nth(0).unwrap(), NaiveDate::from_ymd(2013, month, 1));
475 }
476 assert!(months.next().is_none());
477 }
478
479 ///
480 /// Groups an iterator of dates by week.
481 ///
482 fn by_week(it: impl DateIterator)
483 -> impl Iterator<Item=(u32, impl DateIterator)> + Clone
484 {
485 // We go forward one day because `isoweekdate` considers the week to start on a Monday.
486 it.group_by(|d| d.succ().isoweekdate().1)
487 }
488
489 fn test_isoweekdate() {
490 fn weeks_uniq(year: i32) -> Vec<((i32, u32), u32)> {
491 let mut weeks = dates_in_year(year).map(|d| d.isoweekdate())
492 .map(|(y,w,_)| (y,w));
493 let mut result = vec![];
494 let mut accum = (weeks.next().unwrap(), 1);
495 for yw in weeks {
496 if accum.0 == yw {
497 accum.1 += 1;
498 } else {
499 result.push(accum);
500 accum = (yw, 1);
501 }
502 }
503 result.push(accum);
504 result
505 }
506
507 let wu_1984 = weeks_uniq(1984);
508 assert_eq!(&wu_1984[..2], &[((1983, 52), 1), ((1984, 1), 7)]);
509 assert_eq!(&wu_1984[wu_1984.len()-2..], &[((1984, 52), 7), ((1985, 1), 1)]);
510
511 let wu_2013 = weeks_uniq(2013);
512 assert_eq!(&wu_2013[..2], &[((2013, 1), 6), ((2013, 2), 7)]);
513 assert_eq!(&wu_2013[wu_2013.len()-2..], &[((2013, 52), 7), ((2014, 1), 2)]);
514
515 let wu_2015 = weeks_uniq(2015);
516 assert_eq!(&wu_2015[..2], &[((2015, 1), 4), ((2015, 2), 7)]);
517 assert_eq!(&wu_2015[wu_2015.len()-2..], &[((2015, 52), 7), ((2015, 53), 4)]);
518 }
519
520 fn test_by_week() {
521 let mut weeks = dates_in_year(2013).__(by_week);
522 assert_eq!(
523 &*weeks.next().unwrap().1.collect::<Vec<_>>(),
524 &[
525 NaiveDate::from_ymd(2013, 1, 1),
526 NaiveDate::from_ymd(2013, 1, 2),
527 NaiveDate::from_ymd(2013, 1, 3),
528 NaiveDate::from_ymd(2013, 1, 4),
529 NaiveDate::from_ymd(2013, 1, 5),
530 ]
531 );
532 assert_eq!(
533 &*weeks.next().unwrap().1.collect::<Vec<_>>(),
534 &[
535 NaiveDate::from_ymd(2013, 1, 6),
536 NaiveDate::from_ymd(2013, 1, 7),
537 NaiveDate::from_ymd(2013, 1, 8),
538 NaiveDate::from_ymd(2013, 1, 9),
539 NaiveDate::from_ymd(2013, 1, 10),
540 NaiveDate::from_ymd(2013, 1, 11),
541 NaiveDate::from_ymd(2013, 1, 12),
542 ]
543 );
544 assert_eq!(weeks.next().unwrap().1.nth(0).unwrap(), NaiveDate::from_ymd(2013, 1, 13));
545 }
546
547 /// The number of columns per day in the formatted output.
548 const COLS_PER_DAY: u32 = 3;
549
550 /// The number of columns per week in the formatted output.
551 const COLS_PER_WEEK: u32 = 7 * COLS_PER_DAY;
552
553 ///
554 /// Formats an iterator of weeks into an iterator of strings.
555 ///
556 fn format_weeks(it: impl Iterator<Item = impl DateIterator>) -> impl Iterator<Item=String> {
557 it.map(|week| {
558 let mut buf = String::with_capacity((COLS_PER_DAY * COLS_PER_WEEK + 2) as usize);
559
560 // Format each day into its own cell and append to target string.
561 let mut last_day = 0;
562 let mut first = true;
563 for d in week {
564 last_day = d.weekday().num_days_from_sunday();
565
566 // Insert enough filler to align the first day with its respective day-of-week.
567 if first {
568 buf.extend(spaces((COLS_PER_DAY * last_day) as usize));
569 first = false;
570 }
571
572 write!(buf, " {:>2}", d.day());
573 }
574
575 // Insert more filler at the end to fill up the remainder of the week,
576 // if its a short week (e.g. at the end of the month).
577 buf.extend(spaces((COLS_PER_DAY * (6 - last_day)) as usize));
578 buf
579 })
580 }
581
582 fn test_format_weeks() {
583 let jan_2013 = dates_in_year(2013)
584 .__(by_month).next() // pick January 2013 for testing purposes
585 // NOTE: This `map` is because `next` returns an `Option<_>`.
586 .map(|(_, month)|
587 month.__(by_week)
588 .map(|(_, weeks)| weeks)
589 .__(format_weeks)
590 .join("\n"));
591
592 assert_eq!(
593 jan_2013.as_ref().map(|s| &**s),
594 Some(" 1 2 3 4 5\n\
595 \x20 6 7 8 9 10 11 12\n\
596 \x2013 14 15 16 17 18 19\n\
597 \x2020 21 22 23 24 25 26\n\
598 \x2027 28 29 30 31 ")
599 );
600 }
601
602 ///
603 /// Formats the name of a month, centered on COLS_PER_WEEK.
604 ///
605 fn month_title(month: u32) -> String {
606 const MONTH_NAMES: &'static [&'static str] = &[
607 "January", "February", "March", "April", "May", "June",
608 "July", "August", "September", "October", "November", "December"
609 ];
610 assert_eq!(MONTH_NAMES.len(), 12);
611
612 // Determine how many spaces before and after the month name
613 // we need to center it over the formatted weeks in the month.
614 let name = MONTH_NAMES[(month - 1) as usize];
615 assert!(name.len() < COLS_PER_WEEK as usize);
616 let before = (COLS_PER_WEEK as usize - name.len()) / 2;
617 let after = COLS_PER_WEEK as usize - name.len() - before;
618
619 // NOTE: Being slightly more verbose to avoid extra allocations.
620 let mut result = String::with_capacity(COLS_PER_WEEK as usize);
621 result.extend(spaces(before));
622 result.push_str(name);
623 result.extend(spaces(after));
624 result
625 }
626
627 fn test_month_title() {
628 assert_eq!(month_title(1).len(), COLS_PER_WEEK as usize);
629 }
630
631 ///
632 /// Formats a month.
633 ///
634 fn format_month(it: impl DateIterator) -> impl Iterator<Item=String> {
635 let mut month_days = it.peekable();
636 let title = month_title(month_days.peek().unwrap().month());
637
638 Some(title).into_iter()
639 .chain(month_days.__(by_week)
640 .map(|(_, week)| week)
641 .__(format_weeks))
642 }
643
644 fn test_format_month() {
645 let month_fmt = dates_in_year(2013)
646 .__(by_month).next() // Pick January as a test case
647 .map(|(_, days)| days.into_iter()
648 .__(format_month)
649 .join("\n"));
650
651 assert_eq!(
652 month_fmt.as_ref().map(|s| &**s),
653 Some(" January \n\
654 \x20 1 2 3 4 5\n\
655 \x20 6 7 8 9 10 11 12\n\
656 \x2013 14 15 16 17 18 19\n\
657 \x2020 21 22 23 24 25 26\n\
658 \x2027 28 29 30 31 ")
659 );
660 }
661
662
663 ///
664 /// Formats an iterator of months.
665 ///
666 fn format_months(it: impl Iterator<Item = impl DateIterator>)
667 -> impl Iterator<Item=impl Iterator<Item=String>>
668 {
669 it.map(format_month)
670 }
671
672 ///
673 /// Takes an iterator of iterators of strings; the sub-iterators are consumed
674 /// in lock-step, with their elements joined together.
675 ///
676 trait PasteBlocks: Iterator + Sized
677 where Self::Item: Iterator<Item=String> {
678 fn paste_blocks(self, sep_width: usize) -> PasteBlocksIter<Self::Item> {
679 PasteBlocksIter {
680 iters: self.collect(),
681 cache: vec![],
682 col_widths: None,
683 sep_width: sep_width,
684 }
685 }
686 }
687
688 impl<It> PasteBlocks for It where It: Iterator, It::Item: Iterator<Item=String> {}
689
690 struct PasteBlocksIter<StrIt>
691 where StrIt: Iterator<Item=String> {
692 iters: Vec<StrIt>,
693 cache: Vec<Option<String>>,
694 col_widths: Option<Vec<usize>>,
695 sep_width: usize,
696 }
697
698 impl<StrIt> Iterator for PasteBlocksIter<StrIt>
699 where StrIt: Iterator<Item=String> {
700 type Item = String;
701
702 fn next(&mut self) -> Option<String> {
703 self.cache.clear();
704
705 // `cache` is now the next line from each iterator.
706 self.cache.extend(self.iters.iter_mut().map(|it| it.next()));
707
708 // If every line in `cache` is `None`, we have nothing further to do.
709 if self.cache.iter().all(|e| e.is_none()) { return None }
710
711 // Get the column widths if we haven't already.
712 let col_widths = match self.col_widths {
713 Some(ref v) => &**v,
714 None => {
715 self.col_widths = Some(self.cache.iter()
716 .map(|ms| ms.as_ref().map(|s| s.len()).unwrap_or(0))
717 .collect());
718 &**self.col_widths.as_ref().unwrap()
719 }
720 };
721
722 // Fill in any `None`s with spaces.
723 let mut parts = col_widths.iter().cloned().zip(self.cache.iter_mut())
724 .map(|(w,ms)| ms.take().unwrap_or_else(|| spaces(w).collect()));
725
726 // Join them all together.
727 let first = parts.next().unwrap_or(String::new());
728 let sep_width = self.sep_width;
729 Some(parts.fold(first, |mut accum, next| {
730 accum.extend(spaces(sep_width));
731 accum.push_str(&next);
732 accum
733 }))
734 }
735 }
736
737 fn test_paste_blocks() {
738 let row = dates_in_year(2013)
739 .__(by_month).map(|(_, days)| days)
740 .take(3)
741 .__(format_months)
742 .paste_blocks(1)
743 .join("\n");
744 assert_eq!(
745 &*row,
746 " January February March \n\
747 \x20 1 2 3 4 5 1 2 1 2\n\
748 \x20 6 7 8 9 10 11 12 3 4 5 6 7 8 9 3 4 5 6 7 8 9\n\
749 \x2013 14 15 16 17 18 19 10 11 12 13 14 15 16 10 11 12 13 14 15 16\n\
750 \x2020 21 22 23 24 25 26 17 18 19 20 21 22 23 17 18 19 20 21 22 23\n\
751 \x2027 28 29 30 31 24 25 26 27 28 24 25 26 27 28 29 30\n\
752 \x20 31 "
753 );
754 }
755
756 ///
757 /// Produces an iterator that yields `n` elements at a time.
758 ///
759 trait Chunks: Iterator + Sized {
760 fn chunks(self, n: usize) -> ChunksIter<Self> {
761 assert!(n > 0);
762 ChunksIter {
763 it: self,
764 n: n,
765 }
766 }
767 }
768
769 impl<It> Chunks for It where It: Iterator {}
770
771 struct ChunksIter<It>
772 where It: Iterator {
773 it: It,
774 n: usize,
775 }
776
777 // NOTE: `chunks` in Rust is more-or-less impossible without overhead of some kind.
778 // Aliasing rules mean you need to add dynamic borrow checking, and the design of
779 // `Iterator` means that you need to have the iterator's state kept in an allocation
780 // that is jointly owned by the iterator itself and the sub-iterator.
781 // As such, I've chosen to cop-out and just heap-allocate each chunk.
782
783 impl<It> Iterator for ChunksIter<It>
784 where It: Iterator {
785 type Item = Vec<It::Item>;
786
787 fn next(&mut self) -> Option<Vec<It::Item>> {
788 let first = match self.it.next() {
789 Some(e) => e,
790 None => return None
791 };
792
793 let mut result = Vec::with_capacity(self.n);
794 result.push(first);
795
796 Some((&mut self.it).take(self.n-1)
797 .fold(result, |mut acc, next| { acc.push(next); acc }))
798 }
799 }
800
801 fn test_chunks() {
802 let r = &[1, 2, 3, 4, 5, 6, 7];
803 let c = r.iter().cloned().chunks(3).collect::<Vec<_>>();
804 assert_eq!(&*c, &[vec![1, 2, 3], vec![4, 5, 6], vec![7]]);
805 }
806
807 ///
808 /// Formats a year.
809 ///
810 fn format_year(year: i32, months_per_row: usize) -> String {
811 const COL_SPACING: usize = 1;
812
813 // Start by generating all dates for the given year.
814 dates_in_year(year)
815
816 // Group them by month and throw away month number.
817 .__(by_month).map(|(_, days)| days)
818
819 // Group the months into horizontal rows.
820 .chunks(months_per_row)
821
822 // Format each row
823 .map(|r| r.into_iter()
824 // By formatting each month
825 .__(format_months)
826
827 // Horizontally pasting each respective month's lines together.
828 .paste_blocks(COL_SPACING)
829 .join("\n")
830 )
831
832 // Insert a blank line between each row
833 .join("\n\n")
834 }
835
836 fn test_format_year() {
837 const MONTHS_PER_ROW: usize = 3;
838
839 macro_rules! assert_eq_cal {
840 ($lhs:expr, $rhs:expr) => {
841 if $lhs != $rhs {
842 println!("got:\n```\n{}\n```\n", $lhs.replace(" ", "."));
843 println!("expected:\n```\n{}\n```", $rhs.replace(" ", "."));
844 panic!("calendars didn't match!");
845 }
846 }
847 }
848
849 assert_eq_cal!(&format_year(1984, MONTHS_PER_ROW), "\
850 \x20 January February March \n\
851 \x20 1 2 3 4 5 6 7 1 2 3 4 1 2 3\n\
852 \x20 8 9 10 11 12 13 14 5 6 7 8 9 10 11 4 5 6 7 8 9 10\n\
853 \x2015 16 17 18 19 20 21 12 13 14 15 16 17 18 11 12 13 14 15 16 17\n\
854 \x2022 23 24 25 26 27 28 19 20 21 22 23 24 25 18 19 20 21 22 23 24\n\
855 \x2029 30 31 26 27 28 29 25 26 27 28 29 30 31\n\
856 \n\
857 \x20 April May June \n\
858 \x20 1 2 3 4 5 6 7 1 2 3 4 5 1 2\n\
859 \x20 8 9 10 11 12 13 14 6 7 8 9 10 11 12 3 4 5 6 7 8 9\n\
860 \x2015 16 17 18 19 20 21 13 14 15 16 17 18 19 10 11 12 13 14 15 16\n\
861 \x2022 23 24 25 26 27 28 20 21 22 23 24 25 26 17 18 19 20 21 22 23\n\
862 \x2029 30 27 28 29 30 31 24 25 26 27 28 29 30\n\
863 \n\
864 \x20 July August September \n\
865 \x20 1 2 3 4 5 6 7 1 2 3 4 1\n\
866 \x20 8 9 10 11 12 13 14 5 6 7 8 9 10 11 2 3 4 5 6 7 8\n\
867 \x2015 16 17 18 19 20 21 12 13 14 15 16 17 18 9 10 11 12 13 14 15\n\
868 \x2022 23 24 25 26 27 28 19 20 21 22 23 24 25 16 17 18 19 20 21 22\n\
869 \x2029 30 31 26 27 28 29 30 31 23 24 25 26 27 28 29\n\
870 \x20 30 \n\
871 \n\
872 \x20 October November December \n\
873 \x20 1 2 3 4 5 6 1 2 3 1\n\
874 \x20 7 8 9 10 11 12 13 4 5 6 7 8 9 10 2 3 4 5 6 7 8\n\
875 \x2014 15 16 17 18 19 20 11 12 13 14 15 16 17 9 10 11 12 13 14 15\n\
876 \x2021 22 23 24 25 26 27 18 19 20 21 22 23 24 16 17 18 19 20 21 22\n\
877 \x2028 29 30 31 25 26 27 28 29 30 23 24 25 26 27 28 29\n\
878 \x20 30 31 ");
879
880 assert_eq_cal!(&format_year(2015, MONTHS_PER_ROW), "\
881 \x20 January February March \n\
882 \x20 1 2 3 1 2 3 4 5 6 7 1 2 3 4 5 6 7\n\
883 \x20 4 5 6 7 8 9 10 8 9 10 11 12 13 14 8 9 10 11 12 13 14\n\
884 \x2011 12 13 14 15 16 17 15 16 17 18 19 20 21 15 16 17 18 19 20 21\n\
885 \x2018 19 20 21 22 23 24 22 23 24 25 26 27 28 22 23 24 25 26 27 28\n\
886 \x2025 26 27 28 29 30 31 29 30 31 \n\
887 \n\
888 \x20 April May June \n\
889 \x20 1 2 3 4 1 2 1 2 3 4 5 6\n\
890 \x20 5 6 7 8 9 10 11 3 4 5 6 7 8 9 7 8 9 10 11 12 13\n\
891 \x2012 13 14 15 16 17 18 10 11 12 13 14 15 16 14 15 16 17 18 19 20\n\
892 \x2019 20 21 22 23 24 25 17 18 19 20 21 22 23 21 22 23 24 25 26 27\n\
893 \x2026 27 28 29 30 24 25 26 27 28 29 30 28 29 30 \n\
894 \x20 31 \n\
895 \n\
896 \x20 July August September \n\
897 \x20 1 2 3 4 1 1 2 3 4 5\n\
898 \x20 5 6 7 8 9 10 11 2 3 4 5 6 7 8 6 7 8 9 10 11 12\n\
899 \x2012 13 14 15 16 17 18 9 10 11 12 13 14 15 13 14 15 16 17 18 19\n\
900 \x2019 20 21 22 23 24 25 16 17 18 19 20 21 22 20 21 22 23 24 25 26\n\
901 \x2026 27 28 29 30 31 23 24 25 26 27 28 29 27 28 29 30 \n\
902 \x20 30 31 \n\
903 \n\
904 \x20 October November December \n\
905 \x20 1 2 3 1 2 3 4 5 6 7 1 2 3 4 5\n\
906 \x20 4 5 6 7 8 9 10 8 9 10 11 12 13 14 6 7 8 9 10 11 12\n\
907 \x2011 12 13 14 15 16 17 15 16 17 18 19 20 21 13 14 15 16 17 18 19\n\
908 \x2018 19 20 21 22 23 24 22 23 24 25 26 27 28 20 21 22 23 24 25 26\n\
909 \x2025 26 27 28 29 30 31 29 30 27 28 29 30 31 ");
910 }
911
912 fn main() {
913 // Run tests.
914 test_spaces();
915 test_dates_in_year();
916 test_group_by();
917 test_by_month();
918 test_isoweekdate();
919 test_by_week();
920 test_format_weeks();
921 test_month_title();
922 test_format_month();
923 test_paste_blocks();
924 test_chunks();
925 test_format_year();
926 }