zproto 0.4.2

A library from communicating with Zaber products in Rust.
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
//! Types for checking the contents of an ASCII response.
//!
//! The [`strict`] and [`minimal`] functions define two common sets of response
//! checks. [`strict`] ensures all reply flags are OK and there are never any
//! warnings. [`minimal`] is similar but more relaxed. While it still ensures
//! all reply flags are OK, it only ensures that there are no fault (`F*`) level
//! warning flags.
//!
//! It is also easy to define your own custom response checks. The [`Check`]
//! trait defines the interface all "checkers" must implement. It is
//! implemented for all closures that take a [`Response`]
//! and return a `Result<Response, AsciiCheckError>`. However, you are
//! encouraged to use the [functions](#functions) provided in this module to
//! generate checking functions. They cover many of the common cases, can be
//! combined together, generate useful error messages, and make code much
//! clearer.
//!
//! For instance, to generate a function that checks if a reply has the flag
//! `OK` and no warning flags (the equivalent of the `strict` function) you
//! could use:
//!
//! ```rust
//! # use zproto::ascii::response::{
//! #     Flag,
//! #     Reply,
//! #     check::{all, Check, flag_is, warning_is_none},
//! # };
//! # fn wrapper() -> impl Check<Reply> {
//! all((
//!    flag_is(Flag::Ok),
//!    warning_is_none(),
//! ))
//! # }
//! ```
//!
//! What each part does should hopefully be self explanatory from the function
//! names:
//!   * [`all`] checks that all of the checks passed to it pass (notice that they
//!     are enclosed in a [`tuple`])
//!   * [`flag_is`] checks that the reply flag on the [`Reply`] is the specified
//!     value
//!   * [`warning_is_none`] checks that the warning is `--`.
//!
//! There are also the `status_*`, `warning_*`, `flag_*`, or [`parsed_data_is`]
//! functions to generate functions to check a response's status, warnings, reply
//! flags, and data, respectively. If the validation logic for a response is more
//! complex, the [`predicate`] function allows you to validate responses using
//! a closure that simply returns a `bool`.

use crate::ascii::response::{
	AnyResponse, Flag, Kind, Reply, Response, ResponseWithStatus, ResponseWithWarning,
	SpecificResponse, Status, Target, Warning,
};
#[allow(clippy::wildcard_imports)]
use crate::error::*;

/// A trait for checking the contents of a response.
///
/// See the [`check`](self) module level documentation for more information about this trait.
pub trait Check<R: Response>: private::Sealed<R> {
	/// Check the contents of a response.
	///
	/// If the contents of the response are considered valid, the response should be returned.
	/// Otherwise return the response as a member in the error.
	fn check(&self, response: R) -> Result<R, AsciiCheckError<R>>;
}

impl<R: Response, F: Fn(R) -> Result<R, AsciiCheckError<R>>> Check<R> for F {
	fn check(&self, response: R) -> Result<R, AsciiCheckError<R>> {
		(self)(response)
	}
}

impl<R: Response> Check<R> for &dyn Check<R> {
	fn check(&self, response: R) -> Result<R, AsciiCheckError<R>> {
		(*self).check(response)
	}
}

/// A helper type for converting any type that implements `Check<R: Response>`
/// to a new type that implements `Check<AnyResponse>`.
///
/// Users shouldn't need to use this directly in most cases.
#[derive(Debug)]
pub struct AnyResponseCheck<K, R>(K, std::marker::PhantomData<R>);

impl<K, R> Check<AnyResponse> for AnyResponseCheck<K, R>
where
	K: Check<R>,
	R: SpecificResponse,
{
	fn check(
		&self,
		any_response: AnyResponse,
	) -> Result<AnyResponse, AsciiCheckError<AnyResponse>> {
		match R::try_from(any_response) {
			Ok(response) => self.0.check(response).map(Into::into).map_err(Into::into),
			Err(any_response) => Ok(any_response),
		}
	}
}

impl<K> Check<AnyResponse> for AnyResponseCheck<K, AnyResponse>
where
	K: Check<AnyResponse>,
{
	fn check(
		&self,
		any_response: AnyResponse,
	) -> Result<AnyResponse, AsciiCheckError<AnyResponse>> {
		self.0.check(any_response)
	}
}

impl<K, R> From<K> for AnyResponseCheck<K, R>
where
	R: Response,
	K: Check<R>,
{
	fn from(other: K) -> AnyResponseCheck<K, R> {
		AnyResponseCheck(other, std::marker::PhantomData)
	}
}

mod private {
	#[allow(clippy::wildcard_imports)]
	use super::*;
	pub trait Sealed<R: Response> {}

	impl<R: Response> Sealed<R> for &dyn Check<R> {}
	impl<R: Response, F: Fn(R) -> Result<R, AsciiCheckError<R>>> Sealed<R> for F {}
	impl<K: Check<R>, R: Response> Sealed<AnyResponse> for AnyResponseCheck<K, R> {}
}

/// A response whose contents has not been checked.
#[derive(Debug)]
#[repr(transparent)]
#[must_use]
pub struct NotChecked<R>(R);

impl<R: Response> NotChecked<R> {
	pub(crate) fn new(response: R) -> Self {
		NotChecked(response)
	}

	pub(crate) fn into_inner(self) -> R {
		self.0
	}

	/// Return the inner response if the `checker` passes, otherwise an error is returned.
	pub fn check(self, checker: impl Check<R>) -> Result<R, AsciiCheckError<R>> {
		checker.check(self.0)
	}

	/// Return the inner response if the [`minimal`] check passes, otherwise an error is returned.
	pub fn check_minimal(self) -> Result<R, AsciiCheckError<R>> {
		minimal().check(self.0)
	}

	/// Return the inner response if the [`strict`] check passes, otherwise an error is returned.
	pub fn check_strict(self) -> Result<R, AsciiCheckError<R>> {
		strict().check(self.0)
	}

	/// Return the target of the response.
	pub fn target(&self) -> Target {
		self.0.target()
	}

	/// Return the message ID of the response, if any.
	pub fn id(&self) -> Option<u8> {
		self.0.id()
	}
}

impl NotChecked<Reply> {
	/// Return the inner [`Reply`] if the flag is `OK`. Otherwise an error is returned.
	pub fn flag_ok(self) -> Result<Reply, AsciiCheckError<Reply>> {
		flag_ok().check(self.0)
	}

	/// Return the inner [`Reply`] if the flag is `OK` and the `checker` passes. Otherwise an error is returned.
	pub fn flag_ok_and(self, checker: impl Check<Reply>) -> Result<Reply, AsciiCheckError<Reply>> {
		flag_ok_and(checker).check(self.0)
	}
}

impl NotChecked<AnyResponse> {
	/// Return the kind of response.
	pub fn kind(&self) -> Kind {
		self.0.kind()
	}
}

/// Return a check that verifies the response's [`Warning`] matches the specified warning.
///
/// ## Example
/// ```rust
/// # use zproto::ascii::response::{check::{Check, warning_is}, Warning, Reply};
/// # fn wrapper() -> impl Check<Reply> {
/// warning_is("WR")
/// # }
/// ```
pub fn warning_is<R, W>(warning: W) -> impl Check<R>
where
	R: ResponseWithWarning,
	Warning: std::convert::TryFrom<W>,
{
	use std::convert::TryFrom as _;
	let warning = Warning::try_from(warning).unwrap_or_else(|_| panic!("Invalid warning"));
	move |response: R| {
		if response.warning() == warning {
			Ok(response)
		} else {
			Err(
				AsciiCheckWarningError::new(format!("expected {warning} warning flag"), response)
					.into(),
			)
		}
	}
}

/// Return a check that verifies the response's [`Warning`] is in the specified list.
///
/// The list can be a slice, array, or tuple of types that are comparable to a [`Warning`].
///
/// ## Example
/// ```rust
/// # use zproto::ascii::response::{check::{Check, warning_in}, Warning, Reply};
/// # fn wrapper() -> impl Check<Reply> {
/// warning_in(["WR", "WH"])
/// # }
/// ```
pub fn warning_in<R: ResponseWithWarning, L: WarningList>(warnings: L) -> impl Check<R> {
	move |response: R| {
		if warnings.contains(response.warning()) {
			Ok(response)
		} else {
			use std::fmt::Write as _;
			let mut msg = String::new();
			msg.write_str("expected one of ").unwrap();
			warnings.write_fmt_to_str(&mut msg);
			msg.write_str(" warning flag(s)").unwrap();
			Err(AsciiCheckWarningError::new(msg, response).into())
		}
	}
}

/// Return a check that verifies the response's [`Warning`] is below the fault
/// level, i.e., `--`, `N*`, or `W*`.
pub fn warning_below_fault<R: ResponseWithWarning>() -> impl Check<R> {
	|response: R| {
		if response.warning().is_fault() {
			Err(
				AsciiCheckWarningError::new("expected warning below fault (F) level", response)
					.into(),
			)
		} else {
			Ok(response)
		}
	}
}

/// Return a check that verifies the response's [`Warning`] is below the
/// warning level, i.e., `--` or `N*`.
pub fn warning_below_warning<R: ResponseWithWarning>() -> impl Check<R> {
	|response: R| {
		let warning = response.warning();
		if !warning.is_fault() && !warning.is_warning() {
			Ok(response)
		} else {
			Err(
				AsciiCheckWarningError::new("expected warning below warning (W) level", response)
					.into(),
			)
		}
	}
}

/// Return a check that verifies the response's [`Warning`] is `--`.
pub fn warning_is_none<R: ResponseWithWarning>() -> impl Check<R> {
	|response: R| {
		if response.warning().is_none() {
			Ok(response)
		} else {
			Err(AsciiCheckWarningError::new("expected no warning (--)", response).into())
		}
	}
}

/// Return a check that verifies the response's [`Status`] matches the specified status.
///
/// ## Example
/// ```rust
/// # use zproto::ascii::response::{check::{Check, status_is}, Status, Reply};
/// # fn wrapper() -> impl Check<Reply> {
/// status_is(Status::Idle)
/// # }
/// ```
pub fn status_is<R: ResponseWithStatus>(status: Status) -> impl Check<R> {
	move |response: R| {
		if response.status() == status {
			Ok(response)
		} else {
			Err(AsciiCheckStatusError::new(status, response).into())
		}
	}
}

/// Return a check that verifies the response's [`Status`] is `IDLE`.
pub fn status_idle<R: ResponseWithStatus>() -> impl Check<R> {
	status_is(Status::Idle)
}

/// Return a check that verifies the response's [`Status`] is `BUSY`.
pub fn status_busy<R: ResponseWithStatus>() -> impl Check<R> {
	status_is(Status::Busy)
}

/// Return a check that verifies the response's [`Flag`] matches the specified flag.
///
/// ## Example
/// ```rust
/// # use zproto::ascii::response::{check::{Check, flag_is}, Flag, Reply};
/// # fn wrapper() -> impl Check<Reply> {
/// flag_is(Flag::Ok)
/// # }
/// ```
pub fn flag_is(flag: Flag) -> impl Check<Reply> {
	move |response: Reply| {
		if response.flag() == flag {
			Ok(response)
		} else {
			Err(AsciiCheckFlagError::new(flag, response).into())
		}
	}
}

/// Return a check that verifies the response's [`Flag`] is `OK`.
pub fn flag_ok() -> impl Check<Reply> {
	flag_is(Flag::Ok)
}

/// Return a check that verifies the response's [`Flag`] is `RJ`.
pub fn flag_rj() -> impl Check<Reply> {
	flag_is(Flag::Rj)
}

/// Return a check that verifies the response's [`Flag`] is `OK` and that the
/// provided `check` also passes.
///
/// ## Example
/// ```rust
/// # use zproto::ascii::response::{check::{Check, flag_ok_and, warning_is}, Flag, Reply};
/// # fn wrapper() -> impl Check<Reply> {
/// flag_ok_and(warning_is("WR"))
/// # }
/// ```
pub fn flag_ok_and(check: impl Check<Reply>) -> impl Check<Reply> {
	all((flag_ok(), check))
}

/// Return a check that verifies the parsed response data matches the specified value.
///
/// If the response data cannot be parsed as the specified value or value does
/// not match an error is returned.
///
/// ## Example
/// ```rust
/// # use zproto::ascii::response::{check::{Check, parsed_data_is}, Reply};
/// # fn wrapper() -> impl Check<Reply> {
/// parsed_data_is(256)
/// # }
/// ```
pub fn parsed_data_is<
	R: Response,
	T: std::str::FromStr + std::cmp::PartialEq<T> + std::fmt::Debug,
>(
	value: T,
) -> impl Check<R> {
	move |response: R| {
		if let Ok(parsed) = response.data().parse::<T>() {
			if parsed == value {
				Ok(response)
			} else {
				Err(AsciiCheckDataError::new(format!("expected data {value:?}"), response).into())
			}
		} else {
			Err(AsciiCheckDataError::new("could not parse data as expected type", response).into())
		}
	}
}

/// Return a check that will validate a response against all the specified checks.
///
/// Once one check fails, no further checks are run. Note that the checks must
/// be passed as members of a [`tuple`].
///
/// ## Example
/// ```rust
/// # use zproto::ascii::response::{check::*, Flag, Reply};
/// # fn wrapper() -> impl Check<Reply> {
/// all((
///     flag_is(Flag::Ok),
///     warning_in(("WR", "WH"))
/// ))
/// # }
/// ```
pub fn all<R: Response, C: CheckAll<R>>(checks: C) -> impl Check<R> {
	move |response: R| checks.check(response)
}

/// Return a strict check for the specified message type.
///
/// For [`Reply`] this is equivalent to
/// ```rust
/// # use zproto::ascii::response::{check::*, *};
/// # fn wrapper() -> impl Check<Reply> {
/// flag_ok_and(warning_is_none())
/// # }
/// ```
///
/// For [`Alert`] this is equivalent to
/// ```rust
/// # use zproto::ascii::response::{check::*, *};
/// # fn wrapper() -> impl Check<Alert> {
/// warning_is_none()
/// # }
/// ```
///
/// For [`Info`] no validation is done.
///
/// For [`AnyResponse`], one of the above checks is
/// chosen at runtime based on the kind of response.
///
/// [`Alert`]: crate::ascii::response::Alert
/// [`Info`]: crate::ascii::response::Info
pub fn strict<R: Response>() -> impl Check<R> {
	R::strict()
}

/// Return a check that performs minimal checks of the specified message type
/// while still checking for major problems with devices. In most cases, more
/// rigorous checks are probably warranted.
///
/// For [`Reply`] this is equivalent to
/// ```rust
/// # use zproto::ascii::response::{check::*, *};
/// # fn wrapper() -> impl Check<Reply> {
/// flag_ok_and(warning_below_fault())
/// # }
/// ```
///
/// For [`Alert`] this is equivalent to
/// ```rust
/// # use zproto::ascii::response::{check::*, *};
/// # fn wrapper() -> impl Check<Alert> {
/// warning_below_fault()
/// # }
/// ```
///
/// For [`Info`] no validation is done.
///
/// For [`AnyResponse`], one of the above checks is
///
/// [`Alert`]: crate::ascii::response::Alert
/// [`Info`]: crate::ascii::response::Info
/// chosen at runtime based on the kind of response.
pub fn minimal<R: Response>() -> impl Check<R> {
	R::minimal()
}

/// Return a check that does not validate the response.
pub fn unchecked<R: Response>() -> impl Check<R> {
	|response: R| Ok(response)
}

/// Return a check that validates a response with the given `predicate`.
///
/// The response is considered valid if and only if `predicate` returns `true`.
///
/// ## Example
/// ```rust
/// # use zproto::ascii::response::{check::{Check, predicate}, Reply};
/// # fn wrapper() -> impl Check<Reply> {
/// let expected_value = "256";
/// let check = predicate(move |reply: &Reply| {
///     reply.data() == expected_value
/// });
/// # check
/// # }
/// ```
pub fn predicate<R: Response, P: Fn(&R) -> bool>(predicate: P) -> impl Check<R> {
	move |response: R| {
		if predicate(&response) {
			Ok(response)
		} else {
			Err(AsciiCheckCustomError::unknown(response).into())
		}
	}
}

/// A helper trait for the [`all`] function.
///
/// It is implemented on tuples up to 5 elements in length.
pub trait CheckAll<R: Response> {
	/// Check the contents of a response against all member checks
	///
	/// If the contents of the response are considered valid by all member checks, the response should be returned.
	/// Otherwise return the response as a member in the error.
	fn check(&self, response: R) -> Result<R, AsciiCheckError<R>>;
}

impl<R: Response, A: Check<R>> CheckAll<R> for (A,) {
	fn check(&self, response: R) -> Result<R, AsciiCheckError<R>> {
		self.0.check(response)
	}
}

impl<R: Response, A: Check<R>, B: Check<R>> CheckAll<R> for (A, B) {
	fn check(&self, response: R) -> Result<R, AsciiCheckError<R>> {
		let response = self.0.check(response)?;
		let response = self.1.check(response)?;
		Ok(response)
	}
}

impl<R: Response, A: Check<R>, B: Check<R>, C: Check<R>> CheckAll<R> for (A, B, C) {
	fn check(&self, response: R) -> Result<R, AsciiCheckError<R>> {
		let response = self.0.check(response)?;
		let response = self.1.check(response)?;
		let response = self.2.check(response)?;
		Ok(response)
	}
}

impl<R: Response, A: Check<R>, B: Check<R>, C: Check<R>, D: Check<R>> CheckAll<R> for (A, B, C, D) {
	fn check(&self, response: R) -> Result<R, AsciiCheckError<R>> {
		let response = self.0.check(response)?;
		let response = self.1.check(response)?;
		let response = self.2.check(response)?;
		let response = self.3.check(response)?;
		Ok(response)
	}
}

impl<R: Response, A: Check<R>, B: Check<R>, C: Check<R>, D: Check<R>, E: Check<R>> CheckAll<R>
	for (A, B, C, D, E)
{
	fn check(&self, response: R) -> Result<R, AsciiCheckError<R>> {
		let response = self.0.check(response)?;
		let response = self.1.check(response)?;
		let response = self.2.check(response)?;
		let response = self.3.check(response)?;
		let response = self.4.check(response)?;
		Ok(response)
	}
}

/// A helper trait for the [`warning_in`] function.
///
/// It is implemented for arrays and slices of any type that can be compared to a [`Warning`].
/// It is also implemented for tuples up to 5 elements in length and containing types that can be compared to a [`Warning`].
pub trait WarningList {
	/// Returns whether the specified warning is present in the list
	fn contains(&self, warning: Warning) -> bool;
	/// Write the contents of the list to the string `s`.
	fn write_fmt_to_str(&self, s: &mut String);
}

impl<A> WarningList for (A,)
where
	A: AsRef<[u8]>,
{
	fn contains(&self, warning: Warning) -> bool {
		warning == self.0
	}
	fn write_fmt_to_str(&self, s: &mut String) {
		use std::fmt::Write as _;
		s.write_fmt(format_args!("{}", String::from_utf8_lossy(self.0.as_ref())))
			.unwrap();
	}
}

impl<A, B> WarningList for (A, B)
where
	A: AsRef<[u8]>,
	B: AsRef<[u8]>,
{
	fn contains(&self, warning: Warning) -> bool {
		warning == self.0 || warning == self.1
	}
	fn write_fmt_to_str(&self, s: &mut String) {
		use std::fmt::Write as _;
		s.write_fmt(format_args!(
			"{} or {}",
			String::from_utf8_lossy(self.0.as_ref()),
			String::from_utf8_lossy(self.1.as_ref())
		))
		.unwrap();
	}
}

impl<A, B, C> WarningList for (A, B, C)
where
	A: AsRef<[u8]>,
	B: AsRef<[u8]>,
	C: AsRef<[u8]>,
{
	fn contains(&self, warning: Warning) -> bool {
		warning == self.0 || warning == self.1 || warning == self.2
	}
	fn write_fmt_to_str(&self, s: &mut String) {
		use std::fmt::Write as _;
		s.write_fmt(format_args!(
			"{}, {}, or {}",
			String::from_utf8_lossy(self.0.as_ref()),
			String::from_utf8_lossy(self.1.as_ref()),
			String::from_utf8_lossy(self.2.as_ref())
		))
		.unwrap();
	}
}

impl<A, B, C, D> WarningList for (A, B, C, D)
where
	A: AsRef<[u8]>,
	B: AsRef<[u8]>,
	C: AsRef<[u8]>,
	D: AsRef<[u8]>,
{
	fn contains(&self, warning: Warning) -> bool {
		warning == self.0 || warning == self.1 || warning == self.2 || warning == self.3
	}
	fn write_fmt_to_str(&self, s: &mut String) {
		use std::fmt::Write as _;
		s.write_fmt(format_args!(
			"{}, {}, {}, or {}",
			String::from_utf8_lossy(self.0.as_ref()),
			String::from_utf8_lossy(self.1.as_ref()),
			String::from_utf8_lossy(self.2.as_ref()),
			String::from_utf8_lossy(self.3.as_ref())
		))
		.unwrap();
	}
}

impl<A, B, C, D, E> WarningList for (A, B, C, D, E)
where
	A: AsRef<[u8]>,
	B: AsRef<[u8]>,
	C: AsRef<[u8]>,
	D: AsRef<[u8]>,
	E: AsRef<[u8]>,
{
	fn contains(&self, warning: Warning) -> bool {
		warning == self.0
			|| warning == self.1
			|| warning == self.2
			|| warning == self.3
			|| warning == self.4
	}
	fn write_fmt_to_str(&self, s: &mut String) {
		use std::fmt::Write as _;
		s.write_fmt(format_args!(
			"{}, {}, {}, {}, or {}",
			String::from_utf8_lossy(self.0.as_ref()),
			String::from_utf8_lossy(self.1.as_ref()),
			String::from_utf8_lossy(self.2.as_ref()),
			String::from_utf8_lossy(self.3.as_ref()),
			String::from_utf8_lossy(self.4.as_ref())
		))
		.unwrap();
	}
}

impl<A> WarningList for [A]
where
	A: AsRef<[u8]>,
{
	fn contains(&self, warning: Warning) -> bool {
		for item in self {
			if warning == *item {
				return true;
			}
		}
		false
	}
	fn write_fmt_to_str(&self, s: &mut String) {
		use std::fmt::Write as _;
		for (i, item) in self.iter().enumerate() {
			let prefix = match i {
				0 => "",
				i if i == self.len() - 1 => ", or ",
				_ => ", ",
			};
			s.write_fmt(format_args!(
				"{}{}",
				prefix,
				String::from_utf8_lossy(item.as_ref())
			))
			.unwrap();
		}
	}
}

impl<A, const SIZE: usize> WarningList for [A; SIZE]
where
	A: AsRef<[u8]>,
{
	fn contains(&self, warning: Warning) -> bool {
		for item in self {
			if warning == *item {
				return true;
			}
		}
		false
	}
	fn write_fmt_to_str(&self, s: &mut String) {
		use std::fmt::Write as _;
		for (i, item) in self.iter().enumerate() {
			let prefix = match i {
				0 => "",
				i if i == self.len() - 1 => ", or ",
				_ => ", ",
			};
			s.write_fmt(format_args!(
				"{}{}",
				prefix,
				String::from_utf8_lossy(item.as_ref())
			))
			.unwrap();
		}
	}
}

impl<T: WarningList> WarningList for &T {
	fn contains(&self, warning: Warning) -> bool {
		(*self).contains(warning)
	}
	fn write_fmt_to_str(&self, s: &mut String) {
		(*self).write_fmt_to_str(s);
	}
}

#[cfg(test)]
mod test {
	use super::*;
	use crate::ascii::{packet::Packet, response::Reply};

	#[test]
	fn check_reply() {
		struct Case<'a> {
			reply: Reply,
			checker: &'a dyn Check<Reply>,
			expected: Result<(), AsciiCheckError<Reply>>,
		}

		let ok_busy_reply =
			Reply::try_from_packet(&Packet::new(b"@01 1 12 OK BUSY -- 0\r\n").unwrap()).unwrap();
		let ok_idle_reply =
			Reply::try_from_packet(&Packet::new(b"@01 1 12 OK IDLE -- 0\r\n").unwrap()).unwrap();
		let ok_idle_ff_reply =
			Reply::try_from_packet(&Packet::new(b"@01 1 12 OK IDLE FF 0\r\n").unwrap()).unwrap();
		let ok_idle_wh_reply =
			Reply::try_from_packet(&Packet::new(b"@01 1 12 OK IDLE WH 0\r\n").unwrap()).unwrap();
		let ok_idle_ni_reply =
			Reply::try_from_packet(&Packet::new(b"@01 1 12 OK IDLE NI 0\r\n").unwrap()).unwrap();
		let rj_idle_reply =
			Reply::try_from_packet(&Packet::new(b"@01 1 12 RJ IDLE -- BADCOMMAND\r\n").unwrap())
				.unwrap();

		let predicate_check = predicate(|reply: &Reply| {
			if reply.flag() == Flag::Ok {
				reply.status() == Status::Idle
			} else {
				reply.data() == "0"
			}
		});

		let cases = &[
			Case {
				reply: ok_busy_reply.clone(),
				checker: &flag_ok(),
				expected: Ok(()),
			},
			Case {
				reply: ok_busy_reply.clone(),
				checker: &flag_is(Flag::Rj),
				expected: Err(AsciiCheckFlagError::new(Flag::Rj, ok_busy_reply.clone()).into()),
			},
			Case {
				reply: ok_busy_reply.clone(),
				checker: &flag_rj(),
				expected: Err(AsciiCheckFlagError::new(Flag::Rj, ok_busy_reply.clone()).into()),
			},
			Case {
				reply: ok_busy_reply.clone(),
				checker: &flag_ok_and(status_is(Status::Busy)),
				expected: Ok(()),
			},
			Case {
				reply: ok_busy_reply.clone(),
				checker: &flag_ok_and(status_is(Status::Idle)),
				expected: Err(
					AsciiCheckStatusError::new(Status::Idle, ok_busy_reply.clone()).into(),
				),
			},
			Case {
				reply: ok_busy_reply.clone(),
				checker: &unchecked(),
				expected: Ok(()),
			},
			Case {
				reply: rj_idle_reply.clone(),
				checker: &unchecked(),
				expected: Ok(()),
			},
			Case {
				reply: ok_idle_reply.clone(),
				checker: &strict(),
				expected: Ok(()),
			},
			Case {
				reply: ok_busy_reply.clone(),
				checker: &strict(),
				expected: Ok(()),
			},
			Case {
				reply: ok_idle_ni_reply.clone(),
				checker: &strict(),
				expected: Err(AsciiCheckWarningError::new(
					"expected no warning (--)",
					ok_idle_ni_reply.clone(),
				)
				.into()),
			},
			Case {
				reply: rj_idle_reply.clone(),
				checker: &strict(),
				expected: Err(AsciiCheckFlagError::new(Flag::Ok, rj_idle_reply.clone()).into()),
			},
			Case {
				reply: ok_idle_reply.clone(),
				checker: &minimal(),
				expected: Ok(()),
			},
			Case {
				reply: ok_busy_reply.clone(),
				checker: &minimal(),
				expected: Ok(()),
			},
			Case {
				reply: ok_idle_ni_reply.clone(),
				checker: &minimal(),
				expected: Ok(()),
			},
			Case {
				reply: ok_idle_wh_reply.clone(),
				checker: &minimal(),
				expected: Ok(()),
			},
			Case {
				reply: ok_idle_ff_reply.clone(),
				checker: &minimal(),
				expected: Err(AsciiCheckWarningError::new(
					"expected warning below fault (F) level",
					ok_idle_ff_reply.clone(),
				)
				.into()),
			},
			Case {
				reply: rj_idle_reply.clone(),
				checker: &minimal(),
				expected: Err(AsciiCheckFlagError::new(Flag::Ok, rj_idle_reply).into()),
			},
			Case {
				reply: ok_busy_reply.clone(),
				checker: &warning_is("WR"),
				expected: Err(AsciiCheckWarningError::new(
					"expected WR warning flag",
					ok_busy_reply.clone(),
				)
				.into()),
			},
			Case {
				reply: ok_idle_wh_reply.clone(),
				checker: &warning_is("WH"),
				expected: Ok(()),
			},
			Case {
				reply: ok_busy_reply.clone(),
				checker: &warning_is_none(),
				expected: Ok(()),
			},
			Case {
				reply: ok_busy_reply.clone(),
				checker: &warning_in(("WR", Warning::NONE)),
				expected: Ok(()),
			},
			Case {
				reply: ok_idle_ff_reply.clone(),
				checker: &warning_in(("WR", Warning::NONE)),
				expected: Err(AsciiCheckWarningError::new(
					"expected one of WR or -- warning flag(s)",
					ok_idle_ff_reply.clone(),
				)
				.into()),
			},
			Case {
				reply: ok_idle_ff_reply.clone(),
				checker: &warning_below_fault(),
				expected: Err(AsciiCheckWarningError::new(
					"expected warning below fault (F) level",
					ok_idle_ff_reply,
				)
				.into()),
			},
			Case {
				reply: ok_idle_wh_reply.clone(),
				checker: &warning_below_fault(),
				expected: Ok(()),
			},
			Case {
				reply: ok_idle_wh_reply.clone(),
				checker: &warning_below_warning(),
				expected: Err(AsciiCheckWarningError::new(
					"expected warning below warning (W) level",
					ok_idle_wh_reply,
				)
				.into()),
			},
			Case {
				reply: ok_idle_ni_reply,
				checker: &warning_below_warning(),
				expected: Ok(()),
			},
			Case {
				reply: ok_busy_reply.clone(),
				checker: &all((
					flag_is(Flag::Ok),
					warning_in(&["--"]),
					status_is(Status::Busy),
				)),
				expected: Ok(()),
			},
			Case {
				reply: ok_busy_reply.clone(),
				checker: &parsed_data_is(0),
				expected: Ok(()),
			},
			Case {
				reply: ok_busy_reply.clone(),
				checker: &parsed_data_is(1),
				expected: Err(
					AsciiCheckDataError::new("expected data 1", ok_busy_reply.clone()).into(),
				),
			},
			Case {
				reply: ok_busy_reply.clone(),
				checker: &parsed_data_is(std::num::NonZeroIsize::new(1).unwrap()),
				expected: Err(AsciiCheckDataError::new(
					"could not parse data as expected type",
					ok_busy_reply.clone(),
				)
				.into()),
			},
			Case {
				reply: ok_busy_reply.clone(),
				checker: &predicate_check,
				expected: Err(AsciiCheckCustomError::new("invalid response", ok_busy_reply).into()),
			},
			Case {
				reply: ok_idle_reply,
				checker: &predicate_check,
				expected: Ok(()),
			},
		];

		for (i, case) in cases.iter().enumerate() {
			println!("case {}: {}", i, case.reply);
			let actual = case.checker.check(case.reply.clone());
			match &case.expected {
				Ok(_) => assert!(actual.is_ok(), "unexpected error: {actual:?}"),
				Err(expected_err) => {
					let actual_err = actual.unwrap_err();
					assert_eq!(*expected_err, actual_err);
				}
			}
		}
	}

	#[test]
	fn test_warning_list() {
		// Make sure a warning list can be created from all the relevant types
		warning_in::<Reply, _>((
			Warning::from(b"FF"),
			"WR",
			b"RR",
			"--".to_string(),
			b"--".to_vec(),
		));
	}
}