croner 4.0.0

Fully-featured, lightweight, and efficient Rust library designed for parsing and evaluating cron patterns
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
//! Parser for Cron patterns.
//!
//! Croner uses [`CronParser`] to parse the cron expression. Invoking
//!
//! ```rust
//! # use std::str::FromStr as _;
//! #
//! # use croner::{Cron, parser::CronParser};
//! #
//! Cron::from_str("pattern");
//! ```
//!
//! is equivalent to
//!
//! ```rust
//! # use std::str::FromStr as _;
//! #
//! # use croner::{Cron, parser::CronParser};
//! #
//! CronParser::new().parse("pattern");
//! ```
//!
//! You can customise the parser by creating a parser builder using
//! [`CronParser::builder`]. So, for example, to parse cron patterns with
//! optional seconds do something like this:
//!
//! ```rust
//! use croner::parser::{CronParser, Seconds};
//!
//! // Configure the parser to allow seconds.
//! let parser = CronParser::builder().seconds(Seconds::Optional).build();
//!
//! let cron_with_seconds = parser
//!     .parse("*/10 * * * * *")
//!     .unwrap();
//! let cron_without_seconds = parser
//!     .parse("* * * * *")
//!     .unwrap();
//! ```

use derive_builder::Builder;
use strum::EnumIs;

use crate::{
    component::{
        CronComponent, ALL_BIT, CLOSEST_WEEKDAY_BIT, LAST_BIT, NONE_BIT, NTH_1ST_BIT, NTH_2ND_BIT,
        NTH_3RD_BIT, NTH_4TH_BIT, NTH_5TH_BIT, NTH_ALL,
    },
    errors::CronError,
    pattern::CronPattern,
    Cron, YEAR_LOWER_LIMIT, YEAR_UPPER_LIMIT,
};

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, EnumIs)]
pub enum Seconds {
    #[default]
    Optional,
    Required,
    Disallowed,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, EnumIs)]
pub enum Year {
    #[default]
    Optional,
    Required,
    Disallowed,
}

/// Parser for Cron patterns.
///
/// In order to build a custom cron parser use [`CronParser::builder`].
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Builder)]
#[builder(default, build_fn(skip), pattern = "owned")]
pub struct CronParser {
    /// Configure how seconds should be handled.
    seconds: Seconds,
    /// Configure how years should be handled.
    year: Year,
    /// Enable the combination of Day of Month (DOM) and Day of Week (DOW) conditions.
    dom_and_dow: bool,
    /// Use the Quartz-style weekday mode.
    alternative_weekdays: bool,
    /// Allow sloppy range syntax (e.g., `0/10` or `/10`) for backward compatibility.
    /// When enabled, patterns like `0/10` (start at 0, step by 10) and `/10` (same as `*/10`)
    /// are accepted. This is not compliant with OCPS/vixie-cron standards.
    sloppy_ranges: bool,
}

impl CronParser {
    /// Create a new parser.
    ///
    /// You should probably be using [`Cron`]'s implementation of
    /// [`FromStr`][std::str::FromStr] instead of invoking this.
    pub fn new() -> Self {
        Self::default()
    }

    /// Construct a builder for custom parsing.
    ///
    /// Equivalent to [`CronParserBuilder::default`].
    pub fn builder() -> CronParserBuilder {
        CronParserBuilder::default()
    }

    /// Parses the cron pattern string.
    pub fn parse(&self, pattern: &str) -> Result<Cron, CronError> {
        // Ensure upper case in parsing, and trim it
        let mut pattern: String = pattern.to_uppercase().trim().to_string();

        // Should already be trimmed
        if pattern.is_empty() {
            return Err(CronError::EmptyPattern);
        }

        // Handle @nicknames
        if pattern.contains('@') {
            pattern = Self::handle_nicknames(
                &pattern,
                self.seconds.is_required(),
                self.year.is_required(),
            )
            .to_string();
        }

        // Handle day-of-week and month aliases (MON... and JAN...)
        pattern = Self::replace_alpha_weekdays(&pattern, self.alternative_weekdays).to_string();
        pattern = Self::replace_alpha_months(&pattern).to_string();

        // Split the pattern into parts
        let mut parts: Vec<&str> = pattern.split_whitespace().collect();
        let num_parts = parts.len();

        // Default seconds to "0" if omitted in an optional context
        if num_parts == 5 {
            parts.insert(0, "0");
        } else if self.seconds.is_disallowed() {
            return Err(CronError::InvalidPattern(
                "Pattern must have 5 fields when seconds are disallowed.".to_string(),
            ));
        }

        // Default year to "*" if omitted in an optional context
        if parts.len() == 6 {
            parts.push("*");
        } else if self.year.is_disallowed() {
            return Err(CronError::InvalidPattern(
                "Pattern must have 5 or 6 fields when years are disallowed.".to_string(),
            ));
        }

        // Validate pattern length based on configuration
        if self.seconds.is_required() {
            if self.year.is_required() && num_parts != 7 {
                return Err(CronError::InvalidPattern(
                    "Pattern must have 7 fields when seconds and years are required.".to_string(),
                ));
            }
            if self.year.is_disallowed() && num_parts != 6 {
                return Err(CronError::InvalidPattern("Pattern must have 6 fields when seconds are required and years are disallowed.".to_string()));
            }
            if self.year.is_optional() && !(6..=7).contains(&num_parts) {
                return Err(CronError::InvalidPattern("Pattern must have 6 or 7 fields when seconds are required and years are optional.".to_string()));
            }
        } else if self.year.is_required() && num_parts != 7 {
            return Err(CronError::InvalidPattern(
                "Pattern must have 7 fields when years are required.".to_string(),
            ));
        } else if !(5..=7).contains(&num_parts) {
            return Err(CronError::InvalidPattern(
                "Pattern must have between 5 and 7 fields.".to_string(),
            ));
        }

        // Replace ? with * in day-of-month and day-of-week
        let mut owned_parts = parts.iter().map(|s| s.to_string()).collect::<Vec<String>>();
        if owned_parts.get(3).is_some_and(|p| p.contains('?')) {
            owned_parts[3] = owned_parts[3].replace('?', "*");
        }
        if owned_parts.get(5).is_some_and(|p| p.contains('?')) {
            owned_parts[5] = owned_parts[5].replace('?', "*");
        }

        // Check for the '+' (AND) modifier in the day-of-week field.
        // This must be done before illegal character validation.
        let mut dom_and_dow_from_pattern = false;
        if let Some(dow_part) = owned_parts.get_mut(5) {
            if dow_part.starts_with('+') {
                dom_and_dow_from_pattern = true;
                // Remove the '+' so the rest of the field can be parsed normally.
                *dow_part = dow_part[1..].to_string();
            }
        }
        parts = owned_parts.iter().map(|s| s.as_str()).collect();

        // Throw at illegal characters
        self.throw_at_illegal_characters(&parts)?;

        // Handle star-dom and star-dow
        let star_dom = parts.get(3).is_some_and(|&p| p == "*");
        let star_dow = parts.get(5).is_some_and(|&p| p == "*");

        // Parse the individual components
        let mut seconds = CronComponent::new(0, 59, NONE_BIT, 0);
        seconds.set_sloppy_ranges(self.sloppy_ranges);
        seconds.parse(parts[0])?;

        let mut minutes = CronComponent::new(0, 59, NONE_BIT, 0);
        minutes.set_sloppy_ranges(self.sloppy_ranges);
        minutes.parse(parts[1])?;

        let mut hours = CronComponent::new(0, 23, NONE_BIT, 0);
        hours.set_sloppy_ranges(self.sloppy_ranges);
        hours.parse(parts[2])?;
        let mut days = CronComponent::new(1, 31, LAST_BIT | CLOSEST_WEEKDAY_BIT, 0);
        days.set_sloppy_ranges(self.sloppy_ranges);
        days.parse(parts[3])?;
        let mut months = CronComponent::new(1, 12, NONE_BIT, 0);
        months.set_sloppy_ranges(self.sloppy_ranges);
        months.parse(parts[4])?;

        let mut days_of_week = if self.alternative_weekdays {
            CronComponent::new(0, 7, LAST_BIT | NTH_ALL, 1)
        } else {
            CronComponent::new(0, 7, LAST_BIT | NTH_ALL, 0)
        };
        days_of_week.set_sloppy_ranges(self.sloppy_ranges);
        days_of_week.parse(parts[5])?;

        let mut years = CronComponent::new(
            YEAR_LOWER_LIMIT as u16,
            YEAR_UPPER_LIMIT as u16,
            NONE_BIT,
            0,
        ); // Placeholder, real limits are i32
        years.set_sloppy_ranges(self.sloppy_ranges);
        years.parse(parts[6])?;

        // Handle conversion of 7 to 0 for day_of_week if necessary
        if !self.alternative_weekdays {
            for nth_bit in [
                ALL_BIT,
                NTH_1ST_BIT,
                NTH_2ND_BIT,
                NTH_3RD_BIT,
                NTH_4TH_BIT,
                NTH_5TH_BIT,
            ] {
                if days_of_week.is_bit_set(7, nth_bit)? {
                    days_of_week.unset_bit(7, nth_bit)?;
                    days_of_week.set_bit(0, nth_bit)?;
                }
            }
        }

        Ok(Cron {
            pattern: CronPattern {
                pattern,
                seconds,
                minutes,
                hours,
                days,
                months,
                days_of_week,
                years,
                star_dom,
                star_dow,
                dom_and_dow: self.dom_and_dow || dom_and_dow_from_pattern,
            },
        })
    }

    // Validates that the cron pattern only contains legal characters for each field.
    fn throw_at_illegal_characters(&self, parts: &[&str]) -> Result<(), CronError> {
        let base_allowed_characters = [
            '*', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ',', '-',
        ];
        let day_of_week_additional_characters = ['#', 'L', '?'];
        let day_of_month_additional_characters = ['L', 'W', '?'];

        for (i, part) in parts.iter().enumerate() {
            // Decide which set of allowed characters to use
            let allowed = match i {
                3 => [
                    base_allowed_characters.as_ref(),
                    day_of_month_additional_characters.as_ref(),
                ]
                .concat(),
                5 => [
                    base_allowed_characters.as_ref(),
                    day_of_week_additional_characters.as_ref(),
                ]
                .concat(),
                // All other fields, including year (index 6) use base characters
                _ => base_allowed_characters.to_vec(),
            };

            for ch in part.chars() {
                if !allowed.contains(&ch) {
                    return Err(CronError::IllegalCharacters(format!(
                        "CronPattern contains illegal character '{ch}' in part '{part}'"
                    )));
                }
            }
        }
        Ok(())
    }

    // Converts named cron pattern shortcuts into their equivalent standard cron pattern.
    fn handle_nicknames(pattern: &str, with_seconds: bool, with_year: bool) -> String {
        let pattern = pattern.trim();
        let eq_ignore_case = |a: &str, b: &str| a.eq_ignore_ascii_case(b);

        let base_pattern = match pattern {
            p if eq_ignore_case(p, "@yearly") || eq_ignore_case(p, "@annually") => "0 0 1 1 *",
            p if eq_ignore_case(p, "@monthly") => "0 0 1 * *",
            p if eq_ignore_case(p, "@weekly") => "0 0 * * 0",
            p if eq_ignore_case(p, "@daily") => "0 0 * * *",
            p if eq_ignore_case(p, "@hourly") => "0 * * * *",
            _ => pattern,
        };

        let mut final_pattern = String::new();
        if with_seconds {
            final_pattern.push_str("0 ");
        }
        final_pattern.push_str(base_pattern);
        if with_year {
            final_pattern.push_str(" *");
        }

        final_pattern
    }

    // Converts day-of-week nicknames into their equivalent standard cron pattern.
    fn replace_alpha_weekdays(pattern: &str, alternative_weekdays: bool) -> String {
        let nicknames = if !alternative_weekdays {
            [
                ("-SUN", "-7"),
                ("SUN", "0"),
                ("MON", "1"),
                ("TUE", "2"),
                ("WED", "3"),
                ("THU", "4"),
                ("FRI", "5"),
                ("SAT", "6"),
            ]
        } else {
            [
                ("-SUN", "-1"),
                ("SUN", "1"),
                ("MON", "2"),
                ("TUE", "3"),
                ("WED", "4"),
                ("THU", "5"),
                ("FRI", "6"),
                ("SAT", "7"),
            ]
        };
        let mut replaced = pattern.to_string();

        // Replace nicknames with their numeric values
        for &(nickname, value) in &nicknames {
            replaced = replaced.replace(nickname, value);
        }

        replaced
    }

    // Converts month nicknames into their equivalent standard cron pattern.
    fn replace_alpha_months(pattern: &str) -> String {
        let nicknames = [
            ("JAN", "1"),
            ("FEB", "2"),
            ("MAR", "3"),
            ("APR", "4"),
            ("MAY", "5"),
            ("JUN", "6"),
            ("JUL", "7"),
            ("AUG", "8"),
            ("SEP", "9"),
            ("OCT", "10"),
            ("NOV", "11"),
            ("DEC", "12"),
        ];

        let mut replaced = pattern.to_string();

        // Replace nicknames with their numeric values
        for &(nickname, value) in &nicknames {
            replaced = replaced.replace(nickname, value);
        }

        replaced
    }
}

impl CronParserBuilder {
    pub fn build(self) -> CronParser {
        let CronParserBuilder {
            seconds,
            year,
            dom_and_dow,
            alternative_weekdays,
            sloppy_ranges,
        } = self;
        CronParser {
            seconds: seconds.unwrap_or_default(),
            year: year.unwrap_or_default(),
            dom_and_dow: dom_and_dow.unwrap_or_default(),
            alternative_weekdays: alternative_weekdays.unwrap_or_default(),
            sloppy_ranges: sloppy_ranges.unwrap_or_default(),
        }
    }
}

#[cfg(test)]
mod tests {
    use std::str::FromStr as _;

    use super::*;

    #[test]
    fn test_cron_pattern_new() {
        let cron = Cron::from_str("*/5 * * * *").unwrap();
        assert_eq!(cron.pattern.pattern, "*/5 * * * *");
        assert!(cron.pattern.seconds.is_bit_set(0, ALL_BIT).unwrap());
        assert!(cron.pattern.minutes.is_bit_set(5, ALL_BIT).unwrap());
    }

    #[test]
    fn test_cron_pattern_new_with_seconds_optional() {
        let cron = CronParser::builder()
            .seconds(Seconds::Optional)
            .build()
            .parse("* */5 * * * *")
            .expect("Success");
        assert_eq!(cron.pattern.pattern, "* */5 * * * *");
        assert!(cron.pattern.seconds.is_bit_set(5, ALL_BIT).unwrap());
    }

    #[test]
    fn test_cron_pattern_new_with_seconds_required() {
        let cron = CronParser::builder()
            .seconds(Seconds::Optional)
            .build()
            .parse("* */5 * * * *")
            .unwrap();
        assert_eq!(cron.pattern.pattern, "* */5 * * * *");
        assert!(cron.pattern.seconds.is_bit_set(5, ALL_BIT).unwrap());
    }

    #[test]
    fn test_cron_pattern_tostring() {
        let cron = Cron::from_str("*/5 * * * *").unwrap();
        assert_eq!(cron.to_string(), "*/5 * * * *");
    }

    #[test]
    fn test_cron_pattern_short() {
        let cron = Cron::from_str("5-59/5 * * * *").unwrap();
        assert_eq!(cron.pattern.pattern, "5-59/5 * * * *");
        assert!(cron.pattern.seconds.is_bit_set(0, ALL_BIT).unwrap());
        assert!(!cron.pattern.seconds.is_bit_set(5, ALL_BIT).unwrap());
        assert!(cron.pattern.minutes.is_bit_set(5, ALL_BIT).unwrap());
        assert!(!cron.pattern.minutes.is_bit_set(0, ALL_BIT).unwrap());
    }

    #[test]
    fn test_cron_pattern_parse() {
        let cron = Cron::from_str("*/15 1 1,15 1 1-5").unwrap();
        assert!(cron.pattern.minutes.is_bit_set(0, ALL_BIT).unwrap());
        assert!(cron.pattern.hours.is_bit_set(1, ALL_BIT).unwrap());
        assert!(
            cron.pattern.days.is_bit_set(1, ALL_BIT).unwrap()
                && cron.pattern.days.is_bit_set(15, ALL_BIT).unwrap()
        );
        assert!(
            cron.pattern.months.is_bit_set(1, ALL_BIT).unwrap()
                && !cron.pattern.months.is_bit_set(2, ALL_BIT).unwrap()
        );
        assert!(
            cron.pattern.days_of_week.is_bit_set(1, ALL_BIT).unwrap()
                && cron.pattern.days_of_week.is_bit_set(5, ALL_BIT).unwrap()
        );
    }

    #[test]
    fn test_cron_pattern_extra_whitespace() {
        let cron = Cron::from_str("  */15  1 1,15 1    1-5    ").unwrap();
        assert!(cron.pattern.minutes.is_bit_set(0, ALL_BIT).unwrap());
        assert!(cron.pattern.hours.is_bit_set(1, ALL_BIT).unwrap());
        assert!(
            cron.pattern.days.is_bit_set(1, ALL_BIT).unwrap()
                && cron.pattern.days.is_bit_set(15, ALL_BIT).unwrap()
        );
        assert!(
            cron.pattern.months.is_bit_set(1, ALL_BIT).unwrap()
                && !cron.pattern.months.is_bit_set(2, ALL_BIT).unwrap()
        );
        assert!(
            cron.pattern.days_of_week.is_bit_set(1, ALL_BIT).unwrap()
                && cron.pattern.days_of_week.is_bit_set(5, ALL_BIT).unwrap()
        );
    }

    #[test]
    fn test_cron_pattern_leading_zeros() {
        let cron = Cron::from_str("  */15  01 01,15 01    01-05    ").unwrap();
        assert!(cron.pattern.minutes.is_bit_set(0, ALL_BIT).unwrap());
        assert!(cron.pattern.hours.is_bit_set(1, ALL_BIT).unwrap());
        assert!(
            cron.pattern.days.is_bit_set(1, ALL_BIT).unwrap()
                && cron.pattern.days.is_bit_set(15, ALL_BIT).unwrap()
        );
        assert!(
            cron.pattern.months.is_bit_set(1, ALL_BIT).unwrap()
                && !cron.pattern.months.is_bit_set(2, ALL_BIT).unwrap()
        );
        assert!(
            cron.pattern.days_of_week.is_bit_set(1, ALL_BIT).unwrap()
                && cron.pattern.days_of_week.is_bit_set(5, ALL_BIT).unwrap()
        );
    }

    #[test]
    fn test_cron_pattern_handle_nicknames() {
        assert_eq!(
            CronParser::handle_nicknames("@yearly", false, false),
            "0 0 1 1 *"
        );
        assert_eq!(
            CronParser::handle_nicknames("@monthly", false, false),
            "0 0 1 * *"
        );
        assert_eq!(
            CronParser::handle_nicknames("@weekly", false, false),
            "0 0 * * 0"
        );
        assert_eq!(
            CronParser::handle_nicknames("@daily", false, false),
            "0 0 * * *"
        );
        assert_eq!(
            CronParser::handle_nicknames("@hourly", false, false),
            "0 * * * *"
        );
    }

    #[test]
    fn test_cron_pattern_handle_nicknames_with_seconds_required() {
        assert_eq!(
            CronParser::handle_nicknames("@yearly", true, false),
            "0 0 0 1 1 *"
        );
        assert_eq!(
            CronParser::handle_nicknames("@monthly", true, false),
            "0 0 0 1 * *"
        );
        assert_eq!(
            CronParser::handle_nicknames("@weekly", true, false),
            "0 0 0 * * 0"
        );
        assert_eq!(
            CronParser::handle_nicknames("@daily", true, false),
            "0 0 0 * * *"
        );
        assert_eq!(
            CronParser::handle_nicknames("@hourly", true, false),
            "0 0 * * * *"
        );
    }

    #[test]
    fn test_month_nickname_range() {
        let cron = Cron::from_str("0 0 * FEB-MAR *").unwrap();
        assert!(!cron.pattern.months.is_bit_set(1, ALL_BIT).unwrap());
        assert!(cron.pattern.months.is_bit_set(2, ALL_BIT).unwrap()); // February
        assert!(cron.pattern.months.is_bit_set(3, ALL_BIT).unwrap()); // March
        assert!(!cron.pattern.months.is_bit_set(4, ALL_BIT).unwrap());
    }

    #[test]
    fn test_weekday_range_sat_sun() {
        let cron = Cron::from_str("0 0 * * SAT-SUN").unwrap();
        assert!(cron.pattern.days_of_week.is_bit_set(0, ALL_BIT).unwrap()); // Sunday
        assert!(cron.pattern.days_of_week.is_bit_set(6, ALL_BIT).unwrap()); // Saturday
    }

    #[test]
    fn test_with_seconds_false() {
        // Explicitly create a parser that disallows seconds
        let parser = CronParser::builder().seconds(Seconds::Disallowed).build();

        // Test with a 6-part pattern when seconds are not allowed
        let error = parser.parse("* * * * * *").unwrap_err();
        assert!(matches!(error, CronError::InvalidPattern(_)));

        // Test with a 5-part pattern when seconds are not allowed
        let no_seconds_pattern = parser.parse("*/10 * * * *").unwrap();

        assert_eq!(no_seconds_pattern.to_string(), "*/10 * * * *");

        // Ensure seconds are defaulted to 0 for a 5-part pattern
        assert!(no_seconds_pattern
            .pattern
            .seconds
            .is_bit_set(0, ALL_BIT)
            .unwrap());
    }

    #[test]
    fn test_with_seconds_required() {
        // Test with a 5-part pattern when seconds are required
        let no_seconds_pattern = CronParser::builder()
            .seconds(Seconds::Required)
            .build()
            .parse("*/10 * * * *")
            .unwrap_err();

        assert!(matches!(no_seconds_pattern, CronError::InvalidPattern(_)));

        // Test with a 6-part pattern when seconds are required
        let cron = CronParser::builder()
            .seconds(Seconds::Required)
            .build()
            .parse("* * * * * *")
            .unwrap();

        // Ensure the 6-part pattern retains seconds information
        // (This assertion depends on how your CronPattern is structured and how it stores seconds information)
        assert!(cron.pattern.seconds.is_bit_set(0, ALL_BIT).unwrap());
    }

    #[test]
    fn test_with_alternative_weekdays() {
        // Test with alternative weekdays enabled
        let cron = CronParser::builder()
            .alternative_weekdays(true)
            .build()
            .parse("* * * * MON-FRI")
            .unwrap();

        // Ensure that the days of the week are offset correctly
        // Note: In this scenario, "MON-FRI" should be treated as "SUN-THU"
        assert!(cron.pattern.days_of_week.is_bit_set(1, ALL_BIT).unwrap()); // Monday
        assert!(cron.pattern.days_of_week.is_bit_set(5, ALL_BIT).unwrap()); // Friday
        assert!(!cron.pattern.days_of_week.is_bit_set(6, ALL_BIT).unwrap()); // Saturday should not be set
    }

    #[test]
    fn test_with_alternative_weekdays_numeric() {
        // Test with alternative weekdays enabled
        let cron = CronParser::builder()
            .alternative_weekdays(true)
            .build()
            .parse("* * * * 2-6")
            .unwrap();

        // Ensure that the days of the week are offset correctly
        // Note: In this scenario, "MON-FRI" should be treated as "SUN-THU"
        assert!(cron.pattern.days_of_week.is_bit_set(1, ALL_BIT).unwrap()); // Monday
        assert!(cron.pattern.days_of_week.is_bit_set(5, ALL_BIT).unwrap()); // Friday
        assert!(!cron.pattern.days_of_week.is_bit_set(6, ALL_BIT).unwrap()); // Saturday should not be set
    }

    #[test]
    fn test_seven_to_zero() {
        // Test with alternative weekdays enabled
        let cron = Cron::from_str("* * * * 7").unwrap();

        // Ensure that the days of the week are offset correctly
        // Note: In this scenario, "MON-FRI" should be treated as "SUN-THU"
        assert!(cron.pattern.days_of_week.is_bit_set(0, ALL_BIT).unwrap()); // Monday
    }

    #[test]
    fn test_one_is_monday_alternative() {
        // Test with alternative weekdays enabled
        let cron = CronParser::builder()
            .alternative_weekdays(true)
            .build()
            .parse("* * * * 1")
            .unwrap();

        // Ensure that the days of the week are offset correctly
        // Note: In this scenario, "MON-FRI" should be treated as "SUN-THU"
        assert!(cron.pattern.days_of_week.is_bit_set(0, ALL_BIT).unwrap()); // Monday
    }

    #[test]
    fn test_zero_with_alternative_weekdays_fails() {
        // Test with alternative weekdays enabled
        let error = CronParser::builder()
            .alternative_weekdays(true)
            .build()
            .parse("* * * * 0")
            .unwrap_err();

        // Parsing should raise a ComponentError
        assert!(matches!(error, CronError::ComponentError(_)));
    }

    #[test]
    fn test_question_mark_allowed_in_day_of_month() {
        let pattern = "* * ? * *";
        assert!(
            Cron::from_str(pattern).is_ok(),
            "Should allow '?' in the day-of-month field."
        );
    }

    #[test]
    fn test_question_mark_allowed_in_day_of_week() {
        let pattern = "* * * * ?";
        assert!(
            Cron::from_str(pattern).is_ok(),
            "Should allow '?' in the day-of-week field."
        );
    }

    #[test]
    fn test_question_mark_disallowed_in_minute() {
        let pattern = "? * * * *";
        let result = Cron::from_str(pattern);
        assert!(
            matches!(result.err(), Some(CronError::IllegalCharacters(_))),
            "Should not allow '?' in the minute field."
        );
    }

    #[test]
    fn test_question_mark_disallowed_in_hour() {
        let pattern = "* ? * * *";
        let result = Cron::from_str(pattern);
        assert!(
            matches!(result.err(), Some(CronError::IllegalCharacters(_))),
            "Should not allow '?' in the hour field."
        );
    }

    #[test]
    fn test_question_mark_disallowed_in_month() {
        let pattern = "* * * ? *";
        let result = Cron::from_str(pattern);
        assert!(
            matches!(result.err(), Some(CronError::IllegalCharacters(_))),
            "Should not allow '?' in the month field."
        );
    }

    #[test]
    fn test_case_sensitivity_lowercase_special_character_ok() {
        let pattern = "* * 15w * *";
        let result = Cron::from_str(pattern);
        assert!(
            result.is_ok(),
            "Should allow lowercase special character w."
        );
    }

    #[test]
    fn test_case_sensitivity_uppercase_special_character_ok() {
        let pattern = "* * 15W * *";
        let result: Result<Cron, CronError> = Cron::from_str(pattern);
        assert!(
            result.is_ok(),
            "Should allow uppercase special character W."
        );
    }

    // Tests for case insensitivity of aliases and modifiers
    #[test]
    fn test_nickname_aliases_case_insensitive() {
        // Test each nickname alias in different cases
        let nicknames = [
            ("@yearly", "@YEARLY", "@YeArLy"),
            ("@annually", "@ANNUALLY", "@AnNuAlLy"),
            ("@monthly", "@MONTHLY", "@MoNtHlY"),
            ("@weekly", "@WEEKLY", "@WeEkLy"),
            ("@daily", "@DAILY", "@DaIlY"),
            ("@hourly", "@HOURLY", "@HoUrLy"),
        ];

        for (lower, upper, mixed) in nicknames {
            let result_lower = Cron::from_str(lower);
            let result_upper = Cron::from_str(upper);
            let result_mixed = Cron::from_str(mixed);

            assert!(result_lower.is_ok(), "Should parse lowercase {}", lower);
            assert!(result_upper.is_ok(), "Should parse uppercase {}", upper);
            assert!(result_mixed.is_ok(), "Should parse mixed case {}", mixed);

            // Verify they all produce the same result
            let cron_lower = result_lower.unwrap();
            let cron_upper = result_upper.unwrap();
            let cron_mixed = result_mixed.unwrap();

            assert_eq!(
                cron_lower.pattern, cron_upper.pattern,
                "Lowercase and uppercase {} should produce the same pattern",
                lower
            );
            assert_eq!(
                cron_lower.pattern, cron_mixed.pattern,
                "Lowercase and mixed case {} should produce the same pattern",
                lower
            );
        }
    }

    #[test]
    fn test_month_aliases_case_insensitive() {
        // Test each month alias in different cases
        let months = [
            ("JAN", "jan", "Jan"),
            ("FEB", "feb", "Feb"),
            ("MAR", "mar", "Mar"),
            ("APR", "apr", "Apr"),
            ("MAY", "may", "May"),
            ("JUN", "jun", "Jun"),
            ("JUL", "jul", "Jul"),
            ("AUG", "aug", "Aug"),
            ("SEP", "sep", "Sep"),
            ("OCT", "oct", "Oct"),
            ("NOV", "nov", "Nov"),
            ("DEC", "dec", "Dec"),
        ];

        for (upper, lower, mixed) in months {
            let pattern_upper = format!("0 0 1 {} *", upper);
            let pattern_lower = format!("0 0 1 {} *", lower);
            let pattern_mixed = format!("0 0 1 {} *", mixed);

            let result_upper = Cron::from_str(&pattern_upper);
            let result_lower = Cron::from_str(&pattern_lower);
            let result_mixed = Cron::from_str(&pattern_mixed);

            assert!(result_upper.is_ok(), "Should parse uppercase {}", upper);
            assert!(result_lower.is_ok(), "Should parse lowercase {}", lower);
            assert!(result_mixed.is_ok(), "Should parse mixed case {}", mixed);

            // Verify they all produce the same result
            let cron_upper = result_upper.unwrap();
            let cron_lower = result_lower.unwrap();
            let cron_mixed = result_mixed.unwrap();

            assert_eq!(
                cron_upper.pattern.months, cron_lower.pattern.months,
                "Uppercase and lowercase {} should produce the same months",
                upper
            );
            assert_eq!(
                cron_upper.pattern.months, cron_mixed.pattern.months,
                "Uppercase and mixed case {} should produce the same months",
                upper
            );
        }
    }

    #[test]
    fn test_weekday_aliases_case_insensitive() {
        // Test each weekday alias in different cases
        let weekdays = [
            ("SUN", "sun", "Sun"),
            ("MON", "mon", "Mon"),
            ("TUE", "tue", "Tue"),
            ("WED", "wed", "Wed"),
            ("THU", "thu", "Thu"),
            ("FRI", "fri", "Fri"),
            ("SAT", "sat", "Sat"),
        ];

        for (upper, lower, mixed) in weekdays {
            let pattern_upper = format!("0 0 * * {}", upper);
            let pattern_lower = format!("0 0 * * {}", lower);
            let pattern_mixed = format!("0 0 * * {}", mixed);

            let result_upper = Cron::from_str(&pattern_upper);
            let result_lower = Cron::from_str(&pattern_lower);
            let result_mixed = Cron::from_str(&pattern_mixed);

            assert!(result_upper.is_ok(), "Should parse uppercase {}", upper);
            assert!(result_lower.is_ok(), "Should parse lowercase {}", lower);
            assert!(result_mixed.is_ok(), "Should parse mixed case {}", mixed);

            // Verify they all produce the same result
            let cron_upper = result_upper.unwrap();
            let cron_lower = result_lower.unwrap();
            let cron_mixed = result_mixed.unwrap();

            assert_eq!(
                cron_upper.pattern.days_of_week, cron_lower.pattern.days_of_week,
                "Uppercase and lowercase {} should produce the same days_of_week",
                upper
            );
            assert_eq!(
                cron_upper.pattern.days_of_week, cron_mixed.pattern.days_of_week,
                "Uppercase and mixed case {} should produce the same days_of_week",
                upper
            );
        }
    }

    #[test]
    fn test_last_modifier_case_insensitive() {
        // Test L modifier for last day of month
        let patterns = ["0 0 L * *", "0 0 l * *"];
        let results: Vec<_> = patterns.iter().map(|p| Cron::from_str(p)).collect();

        for (i, result) in results.iter().enumerate() {
            assert!(
                result.is_ok(),
                "Should parse L modifier pattern: {}",
                patterns[i]
            );
        }

        let cron_upper = results[0].as_ref().unwrap();
        let cron_lower = results[1].as_ref().unwrap();
        assert_eq!(
            cron_upper.pattern.days, cron_lower.pattern.days,
            "L and l modifiers should produce the same days"
        );
    }

    #[test]
    fn test_last_weekday_modifier_case_insensitive() {
        // Test xL modifier for last occurrence of weekday
        let patterns = ["0 0 * * 5L", "0 0 * * 5l"];
        let results: Vec<_> = patterns.iter().map(|p| Cron::from_str(p)).collect();

        for (i, result) in results.iter().enumerate() {
            assert!(
                result.is_ok(),
                "Should parse weekday L modifier pattern: {}",
                patterns[i]
            );
        }

        let cron_upper = results[0].as_ref().unwrap();
        let cron_lower = results[1].as_ref().unwrap();
        assert_eq!(
            cron_upper.pattern.days_of_week, cron_lower.pattern.days_of_week,
            "5L and 5l modifiers should produce the same days_of_week"
        );
    }

    #[test]
    fn test_closest_weekday_modifier_case_insensitive() {
        // Test W modifier for closest weekday
        let patterns = ["0 0 15W * *", "0 0 15w * *"];
        let results: Vec<_> = patterns.iter().map(|p| Cron::from_str(p)).collect();

        for (i, result) in results.iter().enumerate() {
            assert!(
                result.is_ok(),
                "Should parse W modifier pattern: {}",
                patterns[i]
            );
        }

        let cron_upper = results[0].as_ref().unwrap();
        let cron_lower = results[1].as_ref().unwrap();
        assert_eq!(
            cron_upper.pattern.days, cron_lower.pattern.days,
            "15W and 15w modifiers should produce the same days"
        );
    }

    #[test]
    fn test_last_weekday_of_month_lw_case_insensitive() {
        // Test LW modifier for last weekday of month
        let patterns = ["0 0 LW * *", "0 0 lw * *", "0 0 Lw * *", "0 0 lW * *"];
        let results: Vec<_> = patterns.iter().map(|p| Cron::from_str(p)).collect();

        for (i, result) in results.iter().enumerate() {
            assert!(
                result.is_ok(),
                "Should parse LW modifier pattern: {}",
                patterns[i]
            );
        }

        // Verify they all produce the same result
        let cron_first = results[0].as_ref().unwrap();
        for (i, result) in results.iter().enumerate().skip(1) {
            let cron = result.as_ref().unwrap();
            assert_eq!(
                cron_first.pattern.days, cron.pattern.days,
                "LW pattern {} should produce the same days as LW",
                patterns[i]
            );
        }
    }

    #[test]
    fn test_weekday_alias_with_nth_modifier_case_insensitive() {
        // Test weekday aliases with # modifier in different cases
        let patterns = ["0 0 * * MON#2", "0 0 * * mon#2", "0 0 * * Mon#2"];
        let results: Vec<_> = patterns.iter().map(|p| Cron::from_str(p)).collect();

        for (i, result) in results.iter().enumerate() {
            assert!(
                result.is_ok(),
                "Should parse weekday with # pattern: {}",
                patterns[i]
            );
        }

        let cron_first = results[0].as_ref().unwrap();
        for (i, result) in results.iter().enumerate().skip(1) {
            let cron = result.as_ref().unwrap();
            assert_eq!(
                cron_first.pattern.days_of_week, cron.pattern.days_of_week,
                "Pattern {} should produce the same days_of_week as MON#2",
                patterns[i]
            );
        }
    }

    #[test]
    fn test_month_alias_range_case_insensitive() {
        // Test month ranges with different cases
        let patterns = ["0 0 * JAN-MAR *", "0 0 * jan-mar *", "0 0 * Jan-Mar *"];
        let results: Vec<_> = patterns.iter().map(|p| Cron::from_str(p)).collect();

        for (i, result) in results.iter().enumerate() {
            assert!(
                result.is_ok(),
                "Should parse month range pattern: {}",
                patterns[i]
            );
        }

        let cron_first = results[0].as_ref().unwrap();
        for (i, result) in results.iter().enumerate().skip(1) {
            let cron = result.as_ref().unwrap();
            assert_eq!(
                cron_first.pattern.months, cron.pattern.months,
                "Pattern {} should produce the same months as JAN-MAR",
                patterns[i]
            );
        }
    }

    #[test]
    fn test_weekday_alias_range_case_insensitive() {
        // Test weekday ranges with different cases
        let patterns = ["0 0 * * MON-FRI", "0 0 * * mon-fri", "0 0 * * Mon-Fri"];
        let results: Vec<_> = patterns.iter().map(|p| Cron::from_str(p)).collect();

        for (i, result) in results.iter().enumerate() {
            assert!(
                result.is_ok(),
                "Should parse weekday range pattern: {}",
                patterns[i]
            );
        }

        let cron_first = results[0].as_ref().unwrap();
        for (i, result) in results.iter().enumerate().skip(1) {
            let cron = result.as_ref().unwrap();
            assert_eq!(
                cron_first.pattern.days_of_week, cron.pattern.days_of_week,
                "Pattern {} should produce the same days_of_week as MON-FRI",
                patterns[i]
            );
        }
    }

    #[test]
    fn test_year_support() {
        let parser = CronParser::builder()
            .seconds(Seconds::Optional)
            .year(Year::Optional)
            .build();
        // 7-field pattern
        assert!(parser.parse("0 0 0 1 1 * 2025").is_ok());
        // 6-field pattern (year defaults to *)
        assert!(parser.parse("0 0 0 1 1 *").is_ok());
        // 5-field pattern (seconds defaults to 0, year to *)
        assert!(parser.parse("0 0 1 1 *").is_ok());
    }

    #[test]
    fn test_year_required() {
        let parser = CronParser::builder()
            .seconds(Seconds::Required)
            .year(Year::Required)
            .build();
        // Must have 7 fields
        assert!(parser.parse("0 0 0 1 1 * 2025").is_ok());
        // 6 fields should fail
        assert!(parser.parse("0 0 0 1 1 *").is_err());
    }

    #[test]
    fn test_optional_seconds_and_required_year_fails_on_six_parts() {
        // This parser configuration should only accept 7-part patterns.
        let parser = CronParser::builder()
            .seconds(Seconds::Optional)
            .year(Year::Required)
            .build();

        // A 6-part pattern should fail because the year is missing but required.
        let result = parser.parse("* * * * * *");

        assert!(
            matches!(result, Err(CronError::InvalidPattern(_))),
            "Should fail when year is required but not provided."
        );
    }
}