nanoflash 0.1.0

Lay out the flash of ESP32 and Arduino boards and write firmware to them through their bootloaders, natively or in the browser over Web Serial.
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
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
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
//! The errors of connecting to a board and writing it, and their classes.

use alloc::string::String;
use alloc::vec::Vec;
use core::fmt;

use serde::Serialize;

use crate::layout::LayoutError;
use crate::manifest::{ManifestError, Protocol};
use crate::table::TableError;
use crate::transport::{TransportError, UsbIdentity};

/// What can go wrong while connecting to a board and writing it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum Error {
    /// The serial port failed.
    Transport {
        /// What failed.
        error: TransportError,
        /// What was being done, such as `writing "application" at 0x20000`, when it is known.
        during: Option<String>,
    },
    /// The board did not answer a command.
    NoResponse {
        /// The command, such as `GET_SECURITY_INFO`.
        command: &'static str,
    },
    /// The board answered no SYNC after any reset.
    NoSync {
        /// The number of resets tried.
        attempts: u8,
    },
    /// The boot log shows the chip started in another mode than download mode.
    NotInDownloadMode {
        /// The boot mode from the log, such as `0x8`.
        boot_mode: String,
    },
    /// The ROM loader refused a command.
    Rom {
        /// The command.
        command: &'static str,
        /// The error code of the ROM loader.
        code: u8,
    },
    /// The board answered a command with something that cannot be its answer.
    InvalidResponse {
        /// The command.
        command: &'static str,
        /// What is wrong with the answer.
        message: String,
    },
    /// The chip could not be identified.
    UnknownChip {
        /// What was read, such as `magic 0x12345678`.
        detail: String,
    },
    /// The chip was identified, and nanoflash does not support it.
    UnsupportedChip {
        /// The chip, such as `esp8266`.
        chip: String,
    },
    /// The reset sequence does not apply to the protocol.
    UnsupportedReset {
        /// The protocol of the board.
        protocol: Protocol,
        /// The reset sequence, such as `touch-1200`.
        reset: String,
    },
    /// A value does not fit what the protocol can carry.
    OutOfRange {
        /// What the value is, such as `application offset`.
        what: String,
        /// The value.
        value: u64,
    },
    /// The manifest could not be read.
    Manifest {
        /// What is wrong with it.
        error: ManifestError,
    },
    /// The layout of a board has errors.
    Layout {
        /// Every problem found.
        errors: Vec<LayoutError>,
    },
    /// The layout file of a board could not be read or parsed.
    LayoutFile {
        /// The path, as written in the manifest.
        path: String,
        /// What went wrong.
        message: String,
    },
    /// The partition table cannot be written for the layout.
    Table {
        /// What the writer cannot express.
        error: TableError,
    },
    /// An image file could not be read.
    ImageSource {
        /// The path, as written in the manifest.
        path: String,
        /// What went wrong.
        message: String,
    },
    /// An Intel HEX image is invalid.
    IntelHex {
        /// The path, as written in the manifest, or the file given to the command line.
        path: String,
        /// The 1-based line of the problem, when it is on one line.
        line: Option<usize>,
        /// What is wrong.
        message: String,
    },
    /// A valid Intel HEX image does not start where it is written: its addresses are those of
    /// the memory map, the base address of the flash plus the offset it is written at.
    MisplacedIntelHex {
        /// The path, as written in the manifest, or the file given to the command line.
        path: String,
        /// The address of its first byte.
        start: u64,
        /// The address it is written at: the base address of the flash plus its offset.
        expected: u64,
        /// The base address of the flash of the layout; 0 without a layout.
        base_address: u64,
        /// The partition it is written to, when it names one.
        partition: Option<String>,
    },
    /// An image is an ELF file, and this build of nanoflash does not read ELF files (the `elf`
    /// feature).
    ElfNotEnabled {
        /// The path, as written in the manifest, or the file given to the command line.
        path: String,
    },
    /// An ELF image cannot be flashed.
    #[cfg(feature = "elf")]
    Elf {
        /// The path, as written in the manifest, or the file given to the command line.
        path: String,
        /// What is wrong.
        message: String,
    },
    /// A valid ELF image does not start where it is written: its addresses are those of the
    /// memory map, the base address of the flash plus the offset it is written at.
    #[cfg(feature = "elf")]
    MisplacedElf {
        /// The path, as written in the manifest, or the file given to the command line.
        path: String,
        /// The address of its first byte.
        start: u64,
        /// The address it is written at: the base address of the flash plus its offset.
        expected: u64,
        /// The base address of the flash of the layout; 0 without a layout.
        base_address: u64,
        /// The partition it is written to, when it names one.
        partition: Option<String>,
    },
    /// The image source could not build the Espressif application image of an ELF file.
    #[cfg(feature = "elf")]
    ApplicationImage {
        /// The path, as written in the manifest, or the file given to the command line.
        path: String,
        /// The partition the image is written to, when it names one.
        partition: Option<String>,
        /// Why the image could not be built, as the image source says.
        reason: String,
    },
    /// An ELF image is written where the Espressif bootloader does not boot an application from:
    /// a partition that is not a `firmware` or `update` partition, or an offset that starts no
    /// partition of the layout.
    #[cfg(feature = "elf")]
    ElfNotAnApplication {
        /// The path, as written in the manifest, or the file given to the command line.
        path: String,
        /// The partition it is written to, when it names one.
        partition: Option<String>,
        /// The flash offset it is written at.
        offset: u64,
    },
    /// The Espressif application image of an ELF file is written at an offset that is not a
    /// page of the bootloader (a multiple of 0x10000), or that is below the first page.
    #[cfg(feature = "elf")]
    MisalignedApplicationImage {
        /// The path, as written in the manifest, or the file given to the command line.
        path: String,
        /// The partition it is written to, when it names one.
        partition: Option<String>,
        /// The flash offset it is written at.
        offset: u64,
    },
    /// An image does not have the SHA-256 digest the manifest gives.
    ChecksumMismatch {
        /// The path, as written in the manifest.
        path: String,
        /// The digest of the manifest, in lowercase hexadecimal.
        expected: String,
        /// The digest of the file, in lowercase hexadecimal.
        actual: String,
    },
    /// The verifier refused an image.
    ImageRejected {
        /// The path, as written in the manifest.
        path: String,
        /// Why.
        reason: String,
    },
    /// An image goes to a partition and the board has no layout.
    ImageNeedsLayout {
        /// The board.
        board: String,
        /// The partition.
        partition: String,
    },
    /// An image or an erase entry names a partition the layout does not define.
    UnknownPartition {
        /// The board.
        board: String,
        /// The partition.
        partition: String,
    },
    /// An image starts at an offset the flash cannot erase from.
    MisalignedImage {
        /// The image.
        label: String,
        /// Its offset.
        offset: u64,
        /// The multiple the offset must be of.
        required: u64,
    },
    /// Two images share flash sectors.
    OverlappingImages {
        /// The image that comes first by offset.
        first: String,
        /// The image that comes second by offset.
        second: String,
        /// The end of the first image, rounded up to a whole erase sector.
        first_end: u64,
        /// The offset of the second image.
        second_offset: u64,
    },
    /// An image does not fit in its partition.
    ImageTooLarge {
        /// The image.
        label: String,
        /// The partition.
        partition: String,
        /// The size of the image.
        image_size: u64,
        /// The size of the partition.
        partition_size: u64,
    },
    /// An image replaces the partition table of a layout whose partitions grow or move with the
    /// flash of the chip: the table nanoflash generates for the chip would be lost.
    PartitionTableImageForDetectedFlash {
        /// The partition of the table.
        partition: String,
    },
    /// An input tied to flash offsets (an image or an erase entry given by offset, an Intel HEX
    /// image) overlaps a partition that moves with the flash of the chip.
    FixedOffsetOnMovingPartition {
        /// The input, such as `image "image at 0x3f0000"` or `Intel HEX image "core.hex"`.
        what: String,
        /// The offset of its first byte.
        start: u64,
        /// Its exclusive end.
        end: u64,
        /// The partition it overlaps.
        partition: String,
        /// The offset of the partition on that flash.
        partition_offset: u64,
        /// The flash size the layout was resolved for.
        flash_size: u64,
        /// Whether its addresses are in its file (Intel HEX or ELF).
        addresses_in_file: bool,
    },
    /// An image ends after the end of the flash.
    ImageOutsideFlash {
        /// The image.
        label: String,
        /// Its exclusive end.
        end: u64,
        /// The flash size of the layout.
        flash_size: u64,
    },
    /// An erase entry does not start and end on the erase unit of the flash.
    MisalignedErase {
        /// The entry: its partition, or `region at 0x<offset>`.
        entry: String,
        /// Its offset.
        offset: u64,
        /// Its size.
        size: u64,
        /// The multiple the offset and the size must be of.
        required: u64,
    },
    /// An erase entry ends after the end of the flash of the layout.
    EraseOutsideFlash {
        /// The entry: its partition, or `region at 0x<offset>`.
        entry: String,
        /// Its exclusive end.
        end: u64,
        /// The flash size of the layout.
        flash_size: u64,
    },
    /// An image or an erase entry ends beyond what the protocol can address.
    OutsideAddressRange {
        /// What ends there, such as `image "application"`.
        what: String,
        /// Its exclusive end.
        end: u64,
        /// The end of what the protocol can address.
        limit: u64,
        /// The protocol.
        protocol: Protocol,
    },
    /// An image or an erase entry ends after the end of the flash the chip reports.
    OutsideDetectedFlash {
        /// What ends there, such as `image "application"`.
        what: String,
        /// Its exclusive end.
        end: u64,
        /// The flash size the chip reported.
        flash_size: u64,
    },
    /// The board of the manifest lists no image and no erase entry.
    NothingToFlash {
        /// The board.
        board: String,
    },
    /// An image file has no byte.
    EmptyImage {
        /// The path, as written in the manifest.
        path: String,
    },
    /// There is not enough memory for a buffer.
    OutOfMemory {
        /// What the buffer is for, such as `flash image`.
        what: String,
        /// Its size in bytes.
        size: u64,
    },
    /// The requested board is not in the manifest.
    UnknownBoard {
        /// The requested identifier.
        identifier: String,
        /// The identifiers of the manifest.
        known: Vec<String>,
    },
    /// No board of the manifest suits the device.
    NoMatchingBoard {
        /// The USB identity of the device, when it has one.
        identity: Option<UsbIdentity>,
    },
    /// The candidate boards speak several protocols.
    SeveralProtocols {
        /// The protocols.
        protocols: Vec<Protocol>,
    },
    /// Several boards have the detected chip.
    SeveralBoards {
        /// The chip.
        chip: String,
        /// The identifiers of the boards.
        boards: Vec<String>,
    },
    /// The manifest has several boards and none was chosen.
    BoardRequired {
        /// The identifiers of the boards.
        boards: Vec<String>,
    },
    /// The protocol of the device cannot be told from its USB identity and none was given.
    ProtocolRequired {
        /// The USB identity of the device, when it has one.
        identity: Option<UsbIdentity>,
    },
    /// The protocol was not compiled in.
    ProtocolNotEnabled {
        /// The protocol.
        protocol: Protocol,
    },
    /// The size of the flash is needed and neither the layout nor the chip gave it.
    UnknownFlashSize,
    /// A flash size was given for a board whose layout does not have `size = "detect"`.
    FlashSizeNeedsDetectLayout,
    /// The flash of the chip is smaller than the layout.
    FlashTooSmall {
        /// The flash size of the layout.
        layout: u64,
        /// The flash size the chip reported.
        detected: u64,
    },
    /// The chip found is not the one of the selected board.
    WrongChip {
        /// The chip found.
        detected: String,
        /// The chips of the candidate boards.
        expected: Vec<String>,
    },
    /// The flash does not hold what was written.
    VerificationFailed {
        /// The image.
        label: String,
        /// The flash offset of the part checked: the image, or the chunk of it the backend
        /// checks at a time.
        offset: u64,
        /// The number of bytes of the part checked.
        size: u64,
        /// The checksum named by `checksum` of what was written, in lowercase hexadecimal.
        expected: String,
        /// The checksum named by `checksum` the board computed over the flash, in lowercase
        /// hexadecimal.
        actual: String,
        /// The checksum the backend compares, such as `MD5` or `CRC-16`.
        checksum: &'static str,
    },
    /// No bootloader answered: none appeared after the reset, or the port is not one.
    NoBootloader {
        /// The USB identity of the bootloader device waited for after the reset, such as
        /// `2341:005a`; `None` when the port itself did not answer as a bootloader.
        waited_for: Option<String>,
        /// The reset sequence run before waiting, such as `touch-1200` or `custom`; `None` when
        /// nothing was waited for, or for STK500 when the backend pulsed DTR.
        reset: Option<&'static str>,
        /// The protocol of the bootloader, which picks the hint.
        protocol: Protocol,
        /// The baud rates tried on the port, in order; empty for the protocols reached through
        /// the 1200-baud touch, whose USB port ignores the baud rate.
        rates: Vec<u32>,
    },
    /// A backend was asked to erase, write, verify or reset before a successful `connect`.
    NotConnected {
        /// The protocol of the backend.
        protocol: Protocol,
    },
    /// The bootloader lacks the commands nanoflash needs.
    UnsupportedBootloader {
        /// What the bootloader says of its version.
        version: String,
    },
    /// The USB identity the bootloader of a device shows is unknown, so the device cannot be
    /// reopened after the reset.
    UnknownBootloaderDevice {
        /// The USB identity of the device running its application.
        identity: UsbIdentity,
    },
    /// An image or an erase entry starts in the flash the bootloader protects.
    BelowWritableFlash {
        /// What starts there, such as `image "bootloader"`.
        what: String,
        /// Its offset.
        offset: u64,
        /// The lowest flash offset the bootloader writes.
        writable_from: u64,
    },
    /// An image or an erase entry ends in the flash the bootloader occupies at the top of the
    /// flash.
    AboveWritableFlash {
        /// What ends there, such as `image "application"`.
        what: String,
        /// Its end offset.
        end: u64,
        /// The end of the flash the bootloader writes.
        writable_to: u64,
        /// The protocol of the bootloader, which picks the explanation.
        protocol: Protocol,
    },
    /// The flash read back differs from what was written.
    ReadBackDiffers {
        /// The image.
        label: String,
        /// The flash offset of the first differing byte.
        offset: u64,
        /// The byte written.
        expected: u8,
        /// The byte read back.
        actual: u8,
    },
    /// An erase region stops before the end of flash, and the bootloader only erases from an
    /// offset to the end of flash.
    EraseShortOfFlashEnd {
        /// The chip, such as `samd21g18a`.
        chip: String,
        /// The erase entry: its partition, or `region at 0x<offset>`.
        entry: String,
        /// The flash offset of the region.
        offset: u64,
        /// Its exclusive end.
        end: u64,
        /// The flash size of the chip, where every erase ends.
        flash_size: u64,
    },
    /// An image comes after an image written above it, and the bootloader erases from the
    /// start of an image to the end of flash before writing it.
    ImageBelowWritten {
        /// The chip, such as `samd21g18a`.
        chip: String,
        /// The image.
        label: String,
        /// Its offset.
        offset: u64,
    },
    /// A page would be programmed where the bootloader does not erase it first: the wiring
    /// bootloader of the Mega 2560 erases one page per page programmed, in order from 0x0,
    /// wherever the programmed page goes.
    PageOutOfEraseOrder {
        /// What programs the page, such as `image "application"` or `erase region at 0x1000`.
        what: String,
        /// The flash offset of the page.
        offset: u64,
        /// The flash offset of the page the bootloader erases next.
        erases_next: u64,
    },
}

/// Who can fix an error: the input (exit code 1), the device or its connection (2), or the
/// written data did not read back (3).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum ErrorClass {
    /// The manifest, the layout, the images or the options.
    Input,
    /// The board, the port or the cable.
    Device,
    /// What was written differs from what reads back.
    Verification,
}

impl Error {
    /// Who can fix this error.
    pub fn class(&self) -> ErrorClass {
        match self {
            Error::UnsupportedReset { .. }
            | Error::OutOfRange { .. }
            | Error::Manifest { .. }
            | Error::Layout { .. }
            | Error::LayoutFile { .. }
            | Error::Table { .. }
            | Error::ImageSource { .. }
            | Error::ChecksumMismatch { .. }
            | Error::ImageRejected { .. }
            | Error::IntelHex { .. }
            | Error::MisplacedIntelHex { .. }
            | Error::ElfNotEnabled { .. }
            | Error::ImageNeedsLayout { .. }
            | Error::UnknownPartition { .. }
            | Error::MisalignedImage { .. }
            | Error::OverlappingImages { .. }
            | Error::ImageTooLarge { .. }
            | Error::PartitionTableImageForDetectedFlash { .. }
            | Error::FixedOffsetOnMovingPartition { .. }
            | Error::ImageOutsideFlash { .. }
            | Error::MisalignedErase { .. }
            | Error::EraseOutsideFlash { .. }
            | Error::OutsideAddressRange { .. }
            | Error::OutsideDetectedFlash { .. }
            | Error::NothingToFlash { .. }
            | Error::EmptyImage { .. }
            | Error::OutOfMemory { .. }
            | Error::UnknownBoard { .. }
            | Error::NoMatchingBoard { .. }
            | Error::SeveralProtocols { .. }
            | Error::SeveralBoards { .. }
            | Error::BoardRequired { .. }
            | Error::ProtocolRequired { .. }
            | Error::ProtocolNotEnabled { .. }
            | Error::UnknownFlashSize
            | Error::FlashSizeNeedsDetectLayout
            | Error::FlashTooSmall { .. }
            | Error::UnknownBootloaderDevice { .. }
            | Error::BelowWritableFlash { .. }
            | Error::AboveWritableFlash { .. }
            | Error::EraseShortOfFlashEnd { .. }
            | Error::ImageBelowWritten { .. }
            | Error::PageOutOfEraseOrder { .. }
            | Error::NotConnected { .. } => ErrorClass::Input,
            #[cfg(feature = "elf")]
            Error::Elf { .. }
            | Error::MisplacedElf { .. }
            | Error::ApplicationImage { .. }
            | Error::ElfNotAnApplication { .. }
            | Error::MisalignedApplicationImage { .. } => ErrorClass::Input,
            Error::Transport { .. }
            | Error::NoResponse { .. }
            | Error::NoSync { .. }
            | Error::NotInDownloadMode { .. }
            | Error::Rom { .. }
            | Error::InvalidResponse { .. }
            | Error::UnknownChip { .. }
            | Error::UnsupportedChip { .. }
            | Error::WrongChip { .. }
            | Error::NoBootloader { .. }
            | Error::UnsupportedBootloader { .. } => ErrorClass::Device,
            Error::VerificationFailed { .. } | Error::ReadBackDiffers { .. } => {
                ErrorClass::Verification
            }
        }
    }
}

impl From<TransportError> for Error {
    fn from(error: TransportError) -> Self {
        Error::Transport {
            error,
            during: None,
        }
    }
}

impl Error {
    /// Says what was being done when the serial port failed, unless the error already says.
    /// Other errors are returned unchanged.
    pub fn during(self, what: impl FnOnce() -> String) -> Error {
        match self {
            Error::Transport {
                error,
                during: None,
            } => Error::Transport {
                error,
                during: Some(what()),
            },
            other => other,
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::Transport { error, during } => {
                write!(formatter, "{error}")?;
                if let Some(during) = during {
                    write!(formatter, " while {during}")?;
                }
                if *error == TransportError::Disconnected {
                    formatter.write_str(": check the cable and the port, then try again")?;
                }
                Ok(())
            }
            Error::NoResponse { command } => write!(
                formatter,
                "the board did not answer {command}: check the port and the cable, then try again"
            ),
            Error::NoSync { attempts } => write!(
                formatter,
                "the board did not answer SYNC after {attempts} resets: check the port and the cable, or hold BOOT (GPIO0) while pressing RESET"
            ),
            Error::NotInDownloadMode { boot_mode } => write!(
                formatter,
                "the chip booted in mode {boot_mode} instead of download mode: hold BOOT (GPIO0) while pressing RESET, or check the auto-reset circuit"
            ),
            Error::Rom { command, code } => write!(
                formatter,
                "the ROM loader refused {command}: {} (0x{code:02x})",
                rom_error(*code)
            ),
            Error::InvalidResponse { command, message } => write!(
                formatter,
                "the board answered {command} with an invalid response: {message}"
            ),
            Error::UnknownChip { detail } => write!(
                formatter,
                "the chip could not be identified ({detail}): it may be newer than this version of nanoflash"
            ),
            Error::UnsupportedChip { chip } => {
                write!(formatter, "the {chip} is not supported by nanoflash")
            }
            Error::UnsupportedReset { protocol, reset } => write!(
                formatter,
                "the {reset} reset does not apply to the {protocol} protocol: choose another reset for the board in the manifest"
            ),
            Error::OutOfRange { what, value } => write!(
                formatter,
                "the {what} 0x{value:x} is beyond what the protocol can address"
            ),
            Error::Manifest { error } => write!(formatter, "{error}"),
            Error::Layout { errors } => {
                for (index, error) in errors.iter().enumerate() {
                    if index > 0 {
                        formatter.write_str("\n")?;
                    }
                    write!(formatter, "{error}")?;
                }
                Ok(())
            }
            Error::LayoutFile { path, message } => write!(
                formatter,
                "the layout file \"{path}\" could not be read: {message}: check the \"layout\" path of the board in the manifest"
            ),
            Error::Table { error } => write!(
                formatter,
                "the partition table cannot be written for the layout: {error}"
            ),
            Error::ImageSource { path, message } => write!(
                formatter,
                "the image \"{path}\" could not be read: {message}: check the path in the manifest"
            ),
            Error::ChecksumMismatch {
                path,
                expected,
                actual,
            } => write!(
                formatter,
                "the image \"{path}\" has the SHA-256 digest {actual} instead of {expected}: rebuild the image or update the \"sha256\" of the manifest"
            ),
            Error::IntelHex {
                path,
                line,
                message,
            } => {
                write!(formatter, "the Intel HEX image \"{path}\" is invalid")?;
                if let Some(line) = line {
                    write!(formatter, " at line {line}")?;
                }
                write!(
                    formatter,
                    ": {message}: rebuild it, or give its binary form"
                )
            }
            Error::MisplacedIntelHex {
                path,
                start,
                expected,
                base_address,
                partition,
            } => {
                write!(
                    formatter,
                    "the Intel HEX image \"{path}\" starts at 0x{start:x}, but "
                )?;
                match partition {
                    Some(partition) => write!(
                        formatter,
                        "the partition \"{partition}\" it is written to starts at 0x{expected:x}"
                    )?,
                    None => write!(formatter, "the manifest places it at 0x{expected:x}")?,
                }
                match (start.checked_sub(*base_address), partition) {
                    (Some(offset), Some(_)) => write!(
                        formatter,
                        ": fix the partition of the image (it starts at the flash offset 0x{offset:x}), or rebuild it for that partition"
                    ),
                    (Some(offset), None) => write!(
                        formatter,
                        ": fix the offset of the image to 0x{offset:x}, or name the partition that starts there"
                    ),
                    (None, _) => write!(
                        formatter,
                        ": it starts below the flash, which starts at 0x{base_address:x}: rebuild it for this board, or fix the base address of the layout"
                    ),
                }
            }
            Error::ElfNotEnabled { path } => write!(
                formatter,
                "the image \"{path}\" is an ELF file, which this build of nanoflash does not read: give its binary image (objcopy -O binary) or its Intel HEX image"
            ),
            #[cfg(feature = "elf")]
            Error::Elf { path, message } => write!(
                formatter,
                "the ELF image \"{path}\" cannot be flashed: {message}"
            ),
            #[cfg(feature = "elf")]
            Error::MisplacedElf {
                path,
                start,
                expected,
                base_address,
                partition,
            } => {
                write!(
                    formatter,
                    "the ELF image \"{path}\" starts at 0x{start:x}, but "
                )?;
                match partition {
                    Some(partition) => write!(
                        formatter,
                        "the partition \"{partition}\" it is written to starts at 0x{expected:x}"
                    )?,
                    None => write!(formatter, "the manifest places it at 0x{expected:x}")?,
                }
                match (start.checked_sub(*base_address), partition) {
                    (Some(offset), Some(_)) => write!(
                        formatter,
                        ": link it for that partition (memory.x), or fix the partition of the image (it starts at the flash offset 0x{offset:x})"
                    ),
                    (Some(offset), None) => write!(
                        formatter,
                        ": fix the offset of the image to 0x{offset:x}, or name the partition that starts there"
                    ),
                    (None, _) => write!(
                        formatter,
                        ": it starts below the flash, which starts at 0x{base_address:x}: link it for this board, or fix the base address of the layout"
                    ),
                }
            }
            #[cfg(feature = "elf")]
            Error::ApplicationImage {
                path,
                partition,
                reason,
            } => {
                write!(
                    formatter,
                    "the Espressif application image of the ELF file \"{path}\""
                )?;
                if let Some(partition) = partition {
                    write!(formatter, " for the partition \"{partition}\"")?;
                }
                write!(formatter, " could not be built: {reason}")
            }
            #[cfg(feature = "elf")]
            Error::ElfNotAnApplication {
                path,
                partition,
                offset,
            } => {
                write!(formatter, "the ELF image \"{path}\" is written ")?;
                if let Some(partition) = partition {
                    write!(formatter, "to the partition \"{partition}\" ")?;
                }
                write!(
                    formatter,
                    "at 0x{offset:x}, but the Espressif bootloader boots only applications from ELF files, in a \"firmware\" or \"update\" partition: give the binary image of the bootloader or of the data"
                )
            }
            #[cfg(feature = "elf")]
            Error::MisalignedApplicationImage {
                path,
                partition,
                offset,
            } => {
                write!(
                    formatter,
                    "the Espressif application image of \"{path}\" goes "
                )?;
                if let Some(partition) = partition {
                    write!(formatter, "to the partition \"{partition}\" ")?;
                }
                write!(
                    formatter,
                    "at 0x{offset:x}, but the bootloader maps applications in pages of 0x10000 bytes: place it at a multiple of 0x10000, not below 0x10000"
                )
            }
            Error::ImageRejected { path, reason } => {
                write!(formatter, "the image \"{path}\" was rejected: {reason}")
            }
            Error::ImageNeedsLayout { board, partition } => write!(
                formatter,
                "the board \"{board}\" has a manifest image or erase entry for the partition \"{partition}\" and no layout: add a \"layout\" to the board, or use an \"offset\""
            ),
            Error::UnknownPartition { board, partition } => write!(
                formatter,
                "the board \"{board}\" has a manifest image or erase entry for the partition \"{partition}\", which its layout does not define"
            ),
            Error::MisalignedImage {
                label,
                offset,
                required,
            } => write!(
                formatter,
                "the image \"{label}\" starts at offset 0x{offset:x}, which is not a multiple of 0x{required:x}: the bootloader erases whole sectors of 0x{required:x} bytes, so it would erase the bytes before the image; move the image to a multiple of 0x{required:x}"
            ),
            Error::OverlappingImages {
                first,
                second,
                first_end,
                second_offset,
            } => write!(
                formatter,
                "the image \"{first}\" ends at 0x{first_end:x} once rounded up to whole erase sectors, past the start of the image \"{second}\" at 0x{second_offset:x}: move one of the images"
            ),
            Error::ImageTooLarge {
                label,
                partition,
                image_size,
                partition_size,
            } => write!(
                formatter,
                "the image \"{label}\" of 0x{image_size:x} bytes does not fit in the partition \"{partition}\" of 0x{partition_size:x} bytes: enlarge the partition in the layout or shrink the image"
            ),
            Error::PartitionTableImageForDetectedFlash { partition } => write!(
                formatter,
                "the manifest writes an image to the partition table \"{partition}\", but partitions of the layout grow or move with the flash of the chip, so no fixed table fits every chip: remove the image and let nanoflash generate the table, or give the layout a fixed flash size"
            ),
            Error::FixedOffsetOnMovingPartition {
                what,
                start,
                end,
                partition,
                partition_offset,
                flash_size,
                addresses_in_file,
            } => {
                write!(
                    formatter,
                    "the {what} covers 0x{start:x}..0x{end:x}, which overlaps the partition \"{partition}\" at 0x{partition_offset:x} on 0x{flash_size:x} bytes of flash, but \"{partition}\" moves with the flash of the chip: "
                )?;
                formatter.write_str(if *addresses_in_file {
                    "give the partition a binary image (.bin), targeted by name"
                } else {
                    "target the partition by name in the manifest"
                })
            }
            Error::ImageOutsideFlash {
                label,
                end,
                flash_size,
            } => write!(
                formatter,
                "the image \"{label}\" ends at 0x{end:x}, past the end of the 0x{flash_size:x} bytes of flash of the layout: move the image or enlarge the flash in the layout"
            ),
            Error::MisalignedErase {
                entry,
                offset,
                size,
                required,
            } => write!(
                formatter,
                "the erase entry \"{entry}\" covers 0x{offset:x}..0x{:x}, which does not start and end on multiples of 0x{required:x}: the flash is erased in whole sectors of 0x{required:x} bytes, so the bytes around the entry would be erased too; align the entry to 0x{required:x}",
                offset.saturating_add(*size)
            ),
            Error::EraseOutsideFlash {
                entry,
                end,
                flash_size,
            } => write!(
                formatter,
                "the erase entry \"{entry}\" ends at 0x{end:x}, past the end of the 0x{flash_size:x} bytes of flash of the layout: shrink the entry or enlarge the flash in the layout"
            ),
            Error::OutsideAddressRange {
                what,
                end,
                limit,
                protocol,
            } => write!(
                formatter,
                "the {what} ends at 0x{end:x}, past 0x{limit:x}, the end of what the {protocol} protocol can address: move it below 0x{limit:x}"
            ),
            Error::OutsideDetectedFlash {
                what,
                end,
                flash_size,
            } => write!(
                formatter,
                "the {what} ends at 0x{end:x}, past the end of the 0x{flash_size:x} bytes of flash the chip reports, so nothing was erased or written: move it, or connect a board with more flash"
            ),
            Error::NothingToFlash { board } => write!(
                formatter,
                "the board \"{board}\" has no image and no erase entry in the manifest: add an image to write"
            ),
            Error::EmptyImage { path } => write!(
                formatter,
                "the image \"{path}\" is empty: rebuild it, or remove it from the manifest"
            ),
            Error::OutOfMemory { what, size } => write!(
                formatter,
                "there is not enough memory for the 0x{size:x} bytes of the {what}"
            ),
            Error::UnknownBoard { identifier, known } => write!(
                formatter,
                "the manifest has no board \"{identifier}\": the boards are {}",
                known.join(", ")
            ),
            Error::NoMatchingBoard { identity } => {
                match identity {
                    Some(identity) => write!(
                        formatter,
                        "no board of the manifest matches the device {:04x}:{:04x}",
                        identity.vendor, identity.product
                    )?,
                    None => formatter.write_str(
                        "no board of the manifest suits a device without a USB identity",
                    )?,
                }
                formatter.write_str(": pass --board-identifier, or list the device in the manifest")
            }
            Error::SeveralProtocols { protocols } => {
                formatter.write_str("the candidate boards speak several protocols (")?;
                for (index, protocol) in protocols.iter().enumerate() {
                    if index > 0 {
                        formatter.write_str(", ")?;
                    }
                    write!(formatter, "{protocol}")?;
                }
                formatter.write_str("): pass --board-identifier")
            }
            Error::SeveralBoards { chip, boards } => write!(
                formatter,
                "several boards have the chip {chip} ({}): pass --board-identifier",
                boards.join(", ")
            ),
            Error::BoardRequired { boards } => write!(
                formatter,
                "the manifest has several boards ({}): pass --board-identifier",
                boards.join(", ")
            ),
            Error::ProtocolRequired { identity } => {
                match identity {
                    Some(identity) => write!(
                        formatter,
                        "the protocol of the device {:04x}:{:04x} is unknown",
                        identity.vendor, identity.product
                    )?,
                    None => formatter.write_str("the protocol of the device is unknown")?,
                }
                formatter.write_str(": pass --protocol")
            }
            Error::ProtocolNotEnabled { protocol } => write!(
                formatter,
                "the {protocol} protocol is not enabled in this build of nanoflash"
            ),
            Error::UnknownFlashSize => formatter.write_str(
                "the size of the flash is unknown: add a layout to the board, or connect to a chip that reports it",
            ),
            Error::FlashSizeNeedsDetectLayout => formatter.write_str(
                "a flash size needs a board with a layout that has size = \"detect\" and a minimum: this board has no layout, so drop the flash size or add such a layout",
            ),
            Error::FlashTooSmall { layout, detected } => write!(
                formatter,
                "the layout needs 0x{layout:x} bytes of flash and the chip has 0x{detected:x}: use a layout that fits, or a board with more flash"
            ),
            Error::WrongChip { detected, expected } => write!(
                formatter,
                "the chip found is {detected} and the selected boards have {}: pass --board-identifier of the right board, or connect the right board",
                expected.join(", ")
            ),
            Error::VerificationFailed {
                label,
                offset,
                size,
                expected,
                actual,
                checksum,
            } => write!(
                formatter,
                "the image \"{label}\" at 0x{offset:x} (0x{size:x} bytes) does not read back as written: the board computed the {checksum} {actual} instead of {expected}: flash again, and check the power supply and the flash size of the board if it fails again"
            ),
            Error::NoBootloader {
                waited_for,
                reset,
                protocol,
                rates,
            } => match protocol {
                // The Espressif backend reports `NoSync` instead.
                Protocol::Espressif | Protocol::Samba => match (waited_for, reset) {
                    (Some(filter), Some("touch-1200")) => write!(
                        formatter,
                        "no bootloader device matching {filter} appeared within 15 s after the 1200-baud touch: double-tap the reset button of the board (its LED pulses in the bootloader), then try again"
                    ),
                    (Some(filter), Some(reset)) => write!(
                        formatter,
                        "no bootloader device matching {filter} appeared within 15 s after the reset sequence \"{reset}\" of the board: check the reset sequence of the board in the manifest, or double-tap the reset button of the board (its LED pulses in the bootloader) and try again"
                    ),
                    (Some(filter), None) => write!(
                        formatter,
                        "no bootloader device matching {filter} appeared within 15 s after the reset: double-tap the reset button of the board (its LED pulses in the bootloader), then try again"
                    ),
                    (None, _) => formatter.write_str(
                        "no SAM-BA bootloader answered on the port: double-tap the reset button of the board (its LED pulses in the bootloader), then try again with the port it shows",
                    ),
                },
                Protocol::Avr109 => match (waited_for, reset) {
                    (Some(filter), Some("touch-1200")) => write!(
                        formatter,
                        "no bootloader device matching {filter} appeared after the 1200-baud touch: press the reset button of the board once (its LED pulses for 8 s in the bootloader), then try again with the port it shows"
                    ),
                    (Some(filter), Some(reset)) => write!(
                        formatter,
                        "no bootloader device matching {filter} appeared after the reset sequence \"{reset}\" of the board: check the reset sequence of the board in the manifest, or press the reset button of the board once (its LED pulses for 8 s in the bootloader) and try again with the port it shows"
                    ),
                    (Some(filter), None) => write!(
                        formatter,
                        "no bootloader device matching {filter} appeared after the reset: press the reset button of the board once (its LED pulses for 8 s in the bootloader), then try again with the port it shows"
                    ),
                    (None, _) => formatter.write_str(
                        "no AVR109 bootloader answered on the port: press the reset button of the board once (its LED pulses for 8 s in the bootloader), then try again with the port it shows",
                    ),
                },
                Protocol::Stk500v1 | Protocol::Stk500v2 => {
                    let name = if *protocol == Protocol::Stk500v1 {
                        "STK500v1"
                    } else {
                        "STK500v2"
                    };
                    write!(formatter, "no {name} bootloader answered on the port")?;
                    let mut rates = rates.iter();
                    if let Some(first) = rates.next() {
                        write!(formatter, " at {first}")?;
                        for rate in rates {
                            write!(formatter, " and {rate}")?;
                        }
                        formatter.write_str(" baud")?;
                    }
                    if *reset == Some("custom") {
                        formatter.write_str(
                            " after the reset sequence \"custom\" of the board: check the port and the cable and the reset sequence of the board in the manifest, or press the reset button of the board just before flashing",
                        )
                    } else if *reset == Some("none") {
                        formatter.write_str(
                            " with the reset sequence \"none\" of the board, which does not reset it: press the reset button of the board just before flashing, or check the port and the cable",
                        )
                    } else {
                        formatter.write_str(
                            ": check the port and the cable, or press the reset button of the board just before flashing (its automatic reset through DTR may be missing)",
                        )
                    }
                }
            },
            Error::NotConnected { protocol } => write!(
                formatter,
                "the {protocol} backend was asked to erase, write, verify or reset before it connected, so nothing was sent to the board: call connect first"
            ),
            Error::UnsupportedBootloader { version } => write!(
                formatter,
                "the bootloader says \"{version}\" and lacks Arduino's SAM-BA extensions X, Y and Z, which nanoflash needs: update the bootloader, or flash with bossac"
            ),
            Error::UnknownBootloaderDevice { identity } => write!(
                formatter,
                "the USB identity of the bootloader of the device {:04x}:{:04x} is unknown: list it in \"bootloader-devices\" of the board, or double-tap the reset button and pass the bootloader's port",
                identity.vendor, identity.product
            ),
            Error::BelowWritableFlash {
                what,
                offset,
                writable_from,
            } => write!(
                formatter,
                "the {what} starts at 0x{offset:x}, below 0x{writable_from:x}: the bootloader occupies the flash below 0x{writable_from:x} and does not write it; remove it from the manifest or move it to 0x{writable_from:x} or above"
            ),
            Error::AboveWritableFlash {
                what,
                end,
                writable_to,
                protocol: Protocol::Stk500v2,
            } => write!(
                formatter,
                "the {what} ends at 0x{end:x}, past 0x{writable_to:x}: the STK500v2 bootloader of the Mega 2560 erases pages only below 0x{writable_to:x}, 16 KiB under the end of flash although it occupies only the last 8 KiB, so the pages past 0x{writable_to:x} would be programmed without being erased; remove it from the manifest or make it end at 0x{writable_to:x} or below"
            ),
            Error::AboveWritableFlash {
                what,
                end,
                writable_to,
                ..
            } => write!(
                formatter,
                "the {what} ends at 0x{end:x}, past 0x{writable_to:x}: the bootloader occupies the flash from 0x{writable_to:x} and does not write it; remove it from the manifest or make it end at 0x{writable_to:x} or below"
            ),
            Error::ReadBackDiffers {
                label,
                offset,
                expected,
                actual,
            } => write!(
                formatter,
                "the image \"{label}\" does not read back as written: the byte at 0x{offset:x} is 0x{actual:02x} instead of 0x{expected:02x}: flash again; if it fails at the same place, the lock bits of the chip protect that part of the flash"
            ),
            Error::EraseShortOfFlashEnd {
                chip,
                entry,
                offset,
                end,
                flash_size,
            } => write!(
                formatter,
                "the erase entry \"{entry}\" covers 0x{offset:x}..0x{end:x}, and the bootloader of the {chip} erases from an offset to the end of flash, so erasing it would also erase 0x{end:x}..0x{flash_size:x}; it was not erased: make the erase entry end at 0x{flash_size:x}, or remove it from the manifest"
            ),
            Error::ImageBelowWritten {
                chip,
                label,
                offset,
            } => write!(
                formatter,
                "the image \"{label}\" at 0x{offset:x} is written after an image above it, and the bootloader of the {chip} erases from 0x{offset:x} to the end of flash before writing it, which would erase that image, so it was not written: write the images in order of offset"
            ),
            Error::PageOutOfEraseOrder {
                what,
                offset,
                erases_next,
            } => write!(
                formatter,
                "the {what} programs the page at 0x{offset:x}, but the STK500v2 bootloader of the Mega 2560 erases one page per page programmed, in order from 0x0 wherever the page goes, and erases 0x{erases_next:x} next: the page at 0x{offset:x} would not be erased, or another would be; nothing was written: write the images as one run from 0x0 in order of offset and erase only from 0x0, or first erase every page the bootloader erases (--erase-all)"
            ),
        }
    }
}

impl core::error::Error for Error {}

/// The meaning of an Espressif ROM loader error code.
pub(crate) fn rom_error(code: u8) -> &'static str {
    match code {
        0x05 => "the message is malformed",
        0x06 => "the command failed",
        0x07 => "bad checksum",
        0x08 => "flash write failed (read-back mismatch)",
        0x09 => "flash read failed",
        0x0A => "bad flash read length",
        0x0B => "decompression failed",
        0x0C => "decompressed data has a bad Adler-32 checksum",
        0x0D => "bad decompression parameter",
        0x0E => "bad RAM binary size",
        0x0F => "bad RAM binary address",
        0x64 => "invalid parameter",
        0x65 => "invalid format",
        0x66 => "description too long",
        0x67 => "bad encoding description",
        0x69 => "insufficient storage",
        _ => "unknown error",
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::string::ToString;

    #[test]
    fn bootloader_errors_have_their_class_and_hint() {
        let waited = Error::NoBootloader {
            waited_for: Some("2341:005a".into()),
            reset: Some("touch-1200"),
            protocol: Protocol::Samba,
            rates: Vec::new(),
        };
        assert_eq!(waited.class(), ErrorClass::Device);
        assert_eq!(
            waited.to_string(),
            "no bootloader device matching 2341:005a appeared within 15 s after the 1200-baud touch: double-tap the reset button of the board (its LED pulses in the bootloader), then try again"
        );
        let custom = Error::NoBootloader {
            waited_for: Some("2341:005a".into()),
            reset: Some("custom"),
            protocol: Protocol::Samba,
            rates: Vec::new(),
        };
        assert_eq!(
            custom.to_string(),
            "no bootloader device matching 2341:005a appeared within 15 s after the reset sequence \"custom\" of the board: check the reset sequence of the board in the manifest, or double-tap the reset button of the board (its LED pulses in the bootloader) and try again"
        );
        let silent = Error::NoBootloader {
            waited_for: None,
            reset: None,
            protocol: Protocol::Samba,
            rates: Vec::new(),
        };
        assert_eq!(silent.class(), ErrorClass::Device);
        assert_eq!(
            silent.to_string(),
            "no SAM-BA bootloader answered on the port: double-tap the reset button of the board (its LED pulses in the bootloader), then try again with the port it shows"
        );
        let early = Error::NotConnected {
            protocol: Protocol::Samba,
        };
        assert_eq!(early.class(), ErrorClass::Input);
        assert_eq!(
            early.to_string(),
            "the samba backend was asked to erase, write, verify or reset before it connected, so nothing was sent to the board: call connect first"
        );
        let unsupported = Error::UnsupportedBootloader {
            version: "v1.1 [Arduino:IKXYZ]".into(),
        };
        assert_eq!(unsupported.class(), ErrorClass::Device);
        assert_eq!(
            unsupported.to_string(),
            "the bootloader says \"v1.1 [Arduino:IKXYZ]\" and lacks Arduino's SAM-BA extensions X, Y and Z, which nanoflash needs: update the bootloader, or flash with bossac"
        );
        let unknown = Error::UnknownBootloaderDevice {
            identity: UsbIdentity {
                vendor: 0x2341,
                product: 0x805a,
                serial_number: None,
            },
        };
        assert_eq!(unknown.class(), ErrorClass::Input);
        assert_eq!(
            unknown.to_string(),
            "the USB identity of the bootloader of the device 2341:805a is unknown: list it in \"bootloader-devices\" of the board, or double-tap the reset button and pass the bootloader's port"
        );
        let below = Error::BelowWritableFlash {
            what: "image \"bootloader\"".into(),
            offset: 0,
            writable_from: 0x1_0000,
        };
        assert_eq!(below.class(), ErrorClass::Input);
        assert_eq!(
            below.to_string(),
            "the image \"bootloader\" starts at 0x0, below 0x10000: the bootloader occupies the flash below 0x10000 and does not write it; remove it from the manifest or move it to 0x10000 or above"
        );
        let above = Error::AboveWritableFlash {
            what: "image \"application\"".into(),
            end: 0x7E01,
            writable_to: 0x7E00,
            protocol: Protocol::Stk500v1,
        };
        assert_eq!(above.class(), ErrorClass::Input);
        assert_eq!(
            above.to_string(),
            "the image \"application\" ends at 0x7e01, past 0x7e00: the bootloader occupies the flash from 0x7e00 and does not write it; remove it from the manifest or make it end at 0x7e00 or below"
        );
        let mega = Error::AboveWritableFlash {
            what: "image \"application\"".into(),
            end: 0x3_C100,
            writable_to: 0x3_C000,
            protocol: Protocol::Stk500v2,
        };
        assert_eq!(mega.class(), ErrorClass::Input);
        assert_eq!(
            mega.to_string(),
            "the image \"application\" ends at 0x3c100, past 0x3c000: the STK500v2 bootloader of the Mega 2560 erases pages only below 0x3c000, 16 KiB under the end of flash although it occupies only the last 8 KiB, so the pages past 0x3c000 would be programmed without being erased; remove it from the manifest or make it end at 0x3c000 or below"
        );
        let short = Error::EraseShortOfFlashEnd {
            chip: "samd21g18a".into(),
            entry: "storage".into(),
            offset: 0x8000,
            end: 0x9000,
            flash_size: 0x4_0000,
        };
        assert_eq!(short.class(), ErrorClass::Input);
        assert_eq!(
            short.to_string(),
            "the erase entry \"storage\" covers 0x8000..0x9000, and the bootloader of the samd21g18a erases from an offset to the end of flash, so erasing it would also erase 0x9000..0x40000; it was not erased: make the erase entry end at 0x40000, or remove it from the manifest"
        );
        let order = Error::ImageBelowWritten {
            chip: "samd21g18a".into(),
            label: "low".into(),
            offset: 0x2000,
        };
        assert_eq!(order.class(), ErrorClass::Input);
        assert_eq!(
            order.to_string(),
            "the image \"low\" at 0x2000 is written after an image above it, and the bootloader of the samd21g18a erases from 0x2000 to the end of flash before writing it, which would erase that image, so it was not written: write the images in order of offset"
        );
    }

    #[test]
    fn pages_out_of_erase_order_are_input_errors() {
        let error = Error::PageOutOfEraseOrder {
            what: "image \"application\"".into(),
            offset: 0x100,
            erases_next: 0,
        };
        assert_eq!(error.class(), ErrorClass::Input);
        assert_eq!(
            error.to_string(),
            "the image \"application\" programs the page at 0x100, but the STK500v2 bootloader of the Mega 2560 erases one page per page programmed, in order from 0x0 wherever the page goes, and erases 0x0 next: the page at 0x100 would not be erased, or another would be; nothing was written: write the images as one run from 0x0 in order of offset and erase only from 0x0, or first erase every page the bootloader erases (--erase-all)"
        );
    }

    #[test]
    fn read_back_differences_are_verification_failures() {
        let error = Error::ReadBackDiffers {
            label: "application".into(),
            offset: 0x85,
            expected: 0x0f,
            actual: 0xff,
        };
        assert_eq!(error.class(), ErrorClass::Verification);
        assert_eq!(
            error.to_string(),
            "the image \"application\" does not read back as written: the byte at 0x85 is 0xff instead of 0x0f: flash again; if it fails at the same place, the lock bits of the chip protect that part of the flash"
        );
    }

    #[test]
    fn no_bootloader_names_the_protocol_hint() {
        let caterina = Error::NoBootloader {
            waited_for: Some("2341:0036".into()),
            reset: Some("touch-1200"),
            protocol: Protocol::Avr109,
            rates: Vec::new(),
        };
        assert_eq!(caterina.class(), ErrorClass::Device);
        assert_eq!(
            caterina.to_string(),
            "no bootloader device matching 2341:0036 appeared after the 1200-baud touch: press the reset button of the board once (its LED pulses for 8 s in the bootloader), then try again with the port it shows"
        );
        let custom = Error::NoBootloader {
            waited_for: Some("2341:0036".into()),
            reset: Some("custom"),
            protocol: Protocol::Avr109,
            rates: Vec::new(),
        };
        assert_eq!(
            custom.to_string(),
            "no bootloader device matching 2341:0036 appeared after the reset sequence \"custom\" of the board: check the reset sequence of the board in the manifest, or press the reset button of the board once (its LED pulses for 8 s in the bootloader) and try again with the port it shows"
        );
        let silent = Error::NoBootloader {
            waited_for: None,
            reset: None,
            protocol: Protocol::Avr109,
            rates: Vec::new(),
        };
        assert_eq!(
            silent.to_string(),
            "no AVR109 bootloader answered on the port: press the reset button of the board once (its LED pulses for 8 s in the bootloader), then try again with the port it shows"
        );
        let optiboot = Error::NoBootloader {
            waited_for: None,
            reset: None,
            protocol: Protocol::Stk500v1,
            rates: alloc::vec![115_200, 57_600],
        };
        assert_eq!(optiboot.class(), ErrorClass::Device);
        assert_eq!(
            optiboot.to_string(),
            "no STK500v1 bootloader answered on the port at 115200 and 57600 baud: check the port and the cable, or press the reset button of the board just before flashing (its automatic reset through DTR may be missing)"
        );
        let wiring = Error::NoBootloader {
            waited_for: None,
            reset: Some("none"),
            protocol: Protocol::Stk500v2,
            rates: alloc::vec![115_200],
        };
        assert_eq!(
            wiring.to_string(),
            "no STK500v2 bootloader answered on the port at 115200 baud with the reset sequence \"none\" of the board, which does not reset it: press the reset button of the board just before flashing, or check the port and the cable"
        );
        let custom = Error::NoBootloader {
            waited_for: None,
            reset: Some("custom"),
            protocol: Protocol::Stk500v1,
            rates: alloc::vec![57_600],
        };
        assert_eq!(
            custom.to_string(),
            "no STK500v1 bootloader answered on the port at 57600 baud after the reset sequence \"custom\" of the board: check the port and the cable and the reset sequence of the board in the manifest, or press the reset button of the board just before flashing"
        );
    }

    #[test]
    fn verification_failures_name_their_checksum() {
        let error = Error::VerificationFailed {
            label: "application".into(),
            offset: 0x1_1000,
            size: 0x1000,
            expected: "d5b0".into(),
            actual: "1234".into(),
            checksum: "CRC-16",
        };
        assert_eq!(error.class(), ErrorClass::Verification);
        assert_eq!(
            error.to_string(),
            "the image \"application\" at 0x11000 (0x1000 bytes) does not read back as written: the board computed the CRC-16 1234 instead of d5b0: flash again, and check the power supply and the flash size of the board if it fails again"
        );
    }
}