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
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
use ansi_term::Color;
use ansi_term::Color::Fixed;
use ansi_term::Style;
use regex::Regex;
use serde::{Serialize, Deserialize};
use std::cmp::min;
use std::collections::HashSet;
use std::convert::From;
use std::env;
use std::fmt;
use std::fs;
use std::fs::File;
use std::io;
use std::io::Read;
use std::io::Write;
use std::num::NonZeroUsize;
use std::path::Path;
use std::path::PathBuf;
use thiserror::Error;
use unicode_segmentation::UnicodeSegmentation;

pub static DEFAULT_WIDTH:usize = 16;

/* Byte formatting stuff lifted from hexyl */
pub enum ByteCategory {
    Null,
    AsciiPrintable,
    AsciiWhitespace,
    AsciiOther,
    NonAscii,
}

#[derive(Copy, Clone)]
pub struct Byte(pub u8);

impl Byte {
    pub fn category(self) -> ByteCategory {
        if self.0 == 0x00 {
            ByteCategory::Null
        } else if self.0.is_ascii_graphic() {
            ByteCategory::AsciiPrintable
        } else if self.0.is_ascii_whitespace() {
            ByteCategory::AsciiWhitespace
        } else if self.0.is_ascii() {
            ByteCategory::AsciiOther
        } else {
            ByteCategory::NonAscii
        }
    }

    pub fn color(self) -> &'static Color {
        use ByteCategory::*;

        match self.category() {
            Null => &COLOR_NULL,
            AsciiPrintable => &COLOR_ASCII_PRINTABLE,
            AsciiWhitespace => &COLOR_ASCII_WHITESPACE,
            AsciiOther => &COLOR_ASCII_OTHER,
            NonAscii => &COLOR_NONASCII,
        }
    }

    pub fn as_char(self) -> char {
        use ByteCategory::*;

        match self.category() {

            /* hexyl uses 0 here, depending on color to distinguish */
            Null => '•',
            AsciiPrintable => self.0 as char,
            AsciiWhitespace if self.0 == 0x20 => ' ',
            AsciiWhitespace => '_',
            AsciiOther => '•',
            NonAscii => '×',
        }
    }
}

pub const COLOR_NULL: Color = Fixed(1);
pub const COLOR_ASCII_PRINTABLE: Color = Color::Cyan;
pub const COLOR_ASCII_WHITESPACE: Color = Color::Green;
pub const COLOR_ASCII_OTHER: Color = Color::Purple;
pub const COLOR_NONASCII: Color = Color::Yellow;


/// Per [XDG Base Directory Specification], dotfiles should go to
/// $XDG_CONFIG_HOME if it exists, and $HOME/.config if it doesn't.
///
/// [XDG Base Directory Specification]: https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
pub fn preferences_file_path() -> PathBuf {
    let xdg_config_home = env::var("XDG_CONFIG_HOME");
    let home = env::var("HOME");

    let edhex_s = String::from("edhex");
    let prefs_s = String::from("preferences");

    if xdg_config_home.is_ok() {
        let mut return_if_good = PathBuf::from(xdg_config_home.unwrap());

        /* Spec says it must be absolute or ignored */
        if return_if_good.is_absolute() {
            return_if_good.push(edhex_s);
            return_if_good.push(prefs_s);
            return return_if_good;
        }
    }

    let dotconf_s = String::from(".config");
    if home.is_ok() {
        [home.unwrap(), dotconf_s, edhex_s, prefs_s].iter().collect()
    }
    else {
        [".".to_owned(), dotconf_s, edhex_s, prefs_s].iter().collect()
    }
}


/// Per [XDG Base Directory Specification], state files should go to
/// $XDG_STATE_HOME if it exists, and $HOME/.local/state if it doesn't.
///
/// [XDG Base Directory Specification]: https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
pub fn state_file_path() -> PathBuf {
    let xdg_state_home = env::var("XDG_STATE_HOME");
    let home = env::var("HOME");

    let edhex_s = String::from("edhex");
    let state_s = String::from("state");

    if xdg_state_home.is_ok() {
        let mut return_if_good = PathBuf::from(xdg_state_home.unwrap());

        /* Spec says it must be absolute or ignored */
        if return_if_good.is_absolute() {
            return_if_good.push(edhex_s);
            return_if_good.push(state_s);
            return return_if_good;
        }
    }

    let dotlocal_s = String::from(".local");
    if home.is_ok() {
        [home.unwrap(), dotlocal_s, state_s, edhex_s].iter().collect()
    }
    else {
        [".".to_owned(), dotlocal_s, state_s, edhex_s].iter().collect()
    }
}


/// TODO Per https://doc.rust-lang.org/std/io/enum.ErrorKind.html
/// IsADirectory isn't available yet.  Check against it when it is.
pub fn is_a_regular_file(filename: &str) -> bool {
    let path = Path::new(filename);
    path.is_file()
}


pub fn path_exists(filename: &str) -> bool {
    let path = Path::new(filename);
    path.exists()
}


pub fn num_bytes_or_die(open_file: &Option<std::fs::File>) -> Result<usize, i32> {
    if open_file.is_none() {
        return Ok(0);
    }

    let metadata = open_file.as_ref().unwrap().metadata();
    match metadata {
        Ok(metadata) => {
            Ok(metadata.len() as usize)
        }
        Err(_) => {
            println!("Couldn't find file size");
            Err(2)
        }
    }
}


#[derive(Error, Debug)]
pub enum AllBytesFromFilenameError {
    #[error("Cannot read file")]
    FileCannotBeRead,
    #[error("File does not exist")]
    FileDoesNotExist,
    #[error("File is not a regular file")]
    NotARegularFile,
    #[error("Cannot read all bytes of file")]
    CantReadAllBytes,
}


pub fn all_bytes_from_filename(filename: &str)
        -> Result<Vec<u8>, AllBytesFromFilenameError> {

    /* As written right now, `file` always is Some */
    let file = match filehandle(filename) {
        Ok(Some(filehandle)) => {
            Some(filehandle)
        },
        Ok(None) => {
            return Err(AllBytesFromFilenameError::FileDoesNotExist);
        },
        Err(_) => {
            return Err(AllBytesFromFilenameError::FileCannotBeRead);
        }
    };

    let original_num_bytes = match num_bytes_or_die(&file) {
        Ok(num_bytes) => {
            num_bytes
        },
        Err(_) => {
            return Err(AllBytesFromFilenameError::FileCannotBeRead);
        }
    };

    /* Read all bytes into memory just like real ed */
    // TODO A real hex editor needs to buffer
    let mut all_bytes = Vec::new();
    if file.is_some() {
        match file.unwrap().read_to_end(&mut all_bytes) {
            Err(_) => {
                if path_exists(filename) {
                    if !is_a_regular_file(filename) {
                        Err(AllBytesFromFilenameError::NotARegularFile)
                    }
                    else {
                        Err(AllBytesFromFilenameError::FileCannotBeRead)
                    }
                }
                else {
                    Err(AllBytesFromFilenameError::FileDoesNotExist)
                }
            },
            Ok(num_bytes_read) => {
                if num_bytes_read != original_num_bytes {
                    Err(AllBytesFromFilenameError::CantReadAllBytes)
                }
                else {
                    Ok(all_bytes)
                }
            }
        }
    }
    else {
        Err(AllBytesFromFilenameError::FileDoesNotExist)
    }
}



/// This struct exists exclusively for serializing State's to disk without
/// including all_bytes.  If more entries end up in State that need to be
/// saved off, change this struct to reflect them.
///
/// Attempts to deserialize from one of these will cause you to notice
/// missing keys if State changes without you updating this.
#[derive(Serialize, Deserialize, Debug)]
pub struct StateSansBytes {
    pub prefs: Preferences,
    pub unsaved_changes: bool,
    pub filename: String,
    pub readonly: bool,
    pub last_search: Option<Vec<u8>>,
    pub index: usize,
    pub breaks: HashSet<usize>,
}


impl From<&State> for StateSansBytes {
    fn from(state: &State) -> Self {
        StateSansBytes {
            prefs: state.prefs.clone(),
            unsaved_changes: state.unsaved_changes,
            filename: state.filename.clone(),
            readonly: state.readonly,
            last_search: state.last_search.clone(),
            index: state.index,
            breaks: state.breaks.clone(),
        }
    }
}


impl From<&StateSansBytes> for State {
    fn from(state_sans_bytes: &StateSansBytes) -> Self {
        State {
            prefs: state_sans_bytes.prefs.clone(),
            unsaved_changes: state_sans_bytes.unsaved_changes,
            filename: state_sans_bytes.filename.clone(),
            readonly: state_sans_bytes.readonly,
            index: state_sans_bytes.index,
            last_search: state_sans_bytes.last_search.clone(),
            all_bytes: vec![],
            breaks: state_sans_bytes.breaks.clone(),
        }
    }
}


#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Preferences {
    pub radix: u32,
    pub show_byte_numbers: bool,
    pub show_chars: bool,
    pub show_prompt: bool,
    pub color: bool,
    pub width: NonZeroUsize,
    pub underline_main_line: bool,

    /* Spaces to put between a byte number and a byte when displaying */
    pub n_padding: String,

    /* Number of lines to print before current line */
    pub before_context: usize,

    /* Number of lines to print after current line */
    pub after_context: usize,
}


pub trait DiskWritable {
    fn write_to_disk(self, filename: &str) -> Result<(), String>;
}


impl DiskWritable for &Preferences {
    fn write_to_disk(self, filename: &str) -> Result<(), String> {
        let serialized = serde_json::to_string_pretty(&self);

        if serialized.is_err() {
            return Err("? Could not serialize preferences.".to_owned());
        }
        let serialized = serialized.unwrap();

        let result = std::fs::write(filename, &serialized);

        if result.is_err() {
            Err(format!("? Couldn't write to {}", filename))
        }
        else {
            Ok(())
        }
    }
}


impl Preferences {
    pub fn read_from_filename(filename: &str) -> Result<Preferences, String> {
        Self::read_from_path(Path::new(filename))
    }


    pub fn read_from_path(path: &Path) -> Result<Preferences, String> {
        if let Ok(from_disk) = fs::read_to_string(path) {
            serde_json::from_str(&from_disk).or_else(
                |_| Err(format!("Could not read preferences from {}",
                        path.display()))
            )
        }
        else {
            Err(format!("Couldn't read {}", path.display()))
        }
    }


    pub fn default() -> Self {
        Self {
            radix: 16,
            show_byte_numbers: true,
            show_prompt: true,
            color: true,
            show_chars: true,
            underline_main_line: true,
            before_context: 0,
            after_context: 0,
            width: NonZeroUsize::new(DEFAULT_WIDTH).unwrap(),
            // TODO calculate based on longest possible index
            n_padding: "      ".to_owned(),
        }
    }
}


pub struct State {
    pub prefs: Preferences,
    pub unsaved_changes: bool,
    pub filename: String,
    pub readonly: bool,
    pub last_search: Option<Vec<u8>>,

    /* Current byte number, 0 to (len - 1) */
    pub index: usize,

    /* The bytes in memory */
    pub all_bytes: Vec<u8>,

    /* Bytes at which to insert a break when displaying */
    pub breaks: HashSet<usize>,
}


pub fn lino(state:&State) -> String {
    hex_unless_dec_with_radix(state.index, state.prefs.radix)
}


pub fn string_from_radix(radix: u32) -> String {
    if radix == 10 {
        "decimal".to_owned()
    }
    else {
        "hex".to_owned()
    }
}


pub fn hex_unless_dec(number:usize, radix:u32) -> String {
    if radix == 10 {
        format!("{}", number)
    }
    else {
        format!("{:x}", number)
    }
}


pub fn hex_unless_dec_with_radix(number:usize, radix:u32) -> String {
    let letter = if radix == 10 {
        'd'
    }
    else {
        'x'
    };

    format!("0{}{}", letter, hex_unless_dec(number, radix))
}


impl fmt::Debug for State {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "radix: {}|unsaved_changes: {}|show_byte_numbers: {}|show_chars: {}|index: {}|width: {}|n_padding: '{}'|filename: {}|breaks: {:?}|underline_main_line: {}",
                self.prefs.radix, self.unsaved_changes, self.prefs.show_byte_numbers,
                self.prefs.show_chars, self.index, self.prefs.width, self.prefs.n_padding,
                self.filename, self.breaks, self.prefs.underline_main_line)
    }
}


impl DiskWritable for &State {
    /// Serialize to a json blob.
    /// Don't include all_bytes, not only because it could be huge, but
    /// because if you load a state from disk and its bytes differ from
    /// the actual file's on disk bytes, neither collection of bytes are
    /// canonical.  User's can write out bytes to other files at will.
    fn write_to_disk(self, filename: &str) -> Result<(), String> {

        /* NOTICE: To exclude all_bytes, we have to list all the keys
        *  we want to save.  There is no reasonable, general way to
        *  iterate through all keys in a struct.
        *  When State changes what you'd want to save off, you have to
        *  change what this function saves off, too. */
        let serialized = serde_json::to_string_pretty(&StateSansBytes::from(self));

        if serialized.is_err() {
            return Err("? Could not serialize state.".to_owned());
        }
        let serialized = serialized.unwrap();

        let result = std::fs::write(filename, &serialized);

        if result.is_err() {
            Err(format!("? Couldn't write to {}", filename))
        }
        else {
            Ok(())
        }
    }
}


impl State {
    pub fn pretty_color_state(&self) -> String {
        if self.prefs.color {
            format!("{}{}{}{}{}", Color::Red.paint("c"),
                    Color::Yellow.paint("o"), Color::Green.paint("l"),
                    Color::Blue.paint("o"), Color::Purple.paint("r"))
        }
        else {
            "color".to_owned()
        }
    }


    /// Return the byte numbers necessary for the left column of a display
    pub fn addresses(&self, from:usize) -> Vec<usize> {
        // TODO Do this with a generator once
        // those are supported in Rust
        let mut to_return:Vec<usize> = vec![];
        for i in (from..self.all_bytes.len()).step_by(usize::from(self.prefs.width)) {
            to_return.push(i);
        }
        to_return
    }


    pub fn read_from_filename(filename: &str) -> Result<Self, String> {
        Self::read_from_path(Path::new(filename))
    }


    /// Note:  For the forseeable future, from_reader is actually slower
    /// than drawing the entire file into memory.  So until that changes,
    /// doing the latter:  https://github.com/serde-rs/json/issues/160
    pub fn read_from_path(path: &Path) -> Result<Self, String> {
        let state_sans_bytes_s = fs::read_to_string(path);
        if state_sans_bytes_s.is_err() {
            return Err(format!("Problem opening '{}' ({:?})", path.display(),
                    state_sans_bytes_s));
        }
        let state_sans_bytes_s = state_sans_bytes_s.unwrap();
        let state_sans_bytes_r = serde_json::from_str(&state_sans_bytes_s);
        if state_sans_bytes_r.is_err() {
            return Err(format!("? {:?}", state_sans_bytes_r));
        }
        let state_sans_bytes: StateSansBytes = state_sans_bytes_r.unwrap();

        let all_bytes = all_bytes_from_filename(&state_sans_bytes.filename); 
        if all_bytes.is_ok() {
            let mut to_return = State::from(&state_sans_bytes);
            to_return.all_bytes = all_bytes.unwrap();
            Ok(to_return)
        }
        else {
            Err(format!(
                "State in file '{}' said to find the bytes in '{}', but
                    couldn't read '{}'.", path.display(), state_sans_bytes.filename,
                    state_sans_bytes.filename))
        }
    }


    /// Return the range `self.prefs.width` bytes starting at `address`.
    /// Could be cut short by hitting end of all bytes.
    /// Could be empty because `address` is past end of all bytes.
    pub fn bytes_range_from(&self, address:usize) -> std::ops::Range<usize> {
        let width = usize::from(self.prefs.width);
        if address < self.all_bytes.len() {
            let end_index = min(self.all_bytes.len(), address + width);
            address..end_index
        }
        else {
            0..0
        }
    }


    /// Print `self.prefs.width` bytes from `address` or cut off if at end of all bytes
    pub fn bytes_from(&self, address:usize) -> &[u8] {
        &self.all_bytes[self.bytes_range_from(address)]
    }


    pub fn bytes_from_current_row(&self) -> &[u8] {
        self.bytes_from(self.index)
    }


    pub fn current_row_string(&self) -> String {
        self.bytes_line(self.bytes_from_current_row(), 0, false)
    }


    /// Returns the line to print and the index of the last byte printed
    pub fn line_with_break(&self, begin:usize, end:usize, underline:bool)
        -> Option<(String, usize)> {
      if end < begin {
        return None;
      }

      let all_bytes_length = self.all_bytes.len();
      if all_bytes_length == 0 {
        return None;
      }
      if begin + 1 > all_bytes_length {
        return None;
      }

      let mut to_return = String::new();

      /* Address if present */
      if self.prefs.show_byte_numbers {
        to_return += &format!("{}|", &address_display(begin, self.prefs.radix,
            &self.prefs.n_padding, underline));
      }

      /* Bytes */

      /* First byte to print, ignore if it's a break byte.
      *  Guaranteed not to be off the edge because of length check above. */
      to_return += &formatted_byte(self.all_bytes[begin], self.prefs.color,
          underline);
      to_return += " ";
      let mut num_shown = 1;

      for index in (begin + 1)..min(end + 1, self.all_bytes.len()) {
        if (self.breaks.contains(&index)) ||
            ((num_shown + 1) > usize::from(self.prefs.width)) {
          break;
        }

        to_return += &formatted_byte(self.all_bytes[index], self.prefs.color,
            underline);
        to_return += " ";
        num_shown += 1;
      }

      /* Remove trailing space */
      to_return.pop();

      /* Pad for unprinted bytes */
      for _ in 0..(usize::from(self.prefs.width).saturating_sub(num_shown)) {
        to_return += "   ";
      }

      /* Chars */

      if self.prefs.show_chars {
        to_return += &format!("|   ");

        to_return += &formatted_char(self.all_bytes[begin], self.prefs.color,
            underline);
        let mut num_chars_shown = 1;

        for index in (begin + 1)..min(end + 1, self.all_bytes.len()) {
          if (self.breaks.contains(&index)) ||
              ((num_chars_shown + 1) > usize::from(self.prefs.width)) {
            break;
          }

          to_return += &formatted_char(self.all_bytes[index], self.prefs.color,
              underline);
          num_chars_shown += 1;
        }
      }

      Some((to_return, begin + num_shown - 1))
    }


    pub fn bytes_line(&self, bytes:&[u8], line_number:usize,
            underline:bool) -> String {
        let join_char = if underline {
            " "
        }
        else {
            " "
        };
        bytes_line_bytes(bytes, line_number, self.prefs.width).iter().map(|x| formatted_byte(*x, self.prefs.color, underline)).collect::<Vec<String>>().join(join_char)
    }


    // TODO Do this padding stuff format!  Unclear why previous attempts
    // have failed.
    pub fn bytes_line_padding(&self, bytes:&[u8], line_num:usize) -> String{
        let mut to_return = String::new();
        let expected_length = usize::from(self.prefs.width) * 3 - 1;
        let actual_length = bytes_line_bytes(bytes, line_num,
                self.prefs.width).len() * 3 - 1;
        for _ in actual_length..expected_length {
            to_return += " ";
        }

        to_return
    }


    /// Return the range for the bytes in the current row
    pub fn range_from_current_row(&self) ->
            Result<(usize, usize), String> {
        let last_index = self.last_byte_of_row_index();
        if last_index.is_err() {
            return Err(format!("{:?}", last_index));
        }
        Ok((self.index, last_index.unwrap()))
    }


    /// In current row, what's the index of the last byte
    /// to show?
    pub fn last_byte_of_row_index(&self) -> Result<usize, String> {
        let max = self.max_index();
        if max.is_err() {
            return Err(format!("{:?}", max));
        }
        let max = max.unwrap();

        Ok(min(max, self.index + usize::from(self.prefs.width) - 1))
    }


    pub fn print_bytes_and_move_index(&mut self) {
        if let Some(last_byte_index) = self.print_bytes() {
            if let Ok(max) = self.max_index() {
                let new_index = min(last_byte_index + 1, max);
                self.index = new_index;
            }
            else {
                println!("? (No bytes)");
            }
        }
        else {
            println!("? (unknown error)");
        }
    }


    pub fn index_of_byte_after(&self, index:usize) -> Option<usize> {
        let would_be = index + 1;
        if let Ok(max) = self.max_index() {
            if would_be > max {
                None
            }
            else {
                Some(would_be)
            }
        }
        else {
            None
        }
    }


    pub fn index_of_byte_before(&self, index:usize) -> Option<usize> {
        if index < 1 {
            None
        }
        else {
            Some(index - 1)
        }
    }


    pub fn index_of_prev_byte(&self) -> Option<usize> {
        self.index_of_byte_before(self.index)
    }


    pub fn index_of_next_byte(&self) -> Option<usize> {
        self.index_of_byte_after(self.index)
    }

    
    pub fn index_of_next_line(&self) -> Option<usize> {

        // TODO Replace this with direct calculation, then
        // call it inside line_with_break
        /* Calculate line_with_break only to get last_byte_index */
        if let Some((_, last_byte_index)) = self.line_with_break(self.index,
                self.all_bytes.len().saturating_sub(1), false) {
            if let Ok(max) = self.max_index() {
                Some(min(last_byte_index + 1, max))
            }
            else {
                None
            }
        }
        else {
            None
        }
    }


    pub fn move_index_then_print_bytes(&mut self) {
        if let Some(next_index) = self.index_of_next_line() {
            self.index = next_index;
            self.print_bytes();
        }
        else {
            println!("? No bytes after current line");
        }
    }


    pub fn before_context_lines(&self) -> Vec<String> {
        let mut before_lines = vec![];

        let prev_byte = self.index_of_prev_byte();
        if prev_byte.is_none() {
            return before_lines;
        }
        let prev_byte = prev_byte.unwrap();

        let mut cursor = self.index.saturating_sub(
                self.prefs.before_context * usize::from(self.prefs.width));
        loop {
            let last_byte_collected;

            if let Some((line, last_byte_index)) =
                self.line_with_break(cursor, prev_byte, false) {
                    before_lines.push(line);
                    last_byte_collected = Some(last_byte_index);
                }
            else {
                break;
            }

            if last_byte_collected.is_some() {
                if let Some(new_cursor) =
                        self.index_of_byte_after(last_byte_collected.unwrap()) {
                            cursor = new_cursor;
                        }
                else {
                    break;
                }
            }

        }

        before_lines
    }


    pub fn after_context_lines(&self, first_after_context_index:usize,
            max_index:usize) -> Vec<String> {
        let mut after_context_collected = 0;
        let mut to_return = vec![];

        let mut cursor = first_after_context_index;

        loop {
            let last_byte_collected =
                if let Some((line, last_byte_index)) =
                    self.line_with_break(cursor, max_index, false) {
                        if after_context_collected < self.prefs.after_context {
                            to_return.push(line);
                            after_context_collected += 1;
                        }
                        else {
                            break;
                        }
                        last_byte_index
                }
                else {
                    break;
                }
            ;
            cursor = if let Some(new_cursor) =
                    self.index_of_byte_after(last_byte_collected) {
                new_cursor
            }
            else {
                break;
            }
        }

        to_return
    }


    /// returns index of the last byte printed in the non-context line
    pub fn print_bytes(&self) -> Option<usize> {
        if self.empty() {
            return None;
        }

        let max_index = self.max_index();
        if max_index.is_err() {
            println!("? ({:?})", max_index);
            return None;
        }
        let max_index = max_index.unwrap();

        /* Gather up the main line underlined or quit */
        let (to_return, main_line) =
            if let Some((line, last_byte_index)) =
                self.line_with_break(self.index, max_index,
                        self.prefs.underline_main_line) {
                (last_byte_index, line)
            }
            else {
                return None;
            }
        ;

        /* Print before context lines */
        for before_context_line in self.before_context_lines() {
            println!("{}", before_context_line);
        }

        println!("{}", main_line);

        /* If there are after context lines, print them */
        if let Some(first_after_context_index) =
                self.index_of_byte_after(to_return) {
            for after_context_line in self.after_context_lines(
                    first_after_context_index, max_index) {
                println!("{}", after_context_line);
            }
        }

        return Some(to_return);
    }


    pub fn byte_indices_between(&self, range:(usize, usize)) ->
            Option<(usize, usize)> {
        if self.empty() {
            None
        }
        else if let Ok(max) = self.max_index() {
            if range.0 > max {
                None
            }
            else {
                Some((range.0, min(max, range.1)))
            }
        }
        else {
            None
        }
    }


    pub fn bytes_in_range(&self, range:(usize, usize)) -> Result<&[u8], String> {
        if self.empty() {
            return Ok(&[]);
        }

        let max = self.max_index();
        if max.is_err() {
            return Err(format!("? ({:?})", max));
        }
        let max = max.unwrap();

        let from = range.0;
        let to = min(max, range.1);
        if bad_range(&self.all_bytes, (from, to)) {
            return Err(format!("(Bad range: ({}, {}))", range.0, range.1));
        }

        Ok(&self.all_bytes[from..=to])
    }

    /// returns index of the first byte printed on the last line
    /// This is more primitive than `print_bytes`.  It just prints the bytes
    /// from the range.
    pub fn print_bytes_sans_context(&self, range:(usize, usize)) ->
            Option<usize> {
        if let Some(range) = self.byte_indices_between((range.0, range.1)) {
            let mut from = range.0;
            let mut last_from = range.0;
            loop {
                if let Some((line, last_byte_index)) = self.line_with_break(
                        from, range.1, false) {
                    println!("{}", line);
                    last_from = from;
                    from = last_byte_index + 1;
                }
                else {
                    break;
                }
            }
            Some(last_from)
        }
        else {
            None
        }
    }


    pub fn empty(&self) -> bool {
        self.all_bytes.len() == 0
    }

    pub fn range(&self) -> (usize, usize) {
        (self.index, self.index + usize::from(self.prefs.width) - 1)
    }

    pub fn max_index(&self) -> Result<usize, String> {
        if self.all_bytes.len() == 0 {
            Err("No bytes, so no max index.".to_owned())
        }
        else {
            Ok(self.all_bytes.len() - 1)
        }
    }
}


impl fmt::Display for State {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut to_write:String;
        to_write = "State:\n".to_owned();
        to_write += &format!("  Filename: {}\n", self.filename);
        to_write += &format!("  At byte {} of {}\n", lino(&self),
                hex_unless_dec_with_radix(self.all_bytes.len(), self.prefs.radix));
        if self.unsaved_changes {
            to_write += &format!("  Unwritten changes\n");
        }
        else {
            to_write += &format!("  No unwritten changes\n");
        }
        if self.readonly {
            to_write += &format!("  In read-only mode\n");
        }

        to_write += "  Preferences:\n";

        if self.prefs.show_byte_numbers {
            to_write += &format!("    Printing byte numbers in {}\n",
                string_from_radix(self.prefs.radix));
        };
        if self.prefs.show_chars {
            to_write +=
                    &format!("    Printing char representations after bytes\n");
        };
        to_write += &format!("    Interpreting input numbers as {}\n",
                string_from_radix(self.prefs.radix));
        to_write += &format!("    Printing a newline every {} bytes\n",
                hex_unless_dec_with_radix(usize::from(self.prefs.width),
                        self.prefs.radix));
        if self.prefs.underline_main_line {
            to_write += "    Underlining current line of bytes\n";
        }
        if self.prefs.before_context > 0 {
            to_write += &format!("    Printing {} lines before current line\n",
            hex_unless_dec_with_radix(self.prefs.before_context,
                    self.prefs.radix));
        };
        if self.prefs.after_context > 0 {
            to_write += &format!("    Printing {} lines after current line\n",
            hex_unless_dec_with_radix(self.prefs.after_context,
                    self.prefs.radix));
        };
        if self.prefs.color {
            to_write += &format!("    Using {}", self.pretty_color_state());
        }
        else {
            to_write += "    Printing without color";
        }

        write!(f, "{}", to_write)
    }
}


pub fn string_from_bytes(bytes:&[u8]) -> String {
    let mut to_return = "".to_owned();
    for &byte in bytes {
        to_return += &padded_byte(byte);
    }
    return to_return;
}


pub fn padded_byte(byte:u8) -> String {
    format!("{:02x}", byte)
}


pub fn index_of_bytes(needle:&[u8], haystack:&[u8], forward:bool) -> Option<usize> {
    let needle_num_bytes = if needle.len() == 0 {
        return None;
    }
    else {
        needle.len()
    };

    if forward {
        for index in 0..haystack.len() {
            let range = (index, index + needle_num_bytes - 1);

            if bad_range(&haystack.to_vec(), range) {
                return None;
            }

            if &haystack[range.0..=range.1] == needle {
                return Some(index);
            }
        }
    }
    else {
        let max_index = if needle_num_bytes <= haystack.len() {
            haystack.len() - needle_num_bytes
        }
        else {
            0
        };

        for index in (0..=max_index).rev() {
            let range = (index, index + needle_num_bytes - 1);

            if bad_range(&haystack.to_vec(), range) {
                return None;
            }


            let maybe = &haystack[range.0..=range.1];
            if maybe == needle {
                return Some(index);
            }
        }
    }

    None
}


pub fn bytes_from_string(nibbles_s:&str) -> Result<Vec<u8>, String> {
    // TODO Allow general whitespace, not just literal spaces
    let re_bytes = Regex::new(r"^ *([0-9a-fA-F][0-9a-fA-F] *)* *$").unwrap();
    if re_bytes.is_match(&nibbles_s) {
        let nibbles_v:Vec<String> = nibbles_s.replace(" ", "").chars().map(|x| x.to_string()).collect();
        Ok(nibbles_v.chunks(2).map(|x| x.join("")).map(|x| u8::from_str_radix(&x, 16).unwrap()).collect())
    }
    else {
        Err(format!("Couldn't interpret '{}' as a sequence of bytes", &nibbles_s))
    }
}


// TODO: This should take a usize..=usize range object
pub fn bad_range(bytes: &Vec<u8>, range: (usize, usize)) -> bool {
    bytes.len() == 0 || range.1 >= bytes.len()
}


/// Returns new index
pub fn move_to(state:&mut State, index:usize) -> Result<usize, String> {
    if state.empty() {
        Err("Empty file".to_owned())
    }
    else {
        let _max_index = match state.max_index() {
            Ok(max) => max,
            Err(error) => {
                return Err(error);
            },
        };

        if index > _max_index {
            Err(format!("{} > {} = maximum index", hex_unless_dec_with_radix(index, state.prefs.radix), hex_unless_dec_with_radix(_max_index, state.prefs.radix)))
        }
        else {
            state.index = index;
            Ok(index)
        }
    }
}


/// When printing [1, 2, 3, 4, 5, 6, 7] on a width of 3, the
/// maximum 0-up line number is 3.  This function returns that
/// calculation.  See test_max_bytes_line for examples
pub fn max_bytes_line_num(bytes:&[u8], width:NonZeroUsize) -> usize {
    if bytes.len() == 0 {
        0
    }
    else {
        (bytes.len() - 1) / usize::from(width)
    }
}


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

    #[test]
    fn test_bytes_from() {
        let hex_twelve = [
                0x00, 0x01, 0x02,
                0x03, 0x04, 0x05,
                0x06, 0x07, 0x08,
                0x09, 0x0a, 0x0b,
                0x0c, 0x0d, 0x0e,
                0x0f, 0x10, 0x11,
                0x12,
            ];
        let mut state = State {
            prefs: Preferences {
                radix: 16,
                show_byte_numbers: true,
                show_chars: true,
                show_prompt: true,
                underline_main_line: true,
                color: true,
                width: NonZeroUsize::new(0x10).unwrap(),
                n_padding: "   ".to_owned(),
                after_context: 0,
                before_context: 0,
            },
            unsaved_changes: true,
            index: 0,
            readonly: false,
            last_search: None,
            filename: "filename".to_owned(),
            all_bytes: Vec::from(hex_twelve),
            breaks: HashSet::new(),
        };

        assert_eq!(state.bytes_from(0), &hex_twelve[0x00..=0x0f]);
        assert_eq!(state.bytes_from(1), &hex_twelve[0x01..=0x10]);
        assert_eq!(state.bytes_from(2), &hex_twelve[0x02..=0x11]);
        assert_eq!(state.bytes_from(3), &hex_twelve[0x03..=0x12]);
        assert_eq!(state.bytes_from(4), &hex_twelve[0x04..=0x12]);
        assert_eq!(state.bytes_from(5), &hex_twelve[0x05..=0x12]);
        assert_eq!(state.bytes_from(6), &hex_twelve[0x06..=0x12]);
        assert_eq!(state.bytes_from(7), &hex_twelve[0x07..=0x12]);
        assert_eq!(state.bytes_from(11), &hex_twelve[0x0b..=0x12]);
        assert_eq!(state.bytes_from(17), &hex_twelve[0x11..=0x12]);
        assert_eq!(state.bytes_from(18), &hex_twelve[0x12..=0x12]);
        assert_eq!(state.bytes_from(19), &hex_twelve[0..0]);
        state.prefs.width = NonZeroUsize::new(3).unwrap();
        assert_eq!(state.bytes_from(0), &hex_twelve[0x00..=0x02]);
        assert_eq!(state.bytes_from(1), &hex_twelve[0x01..=0x03]);
        assert_eq!(state.bytes_from(11), &hex_twelve[0x0b..=0x0d]);
        assert_eq!(state.bytes_from(17), &hex_twelve[0x11..=0x12]);
        assert_eq!(state.bytes_from(18), &hex_twelve[0x12..=0x12]);
        assert_eq!(state.bytes_from(19), &hex_twelve[0..0]);
    }

    #[test]
    fn test_line_with_break() {
        let mut states = Vec::new();
        states.push(State {
            prefs: Preferences {
                underline_main_line: true,
                radix: 16,
                show_byte_numbers: true,
                show_chars: true,
                show_prompt: true,
                color: false,
                after_context: 0,
                before_context: 0,
                width: NonZeroUsize::new(0x10).unwrap(),
                n_padding: "   ".to_owned(),
            },
            unsaved_changes: true,
            readonly: false,
            last_search: None,
            filename: "filename".to_owned(),
            index: 0,
            breaks: HashSet::new(),
            all_bytes: vec![
                0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
                0x10, 0x11, 0x12,
            ],
        });

        assert_eq!(states[0].line_with_break(0x00, 0x00, false), Some(("    0   |00                                             |   •".to_owned(), 0x00)));
        assert_eq!(states[0].line_with_break(0x00, 0x01, false), Some(("    0   |00 01                                          |   ••".to_owned(), 0x01)));
        assert_eq!(states[0].line_with_break(0x00, 0x02, false), Some(("    0   |00 01 02                                       |   •••".to_owned(), 0x02)));
        assert_eq!(states[0].line_with_break(0x00, 0x03, false), Some(("    0   |00 01 02 03                                    |   ••••".to_owned(), 0x03)));
        assert_eq!(states[0].line_with_break(0x00, 0x04, false), Some(("    0   |00 01 02 03 04                                 |   •••••".to_owned(), 0x04)));
        assert_eq!(states[0].line_with_break(0x00, 0x05, false), Some(("    0   |00 01 02 03 04 05                              |   ••••••".to_owned(), 0x05)));
        assert_eq!(states[0].line_with_break(0x00, 0x06, false), Some(("    0   |00 01 02 03 04 05 06                           |   •••••••".to_owned(), 0x06)));
        assert_eq!(states[0].line_with_break(0x00, 0x07, false), Some(("    0   |00 01 02 03 04 05 06 07                        |   ••••••••".to_owned(), 0x07)));
        assert_eq!(states[0].line_with_break(0x00, 0x08, false), Some(("    0   |00 01 02 03 04 05 06 07 08                     |   •••••••••".to_owned(), 0x08)));
        assert_eq!(states[0].line_with_break(0x00, 0x09, false), Some(("    0   |00 01 02 03 04 05 06 07 08 09                  |   •••••••••_".to_owned(), 0x09)));
        assert_eq!(states[0].line_with_break(0x00, 0x0a, false), Some(("    0   |00 01 02 03 04 05 06 07 08 09 0a               |   •••••••••__".to_owned(), 0x0a)));
        assert_eq!(states[0].line_with_break(0x00, 0x0b, false), Some(("    0   |00 01 02 03 04 05 06 07 08 09 0a 0b            |   •••••••••__•".to_owned(), 0x0b)));
        assert_eq!(states[0].line_with_break(0x00, 0x0c, false), Some(("    0   |00 01 02 03 04 05 06 07 08 09 0a 0b 0c         |   •••••••••__•_".to_owned(), 0x0c)));
        assert_eq!(states[0].line_with_break(0x00, 0x0d, false), Some(("    0   |00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d      |   •••••••••__•__".to_owned(), 0x0d)));
        assert_eq!(states[0].line_with_break(0x00, 0x0e, false), Some(("    0   |00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e   |   •••••••••__•__•".to_owned(), 0x0e)));
        assert_eq!(states[0].line_with_break(0x00, 0x0f, false), Some(("    0   |00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f|   •••••••••__•__••".to_owned(), 0x0f)));
        assert_eq!(states[0].line_with_break(0x00, 0x10, false), Some(("    0   |00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f|   •••••••••__•__••".to_owned(), 0x0f)));
        assert_eq!(states[0].line_with_break(0x00, 0x11, false), Some(("    0   |00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f|   •••••••••__•__••".to_owned(), 0x0f)));
        assert_eq!(states[0].line_with_break(0x00, 0x12, false), Some(("    0   |00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f|   •••••••••__•__••".to_owned(), 0x0f)));

        /* too far */
        assert_eq!(states[0].line_with_break(0x00, 0x13, false), Some(("    0   |00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f|   •••••••••__•__••".to_owned(), 0x0f)));
        assert_eq!(states[0].line_with_break(0x00, 0x14, false), Some(("    0   |00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f|   •••••••••__•__••".to_owned(), 0x0f)));

        assert_eq!(states[0].line_with_break(0x01, 0x14, false), Some(("    1   |01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10|   ••••••••__•__•••".to_owned(), 0x10)));
        assert_eq!(states[0].line_with_break(0x01, 0x13, false), Some(("    1   |01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10|   ••••••••__•__•••".to_owned(), 0x10)));
        assert_eq!(states[0].line_with_break(0x01, 0x12, false), Some(("    1   |01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10|   ••••••••__•__•••".to_owned(), 0x10)));
        assert_eq!(states[0].line_with_break(0x01, 0x11, false), Some(("    1   |01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10|   ••••••••__•__•••".to_owned(), 0x10)));
        assert_eq!(states[0].line_with_break(0x01, 0x10, false), Some(("    1   |01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10|   ••••••••__•__•••".to_owned(), 0x10)));
        assert_eq!(states[0].line_with_break(0x01, 0x0f, false), Some(("    1   |01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f   |   ••••••••__•__••".to_owned(), 0x0f)));
        assert_eq!(states[0].line_with_break(0x01, 0x0e, false), Some(("    1   |01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e      |   ••••••••__•__•".to_owned(), 0x0e)));
        assert_eq!(states[0].line_with_break(0x01, 0x0d, false), Some(("    1   |01 02 03 04 05 06 07 08 09 0a 0b 0c 0d         |   ••••••••__•__".to_owned(), 0x0d)));
        assert_eq!(states[0].line_with_break(0x01, 0x0c, false), Some(("    1   |01 02 03 04 05 06 07 08 09 0a 0b 0c            |   ••••••••__•_".to_owned(), 0x0c)));
        assert_eq!(states[0].line_with_break(0x01, 0x0b, false), Some(("    1   |01 02 03 04 05 06 07 08 09 0a 0b               |   ••••••••__•".to_owned(), 0x0b)));
        assert_eq!(states[0].line_with_break(0x01, 0x0a, false), Some(("    1   |01 02 03 04 05 06 07 08 09 0a                  |   ••••••••__".to_owned(), 0x0a)));
        assert_eq!(states[0].line_with_break(0x01, 0x09, false), Some(("    1   |01 02 03 04 05 06 07 08 09                     |   ••••••••_".to_owned(), 0x09)));
        assert_eq!(states[0].line_with_break(0x01, 0x08, false), Some(("    1   |01 02 03 04 05 06 07 08                        |   ••••••••".to_owned(), 0x08)));
        assert_eq!(states[0].line_with_break(0x01, 0x07, false), Some(("    1   |01 02 03 04 05 06 07                           |   •••••••".to_owned(), 0x07)));
        assert_eq!(states[0].line_with_break(0x01, 0x06, false), Some(("    1   |01 02 03 04 05 06                              |   ••••••".to_owned(), 0x06)));
        assert_eq!(states[0].line_with_break(0x01, 0x05, false), Some(("    1   |01 02 03 04 05                                 |   •••••".to_owned(), 0x05)));
        assert_eq!(states[0].line_with_break(0x01, 0x04, false), Some(("    1   |01 02 03 04                                    |   ••••".to_owned(), 0x04)));
        assert_eq!(states[0].line_with_break(0x01, 0x03, false), Some(("    1   |01 02 03                                       |   •••".to_owned(), 0x03)));
        assert_eq!(states[0].line_with_break(0x01, 0x02, false), Some(("    1   |01 02                                          |   ••".to_owned(), 0x02)));
        assert_eq!(states[0].line_with_break(0x01, 0x01, false), Some(("    1   |01                                             |   •".to_owned(), 0x01)));
        assert_eq!(states[0].line_with_break(0x01, 0x00, false), None);

        assert_eq!(states[0].line_with_break(0x02, 0x14, false), Some(("    2   |02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11|   •••••••__•__••••".to_owned(), 0x11)));
        assert_eq!(states[0].line_with_break(0x02, 0x13, false), Some(("    2   |02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11|   •••••••__•__••••".to_owned(), 0x11)));
        assert_eq!(states[0].line_with_break(0x02, 0x12, false), Some(("    2   |02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11|   •••••••__•__••••".to_owned(), 0x11)));
        assert_eq!(states[0].line_with_break(0x02, 0x11, false), Some(("    2   |02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11|   •••••••__•__••••".to_owned(), 0x11)));
        assert_eq!(states[0].line_with_break(0x02, 0x10, false), Some(("    2   |02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10   |   •••••••__•__•••".to_owned(), 0x10)));
        assert_eq!(states[0].line_with_break(0x02, 0x0f, false), Some(("    2   |02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f      |   •••••••__•__••".to_owned(), 0x0f)));
        assert_eq!(states[0].line_with_break(0x02, 0x0e, false), Some(("    2   |02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e         |   •••••••__•__•".to_owned(), 0x0e)));
        assert_eq!(states[0].line_with_break(0x02, 0x0d, false), Some(("    2   |02 03 04 05 06 07 08 09 0a 0b 0c 0d            |   •••••••__•__".to_owned(), 0x0d)));
        assert_eq!(states[0].line_with_break(0x02, 0x0c, false), Some(("    2   |02 03 04 05 06 07 08 09 0a 0b 0c               |   •••••••__•_".to_owned(), 0x0c)));
        assert_eq!(states[0].line_with_break(0x02, 0x0b, false), Some(("    2   |02 03 04 05 06 07 08 09 0a 0b                  |   •••••••__•".to_owned(), 0x0b)));
        assert_eq!(states[0].line_with_break(0x02, 0x0a, false), Some(("    2   |02 03 04 05 06 07 08 09 0a                     |   •••••••__".to_owned(), 0x0a)));
        assert_eq!(states[0].line_with_break(0x02, 0x09, false), Some(("    2   |02 03 04 05 06 07 08 09                        |   •••••••_".to_owned(), 0x09)));
        assert_eq!(states[0].line_with_break(0x02, 0x08, false), Some(("    2   |02 03 04 05 06 07 08                           |   •••••••".to_owned(), 0x08)));
        assert_eq!(states[0].line_with_break(0x02, 0x07, false), Some(("    2   |02 03 04 05 06 07                              |   ••••••".to_owned(), 0x07)));
        assert_eq!(states[0].line_with_break(0x02, 0x06, false), Some(("    2   |02 03 04 05 06                                 |   •••••".to_owned(), 0x06)));
        assert_eq!(states[0].line_with_break(0x02, 0x05, false), Some(("    2   |02 03 04 05                                    |   ••••".to_owned(), 0x05)));
        assert_eq!(states[0].line_with_break(0x02, 0x04, false), Some(("    2   |02 03 04                                       |   •••".to_owned(), 0x04)));
        assert_eq!(states[0].line_with_break(0x02, 0x03, false), Some(("    2   |02 03                                          |   ••".to_owned(), 0x03)));
        assert_eq!(states[0].line_with_break(0x02, 0x02, false), Some(("    2   |02                                             |   •".to_owned(), 0x02)));
        assert_eq!(states[0].line_with_break(0x02, 0x01, false), None);
        assert_eq!(states[0].line_with_break(0x02, 0x00, false), None);

        assert_eq!(states[0].line_with_break(0x03, 0x14, false), Some(("    3   |03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12|   ••••••__•__•••••".to_owned(), 0x12)));
        assert_eq!(states[0].line_with_break(0x03, 0x13, false), Some(("    3   |03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12|   ••••••__•__•••••".to_owned(), 0x12)));
        assert_eq!(states[0].line_with_break(0x03, 0x12, false), Some(("    3   |03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12|   ••••••__•__•••••".to_owned(), 0x12)));
        assert_eq!(states[0].line_with_break(0x03, 0x11, false), Some(("    3   |03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11   |   ••••••__•__••••".to_owned(), 0x11)));
        assert_eq!(states[0].line_with_break(0x03, 0x10, false), Some(("    3   |03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10      |   ••••••__•__•••".to_owned(), 0x10)));
        assert_eq!(states[0].line_with_break(0x03, 0x0f, false), Some(("    3   |03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f         |   ••••••__•__••".to_owned(), 0x0f)));
        assert_eq!(states[0].line_with_break(0x03, 0x0e, false), Some(("    3   |03 04 05 06 07 08 09 0a 0b 0c 0d 0e            |   ••••••__•__•".to_owned(), 0x0e)));
        assert_eq!(states[0].line_with_break(0x03, 0x0d, false), Some(("    3   |03 04 05 06 07 08 09 0a 0b 0c 0d               |   ••••••__•__".to_owned(), 0x0d)));
        assert_eq!(states[0].line_with_break(0x03, 0x0c, false), Some(("    3   |03 04 05 06 07 08 09 0a 0b 0c                  |   ••••••__•_".to_owned(), 0x0c)));
        assert_eq!(states[0].line_with_break(0x03, 0x0b, false), Some(("    3   |03 04 05 06 07 08 09 0a 0b                     |   ••••••__•".to_owned(), 0x0b)));
        assert_eq!(states[0].line_with_break(0x03, 0x0a, false), Some(("    3   |03 04 05 06 07 08 09 0a                        |   ••••••__".to_owned(), 0x0a)));
        assert_eq!(states[0].line_with_break(0x03, 0x09, false), Some(("    3   |03 04 05 06 07 08 09                           |   ••••••_".to_owned(), 0x09)));
        assert_eq!(states[0].line_with_break(0x03, 0x08, false), Some(("    3   |03 04 05 06 07 08                              |   ••••••".to_owned(), 0x08)));
        assert_eq!(states[0].line_with_break(0x03, 0x07, false), Some(("    3   |03 04 05 06 07                                 |   •••••".to_owned(), 0x07)));
        assert_eq!(states[0].line_with_break(0x03, 0x06, false), Some(("    3   |03 04 05 06                                    |   ••••".to_owned(), 0x06)));
        assert_eq!(states[0].line_with_break(0x03, 0x05, false), Some(("    3   |03 04 05                                       |   •••".to_owned(), 0x05)));
        assert_eq!(states[0].line_with_break(0x03, 0x04, false), Some(("    3   |03 04                                          |   ••".to_owned(), 0x04)));
        assert_eq!(states[0].line_with_break(0x03, 0x03, false), Some(("    3   |03                                             |   •".to_owned(), 0x03)));
        assert_eq!(states[0].line_with_break(0x03, 0x02, false), None);
        assert_eq!(states[0].line_with_break(0x03, 0x01, false), None);
        assert_eq!(states[0].line_with_break(0x03, 0x00, false), None);

        assert_eq!(states[0].line_with_break(0x04, 0x14, false), Some(("    4   |04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12   |   •••••__•__•••••".to_owned(), 0x12)));
        assert_eq!(states[0].line_with_break(0x04, 0x13, false), Some(("    4   |04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12   |   •••••__•__•••••".to_owned(), 0x12)));
        assert_eq!(states[0].line_with_break(0x04, 0x12, false), Some(("    4   |04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12   |   •••••__•__•••••".to_owned(), 0x12)));
        assert_eq!(states[0].line_with_break(0x04, 0x11, false), Some(("    4   |04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11      |   •••••__•__••••".to_owned(), 0x11)));
        assert_eq!(states[0].line_with_break(0x04, 0x10, false), Some(("    4   |04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10         |   •••••__•__•••".to_owned(), 0x10)));
        assert_eq!(states[0].line_with_break(0x04, 0x0f, false), Some(("    4   |04 05 06 07 08 09 0a 0b 0c 0d 0e 0f            |   •••••__•__••".to_owned(), 0x0f)));
        assert_eq!(states[0].line_with_break(0x04, 0x0e, false), Some(("    4   |04 05 06 07 08 09 0a 0b 0c 0d 0e               |   •••••__•__•".to_owned(), 0x0e)));
        assert_eq!(states[0].line_with_break(0x04, 0x0d, false), Some(("    4   |04 05 06 07 08 09 0a 0b 0c 0d                  |   •••••__•__".to_owned(), 0x0d)));
        assert_eq!(states[0].line_with_break(0x04, 0x0c, false), Some(("    4   |04 05 06 07 08 09 0a 0b 0c                     |   •••••__•_".to_owned(), 0x0c)));
        assert_eq!(states[0].line_with_break(0x04, 0x0b, false), Some(("    4   |04 05 06 07 08 09 0a 0b                        |   •••••__•".to_owned(), 0x0b)));
        assert_eq!(states[0].line_with_break(0x04, 0x0a, false), Some(("    4   |04 05 06 07 08 09 0a                           |   •••••__".to_owned(), 0x0a)));
        assert_eq!(states[0].line_with_break(0x04, 0x09, false), Some(("    4   |04 05 06 07 08 09                              |   •••••_".to_owned(), 0x09)));
        assert_eq!(states[0].line_with_break(0x04, 0x08, false), Some(("    4   |04 05 06 07 08                                 |   •••••".to_owned(), 0x08)));
        assert_eq!(states[0].line_with_break(0x04, 0x07, false), Some(("    4   |04 05 06 07                                    |   ••••".to_owned(), 0x07)));
        assert_eq!(states[0].line_with_break(0x04, 0x06, false), Some(("    4   |04 05 06                                       |   •••".to_owned(), 0x06)));
        assert_eq!(states[0].line_with_break(0x04, 0x05, false), Some(("    4   |04 05                                          |   ••".to_owned(), 0x05)));
        assert_eq!(states[0].line_with_break(0x04, 0x04, false), Some(("    4   |04                                             |   •".to_owned(), 0x04)));
        assert_eq!(states[0].line_with_break(0x04, 0x03, false), None);
        assert_eq!(states[0].line_with_break(0x04, 0x02, false), None);
        assert_eq!(states[0].line_with_break(0x04, 0x01, false), None);
        assert_eq!(states[0].line_with_break(0x04, 0x00, false), None);

        assert_eq!(states[0].line_with_break(0x05, 0x14, false), Some(("    5   |05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12      |   ••••__•__•••••".to_owned(), 0x12)));
        assert_eq!(states[0].line_with_break(0x05, 0x13, false), Some(("    5   |05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12      |   ••••__•__•••••".to_owned(), 0x12)));
        assert_eq!(states[0].line_with_break(0x05, 0x12, false), Some(("    5   |05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12      |   ••••__•__•••••".to_owned(), 0x12)));
        assert_eq!(states[0].line_with_break(0x05, 0x11, false), Some(("    5   |05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11         |   ••••__•__••••".to_owned(), 0x11)));
        assert_eq!(states[0].line_with_break(0x05, 0x10, false), Some(("    5   |05 06 07 08 09 0a 0b 0c 0d 0e 0f 10            |   ••••__•__•••".to_owned(), 0x10)));
        assert_eq!(states[0].line_with_break(0x05, 0x0f, false), Some(("    5   |05 06 07 08 09 0a 0b 0c 0d 0e 0f               |   ••••__•__••".to_owned(), 0x0f)));
        assert_eq!(states[0].line_with_break(0x05, 0x0e, false), Some(("    5   |05 06 07 08 09 0a 0b 0c 0d 0e                  |   ••••__•__•".to_owned(), 0x0e)));
        assert_eq!(states[0].line_with_break(0x05, 0x0d, false), Some(("    5   |05 06 07 08 09 0a 0b 0c 0d                     |   ••••__•__".to_owned(), 0x0d)));
        assert_eq!(states[0].line_with_break(0x05, 0x0c, false), Some(("    5   |05 06 07 08 09 0a 0b 0c                        |   ••••__•_".to_owned(), 0x0c)));
        assert_eq!(states[0].line_with_break(0x05, 0x0b, false), Some(("    5   |05 06 07 08 09 0a 0b                           |   ••••__•".to_owned(), 0x0b)));
        assert_eq!(states[0].line_with_break(0x05, 0x0a, false), Some(("    5   |05 06 07 08 09 0a                              |   ••••__".to_owned(), 0x0a)));
        assert_eq!(states[0].line_with_break(0x05, 0x09, false), Some(("    5   |05 06 07 08 09                                 |   ••••_".to_owned(), 0x09)));
        assert_eq!(states[0].line_with_break(0x05, 0x08, false), Some(("    5   |05 06 07 08                                    |   ••••".to_owned(), 0x08)));
        assert_eq!(states[0].line_with_break(0x05, 0x07, false), Some(("    5   |05 06 07                                       |   •••".to_owned(), 0x07)));
        assert_eq!(states[0].line_with_break(0x05, 0x06, false), Some(("    5   |05 06                                          |   ••".to_owned(), 0x06)));
        assert_eq!(states[0].line_with_break(0x05, 0x05, false), Some(("    5   |05                                             |   •".to_owned(), 0x05)));
        assert_eq!(states[0].line_with_break(0x05, 0x04, false), None);
        assert_eq!(states[0].line_with_break(0x05, 0x03, false), None);
        assert_eq!(states[0].line_with_break(0x05, 0x02, false), None);
        assert_eq!(states[0].line_with_break(0x05, 0x01, false), None);
        assert_eq!(states[0].line_with_break(0x05, 0x00, false), None);

        assert_eq!(states[0].line_with_break(0x06, 0x14, false), Some(("    6   |06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12         |   •••__•__•••••".to_owned(), 0x12)));
        assert_eq!(states[0].line_with_break(0x06, 0x13, false), Some(("    6   |06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12         |   •••__•__•••••".to_owned(), 0x12)));
        assert_eq!(states[0].line_with_break(0x06, 0x12, false), Some(("    6   |06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12         |   •••__•__•••••".to_owned(), 0x12)));
        assert_eq!(states[0].line_with_break(0x06, 0x11, false), Some(("    6   |06 07 08 09 0a 0b 0c 0d 0e 0f 10 11            |   •••__•__••••".to_owned(), 0x11)));
        assert_eq!(states[0].line_with_break(0x06, 0x10, false), Some(("    6   |06 07 08 09 0a 0b 0c 0d 0e 0f 10               |   •••__•__•••".to_owned(), 0x10)));
        assert_eq!(states[0].line_with_break(0x06, 0x0f, false), Some(("    6   |06 07 08 09 0a 0b 0c 0d 0e 0f                  |   •••__•__••".to_owned(), 0x0f)));
        assert_eq!(states[0].line_with_break(0x06, 0x0e, false), Some(("    6   |06 07 08 09 0a 0b 0c 0d 0e                     |   •••__•__•".to_owned(), 0x0e)));
        assert_eq!(states[0].line_with_break(0x06, 0x0d, false), Some(("    6   |06 07 08 09 0a 0b 0c 0d                        |   •••__•__".to_owned(), 0x0d)));
        assert_eq!(states[0].line_with_break(0x06, 0x0c, false), Some(("    6   |06 07 08 09 0a 0b 0c                           |   •••__•_".to_owned(), 0x0c)));
        assert_eq!(states[0].line_with_break(0x06, 0x0b, false), Some(("    6   |06 07 08 09 0a 0b                              |   •••__•".to_owned(), 0x0b)));
        assert_eq!(states[0].line_with_break(0x06, 0x0a, false), Some(("    6   |06 07 08 09 0a                                 |   •••__".to_owned(), 0x0a)));
        assert_eq!(states[0].line_with_break(0x06, 0x09, false), Some(("    6   |06 07 08 09                                    |   •••_".to_owned(), 0x09)));
        assert_eq!(states[0].line_with_break(0x06, 0x08, false), Some(("    6   |06 07 08                                       |   •••".to_owned(), 0x08)));
        assert_eq!(states[0].line_with_break(0x06, 0x07, false), Some(("    6   |06 07                                          |   ••".to_owned(), 0x07)));
        assert_eq!(states[0].line_with_break(0x06, 0x06, false), Some(("    6   |06                                             |   •".to_owned(), 0x06)));
        assert_eq!(states[0].line_with_break(0x06, 0x05, false), None);
        assert_eq!(states[0].line_with_break(0x06, 0x04, false), None);
        assert_eq!(states[0].line_with_break(0x06, 0x03, false), None);
        assert_eq!(states[0].line_with_break(0x06, 0x02, false), None);
        assert_eq!(states[0].line_with_break(0x06, 0x01, false), None);
        assert_eq!(states[0].line_with_break(0x06, 0x00, false), None);

        assert_eq!(states[0].line_with_break(0x10, 0x14, false), Some(("   10   |10 11 12                                       |   •••".to_owned(), 0x12)));
        assert_eq!(states[0].line_with_break(0x10, 0x13, false), Some(("   10   |10 11 12                                       |   •••".to_owned(), 0x12)));
        assert_eq!(states[0].line_with_break(0x10, 0x12, false), Some(("   10   |10 11 12                                       |   •••".to_owned(), 0x12)));
        assert_eq!(states[0].line_with_break(0x10, 0x11, false), Some(("   10   |10 11                                          |   ••".to_owned(), 0x11)));
        assert_eq!(states[0].line_with_break(0x10, 0x10, false), Some(("   10   |10                                             |   •".to_owned(), 0x10)));
        assert_eq!(states[0].line_with_break(0x10, 0x0f, false), None);
        assert_eq!(states[0].line_with_break(0x10, 0x0e, false), None);
        assert_eq!(states[0].line_with_break(0x10, 0x0d, false), None);
        assert_eq!(states[0].line_with_break(0x10, 0x0c, false), None);
        assert_eq!(states[0].line_with_break(0x10, 0x0b, false), None);
        assert_eq!(states[0].line_with_break(0x10, 0x0a, false), None);
        assert_eq!(states[0].line_with_break(0x10, 0x09, false), None);
        assert_eq!(states[0].line_with_break(0x10, 0x08, false), None);
        assert_eq!(states[0].line_with_break(0x10, 0x07, false), None);
        assert_eq!(states[0].line_with_break(0x10, 0x06, false), None);
        assert_eq!(states[0].line_with_break(0x10, 0x05, false), None);
        assert_eq!(states[0].line_with_break(0x10, 0x04, false), None);
        assert_eq!(states[0].line_with_break(0x10, 0x03, false), None);
        assert_eq!(states[0].line_with_break(0x10, 0x02, false), None);
        assert_eq!(states[0].line_with_break(0x10, 0x01, false), None);
        assert_eq!(states[0].line_with_break(0x10, 0x00, false), None);

        assert_eq!(states[0].line_with_break(0x11, 0x14, false), Some(("   11   |11 12                                          |   ••".to_owned(), 0x12)));
        assert_eq!(states[0].line_with_break(0x11, 0x13, false), Some(("   11   |11 12                                          |   ••".to_owned(), 0x12)));
        assert_eq!(states[0].line_with_break(0x11, 0x12, false), Some(("   11   |11 12                                          |   ••".to_owned(), 0x12)));
        assert_eq!(states[0].line_with_break(0x11, 0x11, false), Some(("   11   |11                                             |   •".to_owned(), 0x11)));
        assert_eq!(states[0].line_with_break(0x11, 0x10, false), None);
        assert_eq!(states[0].line_with_break(0x11, 0x0f, false), None);
        assert_eq!(states[0].line_with_break(0x11, 0x0e, false), None);
        assert_eq!(states[0].line_with_break(0x11, 0x0d, false), None);
        assert_eq!(states[0].line_with_break(0x11, 0x0c, false), None);
        assert_eq!(states[0].line_with_break(0x11, 0x0b, false), None);
        assert_eq!(states[0].line_with_break(0x11, 0x0a, false), None);
        assert_eq!(states[0].line_with_break(0x11, 0x09, false), None);
        assert_eq!(states[0].line_with_break(0x11, 0x08, false), None);
        assert_eq!(states[0].line_with_break(0x11, 0x07, false), None);
        assert_eq!(states[0].line_with_break(0x11, 0x06, false), None);
        assert_eq!(states[0].line_with_break(0x11, 0x05, false), None);
        assert_eq!(states[0].line_with_break(0x11, 0x04, false), None);
        assert_eq!(states[0].line_with_break(0x11, 0x03, false), None);
        assert_eq!(states[0].line_with_break(0x11, 0x02, false), None);
        assert_eq!(states[0].line_with_break(0x11, 0x01, false), None);
        assert_eq!(states[0].line_with_break(0x11, 0x00, false), None);

        assert_eq!(states[0].line_with_break(0x12, 0x14, false), Some(("   12   |12                                             |   •".to_owned(), 0x12)));
        assert_eq!(states[0].line_with_break(0x12, 0x13, false), Some(("   12   |12                                             |   •".to_owned(), 0x12)));
        assert_eq!(states[0].line_with_break(0x12, 0x12, false), Some(("   12   |12                                             |   •".to_owned(), 0x12)));
        assert_eq!(states[0].line_with_break(0x12, 0x11, false), None);
        assert_eq!(states[0].line_with_break(0x12, 0x10, false), None);
        assert_eq!(states[0].line_with_break(0x12, 0x0f, false), None);
        assert_eq!(states[0].line_with_break(0x12, 0x0e, false), None);
        assert_eq!(states[0].line_with_break(0x12, 0x0d, false), None);
        assert_eq!(states[0].line_with_break(0x12, 0x0c, false), None);
        assert_eq!(states[0].line_with_break(0x12, 0x0b, false), None);
        assert_eq!(states[0].line_with_break(0x12, 0x0a, false), None);
        assert_eq!(states[0].line_with_break(0x12, 0x09, false), None);
        assert_eq!(states[0].line_with_break(0x12, 0x08, false), None);
        assert_eq!(states[0].line_with_break(0x12, 0x07, false), None);
        assert_eq!(states[0].line_with_break(0x12, 0x06, false), None);
        assert_eq!(states[0].line_with_break(0x12, 0x05, false), None);
        assert_eq!(states[0].line_with_break(0x12, 0x04, false), None);
        assert_eq!(states[0].line_with_break(0x12, 0x03, false), None);
        assert_eq!(states[0].line_with_break(0x12, 0x02, false), None);
        assert_eq!(states[0].line_with_break(0x12, 0x01, false), None);
        assert_eq!(states[0].line_with_break(0x12, 0x00, false), None);

        assert_eq!(states[0].line_with_break(0x13, 0x14, false), None);
        assert_eq!(states[0].line_with_break(0x13, 0x13, false), None);
        assert_eq!(states[0].line_with_break(0x13, 0x12, false), None);
        assert_eq!(states[0].line_with_break(0x13, 0x11, false), None);
        assert_eq!(states[0].line_with_break(0x13, 0x10, false), None);
        assert_eq!(states[0].line_with_break(0x13, 0x0f, false), None);
        assert_eq!(states[0].line_with_break(0x13, 0x0e, false), None);
        assert_eq!(states[0].line_with_break(0x13, 0x0d, false), None);
        assert_eq!(states[0].line_with_break(0x13, 0x0c, false), None);
        assert_eq!(states[0].line_with_break(0x13, 0x0b, false), None);
        assert_eq!(states[0].line_with_break(0x13, 0x0a, false), None);
        assert_eq!(states[0].line_with_break(0x13, 0x09, false), None);
        assert_eq!(states[0].line_with_break(0x13, 0x08, false), None);
        assert_eq!(states[0].line_with_break(0x13, 0x07, false), None);
        assert_eq!(states[0].line_with_break(0x13, 0x06, false), None);
        assert_eq!(states[0].line_with_break(0x13, 0x05, false), None);
        assert_eq!(states[0].line_with_break(0x13, 0x04, false), None);
        assert_eq!(states[0].line_with_break(0x13, 0x03, false), None);
        assert_eq!(states[0].line_with_break(0x13, 0x02, false), None);
        assert_eq!(states[0].line_with_break(0x13, 0x01, false), None);
        assert_eq!(states[0].line_with_break(0x13, 0x00, false), None);

        assert_eq!(states[0].line_with_break(0x14, 0x14, false), None);
        assert_eq!(states[0].line_with_break(0x14, 0x13, false), None);

        states.push(State {
            prefs: Preferences {
                radix: 16,
                show_byte_numbers: true,
                underline_main_line: true,
                show_chars: true,
                show_prompt: true,
                color: false,
                after_context: 0,
                before_context: 0,
                width: NonZeroUsize::new(0x10).unwrap(),
                n_padding: "   ".to_owned(),
            },
            unsaved_changes: true,
            readonly: false,
            last_search: None,
            filename: "filename".to_owned(),
            index: 0,
            breaks: HashSet::from([3, 8]),
            all_bytes: vec![
                0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
                0x10, 0x11, 0x12,
            ],
        });

        assert_eq!(states[1].line_with_break(0x00, 0x00, false), Some(("    0   |00                                             |   •".to_owned(), 0x00)));
        assert_eq!(states[1].line_with_break(0x00, 0x01, false), Some(("    0   |00 01                                          |   ••".to_owned(), 0x01)));
        assert_eq!(states[1].line_with_break(0x00, 0x02, false), Some(("    0   |00 01 02                                       |   •••".to_owned(), 0x02)));
        assert_eq!(states[1].line_with_break(0x00, 0x03, false), Some(("    0   |00 01 02                                       |   •••".to_owned(), 0x02)));
        assert_eq!(states[1].line_with_break(0x00, 0x04, false), Some(("    0   |00 01 02                                       |   •••".to_owned(), 0x02)));
        assert_eq!(states[1].line_with_break(0x00, 0x100, false), Some(("    0   |00 01 02                                       |   •••".to_owned(), 0x02)));

        assert_eq!(states[1].line_with_break(0x01, 0x0a, false), Some(("    1   |01 02                                          |   ••".to_owned(), 0x02)));
        assert_eq!(states[1].line_with_break(0x02, 0x0a, false), Some(("    2   |02                                             |   •".to_owned(), 0x02)));
        assert_eq!(states[1].line_with_break(0x03, 0x0a, false), Some(("    3   |03 04 05 06 07                                 |   •••••".to_owned(), 0x07)));
        assert_eq!(states[1].line_with_break(0x04, 0x0a, false), Some(("    4   |04 05 06 07                                    |   ••••".to_owned(), 0x07)));
        assert_eq!(states[1].line_with_break(0x05, 0x0a, false), Some(("    5   |05 06 07                                       |   •••".to_owned(), 0x07)));
        assert_eq!(states[1].line_with_break(0x06, 0x0a, false), Some(("    6   |06 07                                          |   ••".to_owned(), 0x07)));
        assert_eq!(states[1].line_with_break(0x07, 0x0a, false), Some(("    7   |07                                             |   •".to_owned(), 0x07)));
        assert_eq!(states[1].line_with_break(0x08, 0x0a, false), Some(("    8   |08 09 0a                                       |   •__".to_owned(), 0x0a)));
        assert_eq!(states[1].line_with_break(0x08, 0x100, false), Some(("    8   |08 09 0a 0b 0c 0d 0e 0f 10 11 12               |   •__•__•••••".to_owned(), 0x12)));
    }


    #[test]
    fn test_byte_numbers() {
        let mut state = State {
            prefs: Preferences {
                underline_main_line: true,
                radix: 16,
                show_byte_numbers: true,
                show_chars: true,
                show_prompt: true,
                color: true,
                after_context: 0,
                before_context: 0,
                width: NonZeroUsize::new(0x10).unwrap(),
                n_padding: "   ".to_owned(),
            },
            unsaved_changes: true,
            readonly: false,
            last_search: None,
            filename: "filename".to_owned(),
            index: 0,
            breaks: HashSet::new(),
            all_bytes: vec![
                0x00, 0x01, 0x02,
                0x03, 0x04, 0x05,
                0x06, 0x07, 0x08,
                0x09, 0x0a, 0x0b,
                0x0c, 0x0d, 0x0e,
                0x0f, 0x10, 0x11,
                0x12,
            ],
        };
        assert_eq!(state.addresses(0x00),
            vec![0x00, 0x10]);
        assert_eq!(state.addresses(0x01),
            vec![0x01, 0x11]);
        assert_eq!(state.addresses(0x04),
            vec![0x04]);
        state.prefs.width = NonZeroUsize::new(3).unwrap();
        assert_eq!(state.addresses(0x04),
            vec![0x04, 0x07, 0x0a, 0x0d, 0x10,]);
    }

    #[test]
    fn test_max_bytes_line() {
        let _1 = NonZeroUsize::new(1).unwrap();
        let _2 = NonZeroUsize::new(2).unwrap();
        let _3 = NonZeroUsize::new(3).unwrap();
        let _4 = NonZeroUsize::new(4).unwrap();
        let _5 = NonZeroUsize::new(5).unwrap();
        let _6 = NonZeroUsize::new(6).unwrap();
        let _7 = NonZeroUsize::new(7).unwrap();
        let _8 = NonZeroUsize::new(8).unwrap();
        let bytes = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
        assert_eq!(max_bytes_line_num(&bytes, _1), 12);
        let bytes = vec![8, 6, 7, 5, 3, 0, 9,];
        assert_eq!(max_bytes_line_num(&bytes, _1), 6);
        assert_eq!(max_bytes_line_num(&bytes, _2), 3);
        assert_eq!(max_bytes_line_num(&bytes, _3), 2);
        assert_eq!(max_bytes_line_num(&bytes, _4), 1);
        assert_eq!(max_bytes_line_num(&bytes, _5), 1);
        assert_eq!(max_bytes_line_num(&bytes, _6), 1);
        assert_eq!(max_bytes_line_num(&bytes, _7), 0);
        assert_eq!(max_bytes_line_num(&bytes, _8), 0);
        let bytes = vec![8, 6, 7, 5, 3, 0,];
        assert_eq!(max_bytes_line_num(&bytes, _1), 5);
        assert_eq!(max_bytes_line_num(&bytes, _2), 2);
        assert_eq!(max_bytes_line_num(&bytes, _3), 1);
        assert_eq!(max_bytes_line_num(&bytes, _4), 1);
        assert_eq!(max_bytes_line_num(&bytes, _5), 1);
        assert_eq!(max_bytes_line_num(&bytes, _6), 0);
        assert_eq!(max_bytes_line_num(&bytes, _7), 0);
        assert_eq!(max_bytes_line_num(&bytes, _8), 0);
        let bytes = vec![8, 6, 7,];
        assert_eq!(max_bytes_line_num(&bytes, _1), 2);
        assert_eq!(max_bytes_line_num(&bytes, _2), 1);
        assert_eq!(max_bytes_line_num(&bytes, _3), 0);
        assert_eq!(max_bytes_line_num(&bytes, _4), 0);
        assert_eq!(max_bytes_line_num(&bytes, _5), 0);
        let bytes = vec![8, 6,];
        assert_eq!(max_bytes_line_num(&bytes, _1), 1);
        assert_eq!(max_bytes_line_num(&bytes, _2), 0);
        assert_eq!(max_bytes_line_num(&bytes, _3), 0);
        assert_eq!(max_bytes_line_num(&bytes, _4), 0);
        let bytes = vec![8,];
        assert_eq!(max_bytes_line_num(&bytes, _1), 0);
        assert_eq!(max_bytes_line_num(&bytes, _2), 0);
        assert_eq!(max_bytes_line_num(&bytes, _3), 0);
        assert_eq!(max_bytes_line_num(&bytes, _4), 0);
        let bytes = vec![];
        assert_eq!(max_bytes_line_num(&bytes, _1), 0);
        assert_eq!(max_bytes_line_num(&bytes, _2), 0);
        assert_eq!(max_bytes_line_num(&bytes, _3), 0);
        assert_eq!(max_bytes_line_num(&bytes, _4), 0);
    }



    #[test]
    fn test_padded_byte() {
        assert_eq!(padded_byte(2), "02");
        assert_eq!(padded_byte(10), "0a");
    }

    #[test]
    fn test_index_of_bytes() {
        let haystack = vec![0xde, 0xad, 0xbe, 0xef];
        assert_eq!(index_of_bytes(&vec![], &haystack, true), None);
        assert_eq!(index_of_bytes(&vec![0xad, 0xbe], &haystack, true), Some(1));
        assert_eq!(index_of_bytes(&vec![0xad, 0xbe, 0xef], &haystack, true), Some(1));
        assert_eq!(index_of_bytes(&vec![0xad, 0xbe, 0xef, 0xef], &haystack, true), None);
        assert_eq!(index_of_bytes(&vec![0xde,], &haystack, true), Some(0));
    }


    #[test]
    fn test_num_graphemes() {
        assert_eq!(num_graphemes("hey, there"), 10);
        assert_eq!(num_graphemes("दीपक"), 3);
        assert_eq!(num_graphemes("ﷺ"), 1);
        assert_eq!(num_graphemes("père"), 4);
    }


    #[test]
    fn test_bytes_line() {
        let bytes = vec![];
        let _1 = NonZeroUsize::new(1).unwrap();
        let _2 = NonZeroUsize::new(2).unwrap();
        let _3 = NonZeroUsize::new(3).unwrap();
        let _4 = NonZeroUsize::new(4).unwrap();
        let _5 = NonZeroUsize::new(5).unwrap();
        let _6 = NonZeroUsize::new(6).unwrap();
        let _7 = NonZeroUsize::new(7).unwrap();
        let _8 = NonZeroUsize::new(8).unwrap();
        let _empty: Vec<u8> = vec![];
        assert_eq!(bytes_line_bytes(&bytes, 0, _1).to_owned(), _empty);
        assert_eq!(bytes_line_bytes(&bytes, 0, _2).to_owned(), _empty);
        assert_eq!(bytes_line_bytes(&bytes, 1, _1).to_owned(), _empty);
        assert_eq!(bytes_line_bytes(&bytes, 1, _2).to_owned(), _empty);
        assert_eq!(bytes_line_bytes(&bytes, 2, _1).to_owned(), _empty);
        assert_eq!(bytes_line_bytes(&bytes, 2, _2).to_owned(), _empty);
        let bytes = vec![8, 6, 7, 5, 3, 0, 9,];
        assert_eq!(bytes_line_bytes(&bytes, 0, _1).to_owned(), vec![8,]);
        assert_eq!(bytes_line_bytes(&bytes, 1, _1).to_owned(), vec![6,]);
        assert_eq!(bytes_line_bytes(&bytes, 2, _1).to_owned(), vec![7,]);
        assert_eq!(bytes_line_bytes(&bytes, 3, _1).to_owned(), vec![5,]);
        assert_eq!(bytes_line_bytes(&bytes, 4, _1).to_owned(), vec![3,]);
        assert_eq!(bytes_line_bytes(&bytes, 5, _1).to_owned(), vec![0,]);
        assert_eq!(bytes_line_bytes(&bytes, 6, _1).to_owned(), vec![9,]);
        assert_eq!(bytes_line_bytes(&bytes, 7, _1).to_owned(), _empty);
        assert_eq!(bytes_line_bytes(&bytes, 8, _1).to_owned(), _empty);
        assert_eq!(bytes_line_bytes(&bytes, 9, _1).to_owned(), _empty);
        assert_eq!(bytes_line_bytes(&bytes, 0, _2).to_owned(), vec![8, 6,]);
        assert_eq!(bytes_line_bytes(&bytes, 1, _2).to_owned(), vec![7, 5,]);
        assert_eq!(bytes_line_bytes(&bytes, 2, _2).to_owned(), vec![3, 0,]);
        assert_eq!(bytes_line_bytes(&bytes, 3, _2).to_owned(), vec![9,]);
        assert_eq!(bytes_line_bytes(&bytes, 4, _2).to_owned(), _empty);
        assert_eq!(bytes_line_bytes(&bytes, 5, _2).to_owned(), _empty);
        assert_eq!(bytes_line_bytes(&bytes, 0, _3).to_owned(), vec![8, 6, 7,]);
        assert_eq!(bytes_line_bytes(&bytes, 1, _3).to_owned(), vec![5, 3, 0,]);
        assert_eq!(bytes_line_bytes(&bytes, 2, _3).to_owned(), vec![9,]);
        assert_eq!(bytes_line_bytes(&bytes, 3, _3).to_owned(), _empty);
        assert_eq!(bytes_line_bytes(&bytes, 4, _3).to_owned(), _empty);
        assert_eq!(bytes_line_bytes(&bytes, 0, _4).to_owned(), vec![8, 6, 7, 5,]);
        assert_eq!(bytes_line_bytes(&bytes, 1, _4).to_owned(), vec![3, 0, 9,]);
        assert_eq!(bytes_line_bytes(&bytes, 2, _4).to_owned(), _empty);
        assert_eq!(bytes_line_bytes(&bytes, 3, _4).to_owned(), _empty);
        assert_eq!(bytes_line_bytes(&bytes, 4, _4).to_owned(), _empty);
        assert_eq!(bytes_line_bytes(&bytes, 0, _5).to_owned(), vec![8, 6, 7, 5, 3,]);
        assert_eq!(bytes_line_bytes(&bytes, 1, _5).to_owned(), vec![0, 9,]);
        assert_eq!(bytes_line_bytes(&bytes, 2, _5).to_owned(), _empty);
        assert_eq!(bytes_line_bytes(&bytes, 3, _5).to_owned(), _empty);
        assert_eq!(bytes_line_bytes(&bytes, 0, _6).to_owned(), vec![8, 6, 7, 5, 3, 0,]);
        assert_eq!(bytes_line_bytes(&bytes, 1, _6).to_owned(), vec![9,]);
        assert_eq!(bytes_line_bytes(&bytes, 2, _6).to_owned(), _empty);
        assert_eq!(bytes_line_bytes(&bytes, 3, _6).to_owned(), _empty);
        assert_eq!(bytes_line_bytes(&bytes, 0, _7).to_owned(), vec![8, 6, 7, 5, 3, 0, 9,]);
        assert_eq!(bytes_line_bytes(&bytes, 1, _7).to_owned(), _empty);
        assert_eq!(bytes_line_bytes(&bytes, 2, _7).to_owned(), _empty);
        assert_eq!(bytes_line_bytes(&bytes, 3, _7).to_owned(), _empty);
        assert_eq!(bytes_line_bytes(&bytes, 0, _8).to_owned(), vec![8, 6, 7, 5, 3, 0, 9,]);
        assert_eq!(bytes_line_bytes(&bytes, 1, _8).to_owned(), _empty);
        assert_eq!(bytes_line_bytes(&bytes, 2, _8).to_owned(), _empty);
        assert_eq!(bytes_line_bytes(&bytes, 3, _8).to_owned(), _empty);
    }
}


pub fn bytes_line_range(bytes:&[u8], line_number:usize, width:NonZeroUsize) -> std::ops::Range<usize> {
    let width = usize::from(width);
    if line_number * width < bytes.len() {
        let end_index = min(bytes.len(), line_number * width + width);
        line_number * width..end_index
    }
    else {
        0..0
    }
}


pub fn bytes_line_bytes(bytes:&[u8], line_number:usize, width:NonZeroUsize) -> &[u8] {
    &bytes[bytes_line_range(bytes, line_number, width)]
}


pub fn chars_line_chars(bytes:&[u8], line_number:usize, width:NonZeroUsize) -> Vec<char> {
    let mut to_return:Vec<char> = vec![];
    for index in bytes_line_range(bytes, line_number, width) {
        to_return.push(chared_byte(bytes[index]));
    }

    to_return
}


pub fn colored_chared_bytes(bytes:&[u8], line_number:usize, width:NonZeroUsize,
        underline:bool) -> Vec<String> {
    let mut to_return:Vec<String> = vec![];
    for index in bytes_line_range(bytes, line_number, width) {
            to_return.push(String::from(colored_chared_byte(bytes[index], underline)));
    }

    to_return
}


pub fn chared_bytes(bytes:&[u8], line_number:usize, width:NonZeroUsize) -> Vec<char> {
    let mut to_return:Vec<char> = vec![];
    for index in bytes_line_range(bytes, line_number, width) {
        to_return.push(chared_byte(bytes[index]));
    }

    to_return
}


pub fn chars_line(bytes:&[u8], line_number:usize, width:NonZeroUsize,
        color:bool, underline:bool) -> String {
    let mut to_return:String = "".to_owned();
    if color {
        for colored_char in colored_chared_bytes(bytes, line_number, width,
                underline) {
            to_return += &colored_char;
        }
    }
    else {
        for chared in chared_bytes(bytes, line_number, width) {
            to_return += &chared.to_string();
        }
    }

    to_return
}


fn formatted_byte(byte:u8, color:bool, underline:bool) -> String {
    if color {
        if underline {
            Byte(byte).color().underline().paint(padded_byte(byte)).to_string()
        }
        else {
            Byte(byte).color().paint(padded_byte(byte)).to_string()
        }
    }
    else {
        padded_byte(byte)
    }
}


fn formatted_char(byte:u8, color:bool, underline:bool) -> String {
  if color {
    colored_chared_byte(byte, underline)
  }
  else {
    chared_byte(byte).to_string()
  }
}


fn colored_chared_byte(byte:u8, underline: bool) -> String {
    if underline {
        Byte(byte).color().underline().paint(String::from(Byte(byte).as_char())).to_string()
    }
    else {
        Byte(byte).color().paint(String::from(Byte(byte).as_char())).to_string()
    }
}


pub fn chared_byte(byte:u8) -> char {
    Byte(byte).as_char()
}


/// .len gives the number of bytes
/// .chars.count() gives the number of characters (which counts è as two characters.
/// The human concept is unicode "graphemes" or "glyphs" defined to be what
/// think they are.
pub fn num_graphemes(unicode_string: &str) -> usize {
    return unicode_string.graphemes(true).count();
}


pub fn cargo_version() -> Result<String, String> {
    if let Some(version) = option_env!("CARGO_PKG_VERSION") {
        return Ok(String::from(version));
    }
    return Err("Version unknown (not compiled with cargo)".to_string());
}


pub fn address_display(address: usize, radix:u32, padding:&str,
        underline:bool) -> String {
    let address = if radix == 10 {
        format!("{:>5}", address)
    }
    else {
        format!("{:>5x}", address)
    };

    let address = if underline {
        format!("{}", Style::new().underline().paint(address))
    }
    else {
        format!("{}", address)
    };

    format!("{}{}", address, padding)
}


pub fn filehandle(filename:&str) -> Result<Option<File>, String> {
    match File::open(filename) {
        Ok(filehandle) => {
            Ok(Some(filehandle))
        },
        Err(error) => {
            if error.kind() == std::io::ErrorKind::NotFound {
                Ok(None)
            }
            else {
                Err(format!("Error opening '{}'", filename))
            }
        },
    }
}


pub fn get_input_or_die() -> Result<String, i32> {
    let mut input = String::new();
    match io::stdin().read_line(&mut input) {
        Ok(_num_bytes) => {

            /* EOF Return error of 0 to indicate time for a clean exit.  */
            if _num_bytes == 0 {
                Err(0)
            }
            else {
                Ok(input.trim().to_string())
            }
        }
        Err(_) => {
            println!("Unable to read input");
            Err(3)
        }
    }
}


pub fn read_string_from_user(prompt: Option<&str>) -> Result<String, String> {
    print!("{}", if prompt.is_none() {
            "> "
        }
        else {
            prompt.unwrap()
        }
    );

    io::stdout().flush().unwrap();
    let result = get_input_or_die();

    if result.is_ok() {
        Ok(result.unwrap())
    }

    /* Consider EOF empty string */
    else if result == Err(0) {
        Ok("".to_owned())
    }

    else {
        Err("Couldn't read input from user".to_owned())
    }
}


pub fn save_to_path_or_default<T: DiskWritable>(to_be_saved: T, prompt: &str,
        default_path: PathBuf) {
    let filename = read_string_from_user(Some(&format!(
            "{} [{}]: ", prompt, default_path.display())));

    if filename.is_ok() {
        let mut filename = filename.unwrap();
        if filename == "" {
            if let Some(default_path_s) = default_path.to_str() {
                filename = default_path_s.to_owned();

                /* In the default case, we're brave enough to create
                 * the parent directory for the file if it's not root */
                if let Some(parent_dir) = default_path.parent() {
                    if let Err(error) = fs::create_dir_all(parent_dir) {
                        println!("? Couldn't create director {} ({:?})",
                                parent_dir.display(), error);
                    }
                }
            }
            else {
                println!("? Default path ({}) is not valid unicode.",
                        default_path.display());
                return;
            }
        }

        let result = to_be_saved.write_to_disk(&filename);
        if let Err(error) = result {
            println!("? {:?}", error);
        }
    }
    else {
        println!("? {:?}", filename);
    }
}