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
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
//! This module provides a pattern-string based formatter.
//!
//! The [`PatternFormatter`] struct defines a formatter that formats log
//! messages against a specific text pattern.
//!
//! Patterns are represented by the [`Pattern`] trait. You can create your own
//! pattern by implementing the [`Pattern`] trait.
//!
//! You can also build a pattern with the [`pattern`][pattern-macro] macro.
//!
//! [pattern-macro]: crate::formatter::pattern

#[doc(hidden)]
#[path = "pattern/mod.rs"]
pub mod __pattern;

use std::{fmt::Write, ops::Range, sync::Arc};

use crate::{
    formatter::{FmtExtraInfo, FmtExtraInfoBuilder, Formatter},
    Error, Record, StringBuf,
};

#[rustfmt::skip] // rustfmt currently breaks some empty lines if `#[doc = include_str!("xxx")]` exists
/// Build a pattern from a template string at compile-time.
///
/// It accepts inputs in the form:
///
/// ```ignore
/// // This is not exactly a valid declarative macro, just for intuition.
/// macro_rules! pattern {
///     ( $template:literal $(,)? ) => {};
///     ( $template:literal, $( {$$custom:ident} => $ctor:expr ),+ $(,)? ) => {};
/// }
/// ```
///
/// Examples of valid inputs:
///
/// ```
/// # use spdlog::formatter::pattern;
/// # #[derive(Default)]
/// # struct MyPattern;
/// pattern!("text");
/// pattern!("current line: {line}");
/// pattern!("custom: {$my_pattern}", {$my_pattern} => MyPattern::default);
/// ```
///
/// # Note
///
/// The value returned by this macro is implementation details and users should
/// not access them. If these details are changed in the future, it may not be
/// considered as a breaking change.
///
/// # Basic Usage
///
/// In its simplest form, `pattern` receives a **literal** pattern string and
/// converts it into a zero-cost pattern:
/// ```
/// use spdlog::formatter::{pattern, PatternFormatter};
///
/// let formatter = PatternFormatter::new(pattern!("pattern string"));
/// ```
///
/// # Using Built-in Patterns
///
/// A pattern that always outputs a fixed string is boring and useless.
/// Luckily, the pattern template string can contain placeholders that
/// represents built-in patterns. For example, to include the log level and
/// payload in the pattern, we can simply use `{level}` and `{payload}` in the
/// pattern template string:
/// ```
/// # use spdlog::formatter::{pattern, PatternFormatter};
/// use spdlog::info;
#[doc = include_str!("../../include/doc/test_utils.rs")]
///
/// let formatter = PatternFormatter::new(pattern!("[{level}] {payload}"));
/// # let (doctest, sink) = doc_test_utils::echo_logger_from_formatter(
/// #     Box::new(formatter),
/// #     None
/// # );
///
/// info!(logger: doctest, "Interesting log message");
/// # assert_eq!(
/// #     String::from_utf8(sink.clone_target()).unwrap(),
/// /* Output */ "[info] Interesting log message"
/// # );
/// ```
///
/// Here, `{level}` and `{payload}` are "placeholders" that will be replaced by
/// the output of the corresponding built-in patterns when formatting log
/// records.
///
/// What if you want to output a literal `{` or `}` character? Simply use `{{`
/// and `}}`:
/// ```
/// # use spdlog::{
/// #     formatter::{pattern, PatternFormatter},
/// #     info,
/// # };
#[doc = include_str!("../../include/doc/test_utils.rs")]
/// let formatter = PatternFormatter::new(pattern!("[{{escaped}}] {payload}"));
/// # let (doctest, sink) = doc_test_utils::echo_logger_from_formatter(
/// #     Box::new(formatter),
/// #     None
/// # );
///
/// info!(logger: doctest, "Interesting log message");
/// # assert_eq!(
/// #     String::from_utf8(sink.clone_target()).unwrap(),
/// /* Output */ "[{escaped}] Interesting log message"
/// # );
/// ```
///
/// You can find a full list of all built-in patterns and their corresponding
/// placeholders at [Appendix](#appendix-a-full-list-of-built-in-patterns)
/// below.
///
/// # Using Style Range
///
/// A specific portion of a formatted log message can be specified as "style
/// range". Formatted text in the style range will be rendered in a different
/// style by supported sinks. You can use `{^...}` to mark the style range in
/// the pattern template string:
/// ```
/// # use spdlog::{
/// #     formatter::{pattern, PatternFormatter},
/// #     info,
/// # };
#[doc = include_str!("../../include/doc/test_utils.rs")]
/// let formatter = PatternFormatter::new(pattern!("{^[{level}]} {payload}"));
/// # let (doctest, sink) = doc_test_utils::echo_logger_from_formatter(
/// #     Box::new(formatter),
/// #     None
/// # );
///
/// info!(logger: doctest, "Interesting log message");
/// # assert_eq!(
/// #     String::from_utf8(sink.clone_target()).unwrap(),
/// /* Output */ "[info] Interesting log message"
/// //            ^^^^^^ <- style range
/// # );
/// ```
/// 
/// # Using Your Own Patterns
///
/// Yes, you can refer your own implementation of [`Pattern`] in the pattern
/// template string! Let's say you have a struct that implements the
/// [`Pattern`] trait. To refer `MyPattern` in the pattern template string, you
/// need to use the extended syntax to associate `MyPattern` with a name so
/// that `pattern!` can resolve it:
/// ```
/// use std::fmt::Write;
///
/// use spdlog::{
///     formatter::{pattern, Pattern, PatternContext, PatternFormatter},
///     Record, StringBuf, info
/// };
#[doc = include_str!("../../include/doc/test_utils.rs")]
///
/// #[derive(Default, Clone)]
/// struct MyPattern;
///
/// impl Pattern for MyPattern {
///     fn format(
///         &self,
///         record: &Record,
///         dest: &mut StringBuf,
///         _ctx: &mut PatternContext,
///     ) -> spdlog::Result<()> {
///         write!(dest, "My own pattern").map_err(spdlog::Error::FormatRecord)
///     }
/// }
///
/// let pat = pattern!("[{level}] {payload} - {$mypat}",
///     {$mypat} => MyPattern::default,
/// );
/// let formatter = PatternFormatter::new(pat);
/// # let (doctest, sink) = doc_test_utils::echo_logger_from_formatter(
/// #     Box::new(formatter),
/// #     None
/// # );
///
/// info!(logger: doctest, "Interesting log message");
/// # assert_eq!(
/// #   String::from_utf8(sink.clone_target()).unwrap(),
/// /* Output */ "[info] Interesting log message - My own pattern"
/// # );
/// ```
///
/// Note the special `{$name} => id` syntax given to the `pattern` macro.
/// `name` is the name of your own pattern; placeholder `{$name}` in the
/// template string will be replaced by the output of your own pattern. `name`
/// can only be an identifier. `id` is a [path] that identifies a **function**
/// that can be called with **no arguments**. Instances of your own pattern
/// will be created by calling this function with no arguments.
///
/// [path]: https://doc.rust-lang.org/stable/reference/paths.html
///
/// ## Custom Pattern Creation
///
/// Each placeholder results in a new pattern instance. For example, consider a
/// custom pattern that writes a unique ID to the output. If the pattern
/// template string contains multiple placeholders that refer to `MyPattern`,
/// each placeholder will eventually be replaced by different IDs.
///
/// ```
/// # use std::{
/// #     fmt::Write,
/// #     sync::atomic::{AtomicU32, Ordering},
/// # };
/// # use spdlog::{
/// #     formatter::{pattern, Pattern, PatternContext, PatternFormatter},
/// #     prelude::*,
/// #     Record, StringBuf,
/// # };
#[doc = include_str!("../../include/doc/test_utils.rs")]
/// static NEXT_ID: AtomicU32 = AtomicU32::new(0);
///
/// #[derive(Clone)]
/// struct MyPattern {
///     id: u32,
/// }
///
/// impl MyPattern {
///     fn new() -> Self {
///         Self {
///             id: NEXT_ID.fetch_add(1, Ordering::Relaxed),
///         }
///     }
/// }
///
/// impl Pattern for MyPattern {
///     fn format(
///         &self,
///         record: &Record,
///         dest: &mut StringBuf,
///         _ctx: &mut PatternContext,
///     ) -> spdlog::Result<()> {
///         write!(dest, "{}", self.id).map_err(spdlog::Error::FormatRecord)
///     }
/// }
///
/// let pat = pattern!("[{level}] {payload} - {$mypat} {$mypat} {$mypat}",
///     {$mypat} => MyPattern::new,
/// );
/// let formatter = PatternFormatter::new(pat);
/// # let (doctest, sink) = doc_test_utils::echo_logger_from_formatter(
/// #     Box::new(formatter),
/// #     None
/// # );
///
/// info!(logger: doctest, "Interesting log message");
/// # assert_eq!(
/// #   String::from_utf8(sink.clone_target()).unwrap(),
/// /* Output */ "[info] Interesting log message - 0 1 2"
/// # );
/// ```
///
/// Of course, you can have multiple custom patterns:
/// ```
/// # use spdlog::formatter::pattern;
/// #
/// # #[derive(Default)]
/// # struct MyPattern;
/// # #[derive(Default)]
/// # struct MyOtherPattern;
/// #
/// let pat = pattern!("[{level}] {payload} - {$mypat} {$myotherpat}",
///     {$mypat} => MyPattern::default,
///     {$myotherpat} => MyOtherPattern::default,
/// );
/// ```
///
/// ## Name Conflicts are Hard Errors
///
/// It's a hard error if names of your own custom pattern conflicts with other
/// patterns:
///
/// ```compile_fail
/// # use spdlog::formatter::pattern;
/// #
/// # #[derive(Default)]
/// # struct MyPattern;
/// # #[derive(Default)]
/// # struct MyOtherPattern;
/// #
/// let pattern = pattern!("[{level}] {payload} - {$mypat}",
///     {$mypat} => MyPattern::new,
///     // Error: name conflicts with another custom pattern
///     {$mypat} => MyOtherPattern::new,
/// );
/// ```
///
/// ```compile_fail
/// # use spdlog::formatter::pattern;
/// #
/// # #[derive(Default)]
/// # struct MyPattern;
/// #
/// let pattern = pattern!("[{level}] {payload} - {$day}",
///     // Error: name conflicts with a built-in pattern
///     {$day} => MyPattern::new,
/// );
/// ```
///
/// # Appendix: A Full List of Built-in Patterns
///
/// | Placeholders          | Description                  | Example                                      |
/// | --------------------- | ---------------------------- | -------------------------------------------- |
/// | `{weekday_name}`      | Abbreviated weekday name     | `Mon`, `Tue`                                 |
/// | `{weekday_name_full}` | Weekday name                 | `Monday`, `Tuesday`                          |
/// | `{month_name}`        | Abbreviated month name       | `Jan`, `Feb`                                 |
/// | `{month_name_full}`   | Month name                   | `January`, `February`                        |
/// | `{datetime}`          | Full date time               | `Thu Aug 23 15:35:46 2014`                   |
/// | `{year_short}`        | Short year                   | `22`, `20`                                   |
/// | `{year}`              | Year                         | `2022`, `2021`                               |
/// | `{date_short}`        | Short date                   | `04/01/22`, `12/31/21`                       |
/// | `{date}`              | Date (ISO 8601)              | `2022-04-01`, `2021-12-31`                   |
/// | `{month}`             | Month                        | `01`, `12`                                   |
/// | `{day}`               | Day in month                 | `01`, `12`, `31`, `30`                       |
/// | `{hour}`              | Hour in 24-hour              | `01`, `12`, `23`                             |
/// | `{hour_12}`           | Hour in 12-hour              | `01`, `12`                                   |
/// | `{minute}`            | Minute                       | `00`, `05`, `59`                             |
/// | `{second}`            | Second                       | `00`, `05`, `59`                             |
/// | `{millisecond}`       | Millisecond                  | `231`                                        |
/// | `{microsecond}`       | Microseconds within a second | `372152`                                     |
/// | `{nanosecond}`        | Nanoseconds within a second  | `482930154`                                  |
/// | `{am_pm}`             | AM / PM                      | `AM`, `PM`                                   |
/// | `{time_12}`           | Time in 12-hour format       | `02:55:02 PM`                                |
/// | `{time_short}`        | Short time                   | `22:28`, `09:53`                             |
/// | `{time}`              | Time                         | `22:28:02`, `09:53:41`                       |
/// | `{tz_offset}`         | Timezone offset              | `+08:00`, `+00:00`, `-06:00`                 |
/// | `{unix_timestamp}`    | Unix timestamp               | `1528834770`                                 |
/// | `{full}`              | Full log message             | See [`FullFormatter`]                        |
/// | `{level}`             | Log level                    | `critical`, `error`, `warn`                  |
/// | `{level_short}`       | Short log level              | `C`, `E`, `W`                                |
/// | `{source}`            | Source file and line         | `path/to/main.rs:30` [^1]                    |
/// | `{file_name}`         | Source file name             | `main.rs` [^1]                               |
/// | `{file}`              | Source file path             | `path/to/main.rs` [^1]                       |
/// | `{line}`              | Source file line             | `30` [^1]                                    |
/// | `{column}`            | Source file column           | `20` [^1]                                    |
/// | `{module_path}`       | Source module path           | `mod::module` [^1]                           |
/// | `{logger}`            | Logger name                  | `my-logger`                                  |
/// | `{payload}`           | Log payload                  | `log message`                                |
/// | `{pid}`               | Process ID                   | `3824`                                       |
/// | `{tid}`               | Thread ID                    | `3132`                                       |
/// | `{eol}`               | End of line                  | `\n` (on non-Windows) or `\r\n` (on Windows) |
/// 
/// [^1]: Patterns related to source location require that feature
///       `source-location` is enabled, otherwise the output is empty.
///
/// [`FullFormatter`]: crate::formatter::FullFormatter
pub use ::spdlog_macros::pattern;

/// A formatter that formats log records according to a specified pattern.
#[derive(Clone)]
pub struct PatternFormatter<P> {
    pattern: P,
}

impl<P> PatternFormatter<P>
where
    P: Pattern,
{
    /// Creates a new `PatternFormatter` object with the given pattern.
    ///
    /// Currently users can only create a `pattern` object at compile-time by
    /// calling [`pattern!`] macro.
    #[must_use]
    pub fn new(pattern: P) -> Self {
        Self { pattern }
    }
}

impl<P> Formatter for PatternFormatter<P>
where
    P: 'static + Clone + Pattern,
{
    fn format(&self, record: &Record, dest: &mut StringBuf) -> crate::Result<FmtExtraInfo> {
        let mut ctx = PatternContext::new(FmtExtraInfoBuilder::default());
        self.pattern.format(record, dest, &mut ctx)?;
        Ok(ctx.fmt_info_builder.build())
    }

    fn clone_box(&self) -> Box<dyn Formatter> {
        Box::new(self.clone())
    }
}

/// Provide context for patterns.
#[derive(Clone, Debug)]
pub struct PatternContext {
    fmt_info_builder: FmtExtraInfoBuilder,
}

impl PatternContext {
    /// Create a new `PatternContext` object.
    #[must_use]
    fn new(fmt_info_builder: FmtExtraInfoBuilder) -> Self {
        Self { fmt_info_builder }
    }

    /// Set the style range of the log message written by the patterns.
    ///
    /// This function is reserved for use by the style range pattern. Other
    /// built-in patterns should not use this function. User-defined
    /// patterns cannot use this function due to type privacy.
    fn set_style_range(&mut self, style_range: Range<usize>) {
        let builder = std::mem::take(&mut self.fmt_info_builder);
        self.fmt_info_builder = builder.style_range(style_range);
    }
}

/// A pattern.
///
/// A pattern is like a formatter, except that multiple patterns can be combined
/// in various ways to create a new pattern. The [`PatternFormatter`] struct
/// provides a [`Formatter`] that formats log records according to a given
/// pattern.
///
/// # Built-in Patterns
///
/// `spdlog` provides a rich set of built-in patterns. See the [`pattern`]
/// macro.
///
/// # Custom Patterns
///
/// There are 2 approaches to create your own pattern:
/// - Define a new type and implements this trait;
/// - Use the [`pattern`] macro to create a pattern from a template string.
pub trait Pattern: Send + Sync {
    /// Format this pattern against the given log record and write the formatted
    /// message into the output buffer.
    ///
    /// **For implementors:** the `ctx` parameter is reserved for future use.
    /// For now, please ignore it.
    fn format(
        &self,
        record: &Record,
        dest: &mut StringBuf,
        ctx: &mut PatternContext,
    ) -> crate::Result<()>;
}

impl Pattern for String {
    fn format(
        &self,
        record: &Record,
        dest: &mut StringBuf,
        ctx: &mut PatternContext,
    ) -> crate::Result<()> {
        <&str as Pattern>::format(&&**self, record, dest, ctx)
    }
}

impl Pattern for str {
    fn format(
        &self,
        _record: &Record,
        dest: &mut StringBuf,
        _ctx: &mut PatternContext,
    ) -> crate::Result<()> {
        dest.write_str(self).map_err(Error::FormatRecord)
    }
}

impl<'a, T> Pattern for &'a T
where
    T: ?Sized + Pattern,
{
    fn format(
        &self,
        record: &Record,
        dest: &mut StringBuf,
        ctx: &mut PatternContext,
    ) -> crate::Result<()> {
        <T as Pattern>::format(*self, record, dest, ctx)
    }
}

impl<'a, T> Pattern for &'a mut T
where
    T: ?Sized + Pattern,
{
    fn format(
        &self,
        record: &Record,
        dest: &mut StringBuf,
        ctx: &mut PatternContext,
    ) -> crate::Result<()> {
        <T as Pattern>::format(*self, record, dest, ctx)
    }
}

impl<T> Pattern for Box<T>
where
    T: ?Sized + Pattern,
{
    fn format(
        &self,
        record: &Record,
        dest: &mut StringBuf,
        ctx: &mut PatternContext,
    ) -> crate::Result<()> {
        <T as Pattern>::format(&**self, record, dest, ctx)
    }
}

impl<T> Pattern for Arc<T>
where
    T: ?Sized + Pattern,
{
    fn format(
        &self,
        record: &Record,
        dest: &mut StringBuf,
        ctx: &mut PatternContext,
    ) -> crate::Result<()> {
        <T as Pattern>::format(&**self, record, dest, ctx)
    }
}

impl<T> Pattern for [T]
where
    T: Pattern,
{
    fn format(
        &self,
        record: &Record,
        dest: &mut StringBuf,
        ctx: &mut PatternContext,
    ) -> crate::Result<()> {
        for p in self {
            <T as Pattern>::format(p, record, dest, ctx)?;
        }
        Ok(())
    }
}

impl<T, const N: usize> Pattern for [T; N]
where
    T: Pattern,
{
    fn format(
        &self,
        record: &Record,
        dest: &mut StringBuf,
        ctx: &mut PatternContext,
    ) -> crate::Result<()> {
        <[T] as Pattern>::format(self, record, dest, ctx)
    }
}

impl<T> Pattern for Vec<T>
where
    T: Pattern,
{
    fn format(
        &self,
        record: &Record,
        dest: &mut StringBuf,
        ctx: &mut PatternContext,
    ) -> crate::Result<()> {
        <[T] as Pattern>::format(self, record, dest, ctx)
    }
}

macro_rules! last {
    ( $a:tt, ) => { $a };
    ( $a:tt, $($rest:tt,)+ ) => { last!($($rest,)+) };
}

macro_rules! tuple_pattern {
    (
        $(
            $Tuple:ident {
                $(
                    ($idx:tt) -> $T:ident
                )+
            }
        )+
    ) => {
        $(
            impl<$($T,)+> Pattern for ($($T,)+)
            where
                $($T : Pattern,)+
                last!($($T,)+) : ?Sized,
            {
                fn format(&self, record: &Record, dest: &mut StringBuf, ctx: &mut PatternContext) -> crate::Result<()> {
                    $(
                        <$T as Pattern>::format(&self.$idx, record, dest, ctx)?;
                    )+
                    Ok(())
                }
            }
        )+
    };
}

impl Pattern for () {
    fn format(
        &self,
        _record: &Record,
        _dest: &mut StringBuf,
        _ctx: &mut PatternContext,
    ) -> crate::Result<()> {
        Ok(())
    }
}

tuple_pattern! {
    Tuple1 {
        (0) -> T0
    }
    Tuple2 {
        (0) -> T0
        (1) -> T1
    }
    Tuple3 {
        (0) -> T0
        (1) -> T1
        (2) -> T2
    }
    Tuple4 {
        (0) -> T0
        (1) -> T1
        (2) -> T2
        (3) -> T3
    }
    Tuple5 {
        (0) -> T0
        (1) -> T1
        (2) -> T2
        (3) -> T3
        (4) -> T4
    }
    Tuple6 {
        (0) -> T0
        (1) -> T1
        (2) -> T2
        (3) -> T3
        (4) -> T4
        (5) -> T5
    }
    Tuple7 {
        (0) -> T0
        (1) -> T1
        (2) -> T2
        (3) -> T3
        (4) -> T4
        (5) -> T5
        (6) -> T6
    }
    Tuple8 {
        (0) -> T0
        (1) -> T1
        (2) -> T2
        (3) -> T3
        (4) -> T4
        (5) -> T5
        (6) -> T6
        (7) -> T7
    }
    Tuple9 {
        (0) -> T0
        (1) -> T1
        (2) -> T2
        (3) -> T3
        (4) -> T4
        (5) -> T5
        (6) -> T6
        (7) -> T7
        (8) -> T8
    }
    Tuple10 {
        (0) -> T0
        (1) -> T1
        (2) -> T2
        (3) -> T3
        (4) -> T4
        (5) -> T5
        (6) -> T6
        (7) -> T7
        (8) -> T8
        (9) -> T9
    }
    Tuple11 {
        (0) -> T0
        (1) -> T1
        (2) -> T2
        (3) -> T3
        (4) -> T4
        (5) -> T5
        (6) -> T6
        (7) -> T7
        (8) -> T8
        (9) -> T9
        (10) -> T10
    }
    Tuple12 {
        (0) -> T0
        (1) -> T1
        (2) -> T2
        (3) -> T3
        (4) -> T4
        (5) -> T5
        (6) -> T6
        (7) -> T7
        (8) -> T8
        (9) -> T9
        (10) -> T10
        (11) -> T11
    }
    Tuple13 {
        (0) -> T0
        (1) -> T1
        (2) -> T2
        (3) -> T3
        (4) -> T4
        (5) -> T5
        (6) -> T6
        (7) -> T7
        (8) -> T8
        (9) -> T9
        (10) -> T10
        (11) -> T11
        (12) -> T12
    }
    Tuple14 {
        (0) -> T0
        (1) -> T1
        (2) -> T2
        (3) -> T3
        (4) -> T4
        (5) -> T5
        (6) -> T6
        (7) -> T7
        (8) -> T8
        (9) -> T9
        (10) -> T10
        (11) -> T11
        (12) -> T12
        (13) -> T13
    }
    Tuple15 {
        (0) -> T0
        (1) -> T1
        (2) -> T2
        (3) -> T3
        (4) -> T4
        (5) -> T5
        (6) -> T6
        (7) -> T7
        (8) -> T8
        (9) -> T9
        (10) -> T10
        (11) -> T11
        (12) -> T12
        (13) -> T13
        (14) -> T14
    }
    Tuple16 {
        (0) -> T0
        (1) -> T1
        (2) -> T2
        (3) -> T3
        (4) -> T4
        (5) -> T5
        (6) -> T6
        (7) -> T7
        (8) -> T8
        (9) -> T9
        (10) -> T10
        (11) -> T11
        (12) -> T12
        (13) -> T13
        (14) -> T14
        (15) -> T15
    }
    Tuple17 {
        (0) -> T0
        (1) -> T1
        (2) -> T2
        (3) -> T3
        (4) -> T4
        (5) -> T5
        (6) -> T6
        (7) -> T7
        (8) -> T8
        (9) -> T9
        (10) -> T10
        (11) -> T11
        (12) -> T12
        (13) -> T13
        (14) -> T14
        (15) -> T15
        (16) -> T16
    }
    Tuple18 {
        (0) -> T0
        (1) -> T1
        (2) -> T2
        (3) -> T3
        (4) -> T4
        (5) -> T5
        (6) -> T6
        (7) -> T7
        (8) -> T8
        (9) -> T9
        (10) -> T10
        (11) -> T11
        (12) -> T12
        (13) -> T13
        (14) -> T14
        (15) -> T15
        (16) -> T16
        (17) -> T17
    }
    Tuple19 {
        (0) -> T0
        (1) -> T1
        (2) -> T2
        (3) -> T3
        (4) -> T4
        (5) -> T5
        (6) -> T6
        (7) -> T7
        (8) -> T8
        (9) -> T9
        (10) -> T10
        (11) -> T11
        (12) -> T12
        (13) -> T13
        (14) -> T14
        (15) -> T15
        (16) -> T16
        (17) -> T17
        (18) -> T18
    }
    Tuple20 {
        (0) -> T0
        (1) -> T1
        (2) -> T2
        (3) -> T3
        (4) -> T4
        (5) -> T5
        (6) -> T6
        (7) -> T7
        (8) -> T8
        (9) -> T9
        (10) -> T10
        (11) -> T11
        (12) -> T12
        (13) -> T13
        (14) -> T14
        (15) -> T15
        (16) -> T16
        (17) -> T17
        (18) -> T18
        (19) -> T19
    }
    Tuple21 {
        (0) -> T0
        (1) -> T1
        (2) -> T2
        (3) -> T3
        (4) -> T4
        (5) -> T5
        (6) -> T6
        (7) -> T7
        (8) -> T8
        (9) -> T9
        (10) -> T10
        (11) -> T11
        (12) -> T12
        (13) -> T13
        (14) -> T14
        (15) -> T15
        (16) -> T16
        (17) -> T17
        (18) -> T18
        (19) -> T19
        (20) -> T20
    }
    Tuple22 {
        (0) -> T0
        (1) -> T1
        (2) -> T2
        (3) -> T3
        (4) -> T4
        (5) -> T5
        (6) -> T6
        (7) -> T7
        (8) -> T8
        (9) -> T9
        (10) -> T10
        (11) -> T11
        (12) -> T12
        (13) -> T13
        (14) -> T14
        (15) -> T15
        (16) -> T16
        (17) -> T17
        (18) -> T18
        (19) -> T19
        (20) -> T20
        (21) -> T21
    }
    Tuple23 {
        (0) -> T0
        (1) -> T1
        (2) -> T2
        (3) -> T3
        (4) -> T4
        (5) -> T5
        (6) -> T6
        (7) -> T7
        (8) -> T8
        (9) -> T9
        (10) -> T10
        (11) -> T11
        (12) -> T12
        (13) -> T13
        (14) -> T14
        (15) -> T15
        (16) -> T16
        (17) -> T17
        (18) -> T18
        (19) -> T19
        (20) -> T20
        (21) -> T21
        (22) -> T22
    }
    Tuple24 {
        (0) -> T0
        (1) -> T1
        (2) -> T2
        (3) -> T3
        (4) -> T4
        (5) -> T5
        (6) -> T6
        (7) -> T7
        (8) -> T8
        (9) -> T9
        (10) -> T10
        (11) -> T11
        (12) -> T12
        (13) -> T13
        (14) -> T14
        (15) -> T15
        (16) -> T16
        (17) -> T17
        (18) -> T18
        (19) -> T19
        (20) -> T20
        (21) -> T21
        (22) -> T22
        (23) -> T23
    }
    Tuple25 {
        (0) -> T0
        (1) -> T1
        (2) -> T2
        (3) -> T3
        (4) -> T4
        (5) -> T5
        (6) -> T6
        (7) -> T7
        (8) -> T8
        (9) -> T9
        (10) -> T10
        (11) -> T11
        (12) -> T12
        (13) -> T13
        (14) -> T14
        (15) -> T15
        (16) -> T16
        (17) -> T17
        (18) -> T18
        (19) -> T19
        (20) -> T20
        (21) -> T21
        (22) -> T22
        (23) -> T23
        (24) -> T24
    }
    Tuple26 {
        (0) -> T0
        (1) -> T1
        (2) -> T2
        (3) -> T3
        (4) -> T4
        (5) -> T5
        (6) -> T6
        (7) -> T7
        (8) -> T8
        (9) -> T9
        (10) -> T10
        (11) -> T11
        (12) -> T12
        (13) -> T13
        (14) -> T14
        (15) -> T15
        (16) -> T16
        (17) -> T17
        (18) -> T18
        (19) -> T19
        (20) -> T20
        (21) -> T21
        (22) -> T22
        (23) -> T23
        (24) -> T24
        (25) -> T25
    }
    Tuple27 {
        (0) -> T0
        (1) -> T1
        (2) -> T2
        (3) -> T3
        (4) -> T4
        (5) -> T5
        (6) -> T6
        (7) -> T7
        (8) -> T8
        (9) -> T9
        (10) -> T10
        (11) -> T11
        (12) -> T12
        (13) -> T13
        (14) -> T14
        (15) -> T15
        (16) -> T16
        (17) -> T17
        (18) -> T18
        (19) -> T19
        (20) -> T20
        (21) -> T21
        (22) -> T22
        (23) -> T23
        (24) -> T24
        (25) -> T25
        (26) -> T26
    }
    Tuple28 {
        (0) -> T0
        (1) -> T1
        (2) -> T2
        (3) -> T3
        (4) -> T4
        (5) -> T5
        (6) -> T6
        (7) -> T7
        (8) -> T8
        (9) -> T9
        (10) -> T10
        (11) -> T11
        (12) -> T12
        (13) -> T13
        (14) -> T14
        (15) -> T15
        (16) -> T16
        (17) -> T17
        (18) -> T18
        (19) -> T19
        (20) -> T20
        (21) -> T21
        (22) -> T22
        (23) -> T23
        (24) -> T24
        (25) -> T25
        (26) -> T26
        (27) -> T27
    }
    Tuple29 {
        (0) -> T0
        (1) -> T1
        (2) -> T2
        (3) -> T3
        (4) -> T4
        (5) -> T5
        (6) -> T6
        (7) -> T7
        (8) -> T8
        (9) -> T9
        (10) -> T10
        (11) -> T11
        (12) -> T12
        (13) -> T13
        (14) -> T14
        (15) -> T15
        (16) -> T16
        (17) -> T17
        (18) -> T18
        (19) -> T19
        (20) -> T20
        (21) -> T21
        (22) -> T22
        (23) -> T23
        (24) -> T24
        (25) -> T25
        (26) -> T26
        (27) -> T27
        (28) -> T28
    }
    Tuple30 {
        (0) -> T0
        (1) -> T1
        (2) -> T2
        (3) -> T3
        (4) -> T4
        (5) -> T5
        (6) -> T6
        (7) -> T7
        (8) -> T8
        (9) -> T9
        (10) -> T10
        (11) -> T11
        (12) -> T12
        (13) -> T13
        (14) -> T14
        (15) -> T15
        (16) -> T16
        (17) -> T17
        (18) -> T18
        (19) -> T19
        (20) -> T20
        (21) -> T21
        (22) -> T22
        (23) -> T23
        (24) -> T24
        (25) -> T25
        (26) -> T26
        (27) -> T27
        (28) -> T28
        (29) -> T29
    }
    Tuple31 {
        (0) -> T0
        (1) -> T1
        (2) -> T2
        (3) -> T3
        (4) -> T4
        (5) -> T5
        (6) -> T6
        (7) -> T7
        (8) -> T8
        (9) -> T9
        (10) -> T10
        (11) -> T11
        (12) -> T12
        (13) -> T13
        (14) -> T14
        (15) -> T15
        (16) -> T16
        (17) -> T17
        (18) -> T18
        (19) -> T19
        (20) -> T20
        (21) -> T21
        (22) -> T22
        (23) -> T23
        (24) -> T24
        (25) -> T25
        (26) -> T26
        (27) -> T27
        (28) -> T28
        (29) -> T29
        (30) -> T30
    }
    Tuple32 {
        (0) -> T0
        (1) -> T1
        (2) -> T2
        (3) -> T3
        (4) -> T4
        (5) -> T5
        (6) -> T6
        (7) -> T7
        (8) -> T8
        (9) -> T9
        (10) -> T10
        (11) -> T11
        (12) -> T12
        (13) -> T13
        (14) -> T14
        (15) -> T15
        (16) -> T16
        (17) -> T17
        (18) -> T18
        (19) -> T19
        (20) -> T20
        (21) -> T21
        (22) -> T22
        (23) -> T23
        (24) -> T24
        (25) -> T25
        (26) -> T26
        (27) -> T27
        (28) -> T28
        (29) -> T29
        (30) -> T30
        (31) -> T31
    }
}

#[cfg(test)]
pub mod tests {
    use super::*;
    use crate::{Level, SourceLocation};

    // We use `get_mock_record` and `test_pattern` in tests/pattern.rs so let's make
    // them pub in test builds.

    #[must_use]
    pub fn get_mock_record() -> Record<'static> {
        Record::builder(Level::Info, "record_payload")
            .logger_name("logger_name")
            .source_location(Some(SourceLocation::__new("module", "file", 10, 20)))
            .build()
    }

    pub fn test_pattern<P, T>(pattern: P, formatted: T, style_range: Option<Range<usize>>)
    where
        P: Pattern,
        T: AsRef<str>,
    {
        let record = get_mock_record();
        let mut output = StringBuf::new();
        let mut ctx = PatternContext::new(FmtExtraInfoBuilder::default());

        let format_result = pattern.format(&record, &mut output, &mut ctx);
        assert!(format_result.is_ok());

        assert_eq!(output.as_str(), formatted.as_ref());

        let fmt_info = ctx.fmt_info_builder.build();
        assert_eq!(fmt_info.style_range(), style_range);
    }

    #[test]
    fn test_string_as_pattern() {
        test_pattern(String::from("literal"), "literal", None);
    }

    #[test]
    fn test_str_as_pattern() {
        test_pattern("literal", "literal", None);
    }

    #[test]
    fn test_pattern_ref_as_pattern() {
        #[allow(clippy::needless_borrow)]
        test_pattern(&String::from("literal"), "literal", None);
    }

    #[test]
    fn test_pattern_mut_as_pattern() {
        #[allow(clippy::needless_borrow)]
        test_pattern(&mut String::from("literal"), "literal", None);
    }

    #[test]
    fn test_box_as_pattern() {
        test_pattern(Box::new(String::from("literal")), "literal", None);
    }

    #[test]
    fn test_arc_as_pattern() {
        test_pattern(Arc::new(String::from("literal")), "literal", None);
    }

    #[test]
    fn test_slice_as_pattern() {
        let pat: &[String] = &[String::from("literal1"), String::from("literal2")];
        test_pattern(pat, "literal1literal2", None);
    }

    #[test]
    fn test_empty_slice_as_pattern() {
        let pat: &[String] = &[];
        test_pattern(pat, "", None);
    }

    #[test]
    fn test_array_as_pattern() {
        let pat: [String; 3] = [
            String::from("literal1"),
            String::from("literal2"),
            String::from("literal3"),
        ];
        test_pattern(pat, "literal1literal2literal3", None);
    }

    #[test]
    fn test_empty_array_as_pattern() {
        let pat: [String; 0] = [];
        test_pattern(pat, "", None);
    }

    #[test]
    fn test_vec_as_pattern() {
        let pat = vec![
            String::from("literal1"),
            String::from("literal2"),
            String::from("literal3"),
        ];
        test_pattern(pat, "literal1literal2literal3", None);
    }

    #[test]
    fn test_empty_vec_as_pattern() {
        let pat: Vec<String> = vec![];
        test_pattern(pat, "", None);
    }

    #[test]
    fn test_tuple_as_pattern() {
        let pat = (
            String::from("literal1"),
            "literal2",
            String::from("literal3"),
        );
        test_pattern(pat, "literal1literal2literal3", None);
    }

    #[test]
    fn test_unit_as_pattern() {
        test_pattern((), "", None);
    }
}