libreda-oasis 0.0.3

OASIS input/output for libreda-db.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
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
/*
 * Copyright (c) 2018-2021 Thomas Kramer.
 *
 * This file is part of LibrEDA 
 * (see https://codeberg.org/libreda/libreda-oasis).
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
//! Collection of constants and commonly used functions.

extern crate libreda_db as db;

use num_traits::Zero;

use std::fmt;
use std::io::{Read, Write};
use byteorder::{LittleEndian, WriteBytesExt, ReadBytesExt};
use std::convert::TryFrom;

pub use db::layout::types::{UInt, SInt};
use db::layout::prelude::*;


pub const MAGIC: &[u8] = "%SEMI-OASIS\r\n".as_bytes();

/// Standard property names.
pub const _S_GDS_PROPERTY_NAME: &str = "S_GDS_PROPERTY";
pub const _S_CELL_OFFSET_NAME: &str = "S_CELL_OFFSET";
pub const _S_MAX_SIGNED_INTEGER_WIDTH_NAME: &str = "S_MAX_SIGNED_INTEGER_WIDTH";
pub const _S_MAX_UNSIGNED_INTEGER_WIDTH_NAME: &str = "S_MAX_UNSIGNED_INTEGER_WIDTH";
pub const _S_TOP_CELL_NAME: &str = "S_TOP_CELL";
pub const _S_BOUNDING_BOXES_AVAILABLE_NAME: &str = "S_BOUNDING_BOXES_AVAILABLE";
pub const _S_BOUNDING_BOX_NAME: &str = "S_BOUNDING_BOX";


/// Convert bit strings into byte strings.
/// Bit strings must be the bit representation
/// as used in the OASIS specification.
/// This is used only for tests.
#[cfg(test)]
fn bits(bit_string: &str) -> Vec<u8> {
    bit_string.split_ascii_whitespace()
        .map(|s| u8::from_str_radix(s, 2).unwrap())
        .collect()
}

/// Shorthand notation for creating byte strings from the bit representation
/// as used in the OASIS specification.
/// This is used only for tests.
#[cfg(test)]
macro_rules! bits {
 ($x:expr) => {&mut bits($x)[..].as_ref()}
}

#[derive(Debug)]
pub enum OASISReadError {
    IOError(std::io::Error),
    /// Undefined OASIS format error.
    FormatError,
    WrongVersionString,
    InvalidResolution(Real),
    NameStringEmpty,
    NameStringNotAscii,
    UnexpectedRecord(UInt),
    MixedImplExplCellnameModes,
    MixedImplExplPropnameModes,
    MixedImplExplTextstringModes,
    MixedImplExplPropstringModes,
    CellnameIdAlreadyPresent(UInt),
    CellnameAlreadyPresent(String),
    PropnameIdAlreadyPresent(UInt),
    TextStringAlreadyPresent(UInt),
    PropStringAlreadyPresent(UInt),
    PropStringIdNotFound(UInt),
    TextStringIdNotFound(UInt),
    CellnameIdNotFound(UInt),
    CellNotFound(String),
    NoImplicitTextStringDefined,
    ModalTextTypeDefined,
    ModalTextLayerDefined,
    ModalRepetitionNotDefined,
    NoImplicitLayerDefined,
    NoImplicitDataTypeDefined,
    HeightIsPresentForSquare,
    NoCellRecordPresent,
    ModalGeometryWNotDefined,
    ModalGeometryHNotDefined,
    ModalLastPropertyNameNotDefined,
    ModalLastValueListNotDefined,
    ModalPolygonPointListNotDefined,
    ModalPathPointListNotDefined,
    ModalPathHalfWidthNotDefined,
    ModalPathStartExtensionNotDefined,
    ModalPathEndExtensionNotDefined,
    ModalPlacementCellNotDefined,
    IllegalRepetitionType(UInt),
    IllegalIntervalType(UInt),
    UnknownValidationScheme(UInt),
    UnresolvedForwardReferences(Vec<UInt>),
    UnexpectedEndOfFile,
}

impl fmt::Display for OASISReadError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use OASISReadError::*;
        match self {
            MixedImplExplCellnameModes => write!(f, "Implicit and explicit CELLNAME modes cannot be mixed."),
            CellnameIdAlreadyPresent(id) => write!(f, "CELLNAME record with ID={} is already present.", id),
            PropnameIdAlreadyPresent(id) => write!(f, "PROPNAME record with ID={} is already present.", id),
            TextStringAlreadyPresent(id) => write!(f, "TEXSTRING record with ID={} is already present.", id),
            PropStringAlreadyPresent(id) => write!(f, "PROPSTRING record with ID={} is already present.", id),
            PropStringIdNotFound(id) => write!(f, "No PROPSTRING declared for property with ID {}.", id),
            CellnameIdNotFound(id) => write!(f, "No CELLNAME declared for cell with ID {}.", id),
            TextStringIdNotFound(id) => write!(f, "No TEXTSTRING declared for TEXT with ID {}.", id),
            other => other.fmt(f)
        }
    }
}

/// Error types for writing OASIS.
#[derive(Debug)]
pub enum OASISWriteError {
    IOError(std::io::Error),
    FormatError,
    NameStringEmpty,
    NameStringNotAscii,
    DbuIsZero,
}

impl fmt::Display for OASISWriteError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use OASISWriteError::*;
        match self {
            DbuIsZero => write!(f, "Data base unit (dbu) must not be zero."),
            NameStringEmpty => write!(f, "Name string cannot be empty."),
            NameStringNotAscii => write!(f, "Name string cannot contain non-ascii characters."),
            FormatError => write!(f, "Unspecified OASIS write error."),
            other => other.fmt(f)
        }
    }
}

impl From<std::io::Error> for OASISReadError {
    fn from(err: std::io::Error) -> Self {
        match err.kind() {
            std::io::ErrorKind::UnexpectedEof => OASISReadError::UnexpectedEndOfFile,
            _ => OASISReadError::IOError(err)
        }
    }
}

impl From<std::io::Error> for OASISWriteError {
    fn from(err: std::io::Error) -> Self {
        match err.kind() {
            _ => OASISWriteError::IOError(err)
        }
    }
}

/// Read the magic string at the beginning of the OASIS file.
/// Returns an error if the magic value is wrong.
pub fn read_magic<R: Read>(reader: &mut R) -> Result<(), OASISReadError> {
    // Read the magic string.
    let mut buf = [0u8; MAGIC.len()];
    reader.read_exact(&mut buf)?;

    // Compare the buffer with the magic string.
    match buf.as_ref() {
        MAGIC => Ok(()), // Matic string is correct.
        _ => {
            let s = String::from_utf8_lossy(&buf);
            log::error!("Wrong file format because OASIS magic string is wrong: '{:?}', hex = '{:02x?}'", s, buf);
            Err(OASISReadError::FormatError)
        } // Magic string is wrong.
    }
}

/// Write the magic string at the beginning of the OASIS file.
pub fn write_magic<W: Write>(writer: &mut W) -> Result<(), OASISWriteError> {
    writer.write_all(MAGIC)?;
    Ok(())
}

#[test]
fn test_write_read_magic() {
    let mut buf = Vec::new();
    write_magic(&mut buf).unwrap();
    assert_eq!(buf.len(), 13);
    assert!(read_magic(&mut buf.as_slice()).is_ok())
}

/// Read a 8-bit integer.
pub fn read_byte<R: Read>(reader: &mut R) -> Result<u8, OASISReadError> {
    Ok(reader.read_u8()?)
}

/// Write a 8-bit integer.
pub fn write_byte<W: Write>(writer: &mut W, b: u8) -> Result<(), OASISWriteError> {
    writer.write_u8(b)?;
    Ok(())
}

/// Read an unsigned integer.
/// Unsigned integers are stored as variable-length byte continuations.
/// The all but last bytes of the continuation have the MSB set to one.
/// The result is the concatenation of the 7 lower-value bits.
/// The low-order byte appears first.
pub fn read_unsigned_integer<R: Read>(reader: &mut R) -> Result<UInt, OASISReadError> {
    // Read byte continuation until the most significant bit is zero.
    let mut bytes = Vec::new();
    for b in reader.bytes() {
        let b = b?;
        bytes.push(b);
        if b & 0x80 == 0 {
            break;
        }
    }
    if bytes.last().map(|b| b & 0x80) != Some(0) { // Last byte must have MSB set to zero.
        // Reached EOF.
        Err(OASISReadError::UnexpectedEndOfFile)
    } else {
        Ok(
            bytes.iter()
                .rev()
                .map(|b| b & 0x7f) // Set MSB to zero.
                .fold(0, |acc, b| b as UInt + (acc << 7))
        )
    }
}


#[test]
fn test_read_unsigned_integer() {
    // Test values from OASIS specification draft.
    assert_eq!(read_unsigned_integer(bits!("00000000")).unwrap(), 0);
    assert_eq!(read_unsigned_integer(bits!("01111111")).unwrap(), 127);
    assert_eq!(read_unsigned_integer(bits!("10000000 00000001")).unwrap(), 128);
    assert_eq!(read_unsigned_integer(bits!("11111111 01111111")).unwrap(), 16383);
    assert_eq!(read_unsigned_integer(bits!("10000000 10000000 00000001")).unwrap(), 16384);

    // Empty bytes should raise an error.
    assert!(read_unsigned_integer(bits!("")).is_err());
    // The last byte must always have the MSB set to zero.
    assert!(read_unsigned_integer(bits!("10000000")).is_err());
}

/// Write an unsigned integer.
/// Unsigned integers are stored as variable-length byte continuations.
/// The all but last bytes of the continuation have the MSB set to one.
/// The result is the concatenation of the 7 lower-value bits.
/// The low-order byte appears first.
pub fn write_unsigned_integer<W: Write>(writer: &mut W, value: UInt) -> Result<(), OASISWriteError> {
    let mut value = value;

    while value > 0x7f {
        let lowest = (value & 0x7f) as u8;
        writer.write_u8(0x80 | lowest)?; // Set the MSB.
        value >>= 7;
    }
    debug_assert_eq!(value & 0x80, 0);
    writer.write_u8(value as u8)?;
    Ok(())
}


#[test]
fn test_write_unsigned_integer() {
    // Test values from OASIS specification draft.

    fn test(num: UInt, expected: Vec<u8>) {
        let mut buf = Vec::new();
        write_unsigned_integer(&mut buf, num).unwrap();
        assert_eq!(buf, expected);
    }

    test(0, vec![0x00]);
    test(1, vec![0x01]);
    test(127, vec![0x7f]);
    test(128, vec![0x80, 0x01]);
    test(16383, vec![0xff, 0x7f]);
    test(16384, vec![0x80, 0x80, 0x01]);
}


/// Read a signed integer.
/// The format is the same as for unsigned integers except that the sign bit
/// is stored in the LSB of the lowest-order byte.
pub fn read_signed_integer<R: Read>(reader: &mut R) -> Result<SInt, OASISReadError> {
    let u = read_unsigned_integer(reader)?;
    let sign = u & 0x1;
    let magnitude = (u >> 1) as SInt;
    Ok(match sign {
        1 => -magnitude,
        _ => magnitude
    })
}

#[test]
fn test_read_signed_integer() {
    // Test values from OASIS specification draft.
    assert_eq!(read_signed_integer(bits!("00")).unwrap(), 0);
    assert_eq!(read_signed_integer(bits!("10")).unwrap(), 1);
    assert_eq!(read_signed_integer(bits!("11")).unwrap(), -1);
    assert_eq!(read_signed_integer(bits!("01111110")).unwrap(), 63);
    assert_eq!(read_signed_integer(bits!("10000001 00000001")).unwrap(), -64);
    assert_eq!(read_signed_integer(bits!("11111110 01111111")).unwrap(), 8191);
    assert_eq!(read_signed_integer(bits!("10000001 10000000 00000001")).unwrap(), -8192);

    // Empty bytes should raise an error.
    assert!(read_signed_integer(bits!("")).is_err());
    // The last byte must always have the MSB set to zero.
    assert!(read_signed_integer(bits!("10000000")).is_err());
}

/// Write a signed integer.
/// The format is the same as for unsigned integers except that the sign bit
/// is stored in the LSB of the lowest-order byte.
pub fn write_signed_integer<W: Write>(writer: &mut W, value: SInt) -> Result<(), OASISWriteError> {
    // Determine the sign bit.
    let (sign, value) = if value < 0 {
        (1, -value)
    } else {
        (0, value)
    };

    // Insert the sign bit at the lowest value bit position.
    let magnitude = (value << 1) as UInt;
    let u = magnitude | sign;

    write_unsigned_integer(writer, u)
}

#[test]
fn test_write_signed_integer() {
    // Test values from OASIS specification draft.

    fn test(num: SInt, expected: Vec<u8>) {
        let mut buf = Vec::new();
        write_signed_integer(&mut buf, num).unwrap();
        assert_eq!(buf, expected);
    }

    test(0, vec![0x00]);
    test(1, vec![0b10]);
    test(-1, vec![0b11]);
    test(63, vec![0b01111110]);
    test(-64, vec![0x81, 0x01]);
    test(8191, vec![0b11111110, 0b01111111]);
    test(-8192, vec![0b10000001, 0b10000000, 0b1]);
}

#[derive(PartialEq, Copy, Clone, Debug)]
pub enum Real {
    PositiveWholeNumber(UInt),
    NegativeWholeNumber(UInt),
    PositiveReciprocal(UInt),
    NegativeReciprocal(UInt),
    PositiveRatio(UInt, UInt),
    NegativeRatio(UInt, UInt),
    IEEEFloat32(f32),
    IEEEFloat64(f64),
}

impl Real {
    /// Convert a `Real` into an approximate floating point value.
    pub fn to_f64(self) -> f64 {
        use Real::*;
        match self {
            PositiveWholeNumber(n) => n as f64,
            NegativeWholeNumber(n) => -(n as f64),
            PositiveReciprocal(n) => 1. / (n as f64),
            NegativeReciprocal(n) => -1. / (n as f64),
            PositiveRatio(a, b) => (a as f64) / (b as f64),
            NegativeRatio(a, b) => -(a as f64) / (b as f64),
            IEEEFloat32(f) => f as f64,
            IEEEFloat64(f) => f
        }
    }

    /// Convert the number into a integer if it actually is an integral value.
    /// Floats are casted to int if their fractional part is zero.
    /// Otherwise `None` is returned.
    pub fn try_to_int(self) -> Option<SInt> {
        use Real::*;
        match self {
            PositiveWholeNumber(n) => Some(n as SInt),
            NegativeWholeNumber(n) => Some(-(n as SInt)),
            PositiveRatio(n, 1) => Some(n as SInt),
            NegativeRatio(n, 1) => Some(-(n as SInt)),
            PositiveReciprocal(1) => Some(1),
            NegativeReciprocal(1) => Some(-1),
            IEEEFloat32(f) => {
                if f.fract() == 0. {
                    Some(f as SInt)
                } else {
                    None
                }
            }
            IEEEFloat64(f) => {
                if f.fract() == 0. {
                    Some(f as SInt)
                } else {
                    None
                }
            }
            _ => None
        }
    }

    /// Tell if this number is an integral number.
    pub fn is_integral(&self) -> bool {
        use Real::*;
        match self {
            PositiveWholeNumber(_) | NegativeWholeNumber(_) => true,
            _ => false
        }
    }

    /// Tell if this number is a rational number.
    pub fn is_rational(&self) -> bool {
        use Real::*;
        match self {
            IEEEFloat32(_) | IEEEFloat64(_) => false,
            _ => true
        }
    }
}

#[test]
fn test_convert_reals() {
    debug_assert_eq!(Real::PositiveWholeNumber(2).to_f64(), 2.0);
    debug_assert_eq!(Real::NegativeWholeNumber(2).to_f64(), -2.0);
    debug_assert_eq!(Real::PositiveReciprocal(2).to_f64(), 0.5);
    debug_assert_eq!(Real::NegativeReciprocal(2).to_f64(), -0.5);
    debug_assert_eq!(Real::PositiveRatio(2, 4).to_f64(), 0.5);
    debug_assert_eq!(Real::NegativeRatio(2, 4).to_f64(), -0.5);
    debug_assert_eq!(Real::IEEEFloat32(0.5f32).to_f64(), 0.5f64);
    debug_assert_eq!(Real::IEEEFloat64(0.5f64).to_f64(), 0.5f64);
}

/// Read a real number if the type ID is already known.
pub fn read_real_without_type<R: Read>(reader: &mut R, type_id: UInt) -> Result<Real, OASISReadError> {
    match type_id {
        0 => Ok(Real::PositiveWholeNumber(read_unsigned_integer(reader)?)),
        1 => Ok(Real::NegativeWholeNumber(read_unsigned_integer(reader)?)),
        2 => Ok(Real::PositiveReciprocal(read_unsigned_integer(reader)?)),
        3 => Ok(Real::NegativeReciprocal(read_unsigned_integer(reader)?)),
        4 => {
            let nom = read_unsigned_integer(reader)?;
            let denom = read_unsigned_integer(reader)?;
            if denom == 0 {
                // A denominator = 0 is a fatal error.
                log::error!("Denominator of a positive ratio is 0 (ratio = {}/{}).", nom, denom);
                Err(OASISReadError::FormatError) // TODO More specific error.
            } else {
                Ok(Real::PositiveRatio(nom, denom))
            }
        }
        5 => {
            let nom = read_unsigned_integer(reader)?;
            let denom = read_unsigned_integer(reader)?;
            if denom == 0 {
                // A denominator = 0 is a fatal error.
                log::error!("Denominator of a negative ratio is 0 (ratio = {}/{}).", nom, denom);
                Err(OASISReadError::FormatError) // TODO More specific error.
            } else {
                Ok(Real::NegativeRatio(nom, denom))
            }
        }
        6 => Ok(Real::IEEEFloat32(reader.read_f32::<LittleEndian>()?)),
        7 => Ok(Real::IEEEFloat64(reader.read_f64::<LittleEndian>()?)),
        _ => Err(OASISReadError::FormatError) // TODO: More precise error type.
    }
}

/// Read a real number.
pub fn read_real<R: Read>(reader: &mut R) -> Result<Real, OASISReadError> {
    let type_id = read_unsigned_integer(reader)?;
    read_real_without_type(reader, type_id)
}

#[test]
fn test_read_real() {

    // 0.0
    assert_eq!(read_real(bits!("00000000 00000000")).unwrap(), Real::PositiveWholeNumber(0));
    assert_eq!(read_real(bits!("00000110 00000000 00000000 00000000 00000000")).unwrap(),
               Real::IEEEFloat32(0.0));

    // 1.0
    assert_eq!(read_real(bits!("00000000 00000001")).unwrap(), Real::PositiveWholeNumber(1));
    assert_eq!(read_real(bits!("00000110 00000000 00000000 10000000 00111111")).unwrap(),
               Real::IEEEFloat32(1.0));

    // -0.5
    assert_eq!(read_real(bits!("00000011 00000010")).unwrap(), Real::NegativeReciprocal(2));
    assert_eq!(read_real(bits!("00000110 00000000 00000000 00000000 10111111")).unwrap(),
               Real::IEEEFloat32(-0.5));

    // 0.3125
    assert_eq!(read_real(bits!("00000100 00000101 00010000")).unwrap(), Real::PositiveRatio(5, 16));
    assert_eq!(read_real(bits!("00000110 00000000 00000000 10100000 00111110")).unwrap(),
               Real::IEEEFloat32(0.3125));

    // 1/3
    assert_eq!(read_real(bits!("00000010 00000011")).unwrap(), Real::PositiveReciprocal(3));
    assert_eq!(read_real(bits!("00000110 10101011 10101010 10101010 00111110")).unwrap(),
               Real::IEEEFloat32(1.0 / 3.0));

    // -2/13
    assert_eq!(read_real(bits!("00000101 00000010 00001101")).unwrap(), Real::NegativeRatio(2, 13));
    assert_eq!(read_real(bits!("00000110 11011001 10001001 00011101 10111110")).unwrap(),
               Real::IEEEFloat32(-2.0 / 13.0));
}


/// Write a real number.
pub fn write_real<W: Write>(writer: &mut W, value: Real) -> Result<(), OASISWriteError> {

    // Write type.
    match value {
        Real::PositiveWholeNumber(n) => {
            write_unsigned_integer(writer, 0)?;
            write_unsigned_integer(writer, n)?;
        }
        Real::NegativeWholeNumber(n) => {
            write_unsigned_integer(writer, 1)?;
            write_unsigned_integer(writer, n)?;
        }
        Real::PositiveReciprocal(n) => {
            write_unsigned_integer(writer, 2)?;
            write_unsigned_integer(writer, n)?;
        }
        Real::NegativeReciprocal(n) => {
            write_unsigned_integer(writer, 3)?;
            write_unsigned_integer(writer, n)?;
        }
        Real::PositiveRatio(d, n) => {
            write_unsigned_integer(writer, 4)?;
            write_unsigned_integer(writer, d)?;
            write_unsigned_integer(writer, n)?;
        }
        Real::NegativeRatio(d, n) => {
            write_unsigned_integer(writer, 5)?;
            write_unsigned_integer(writer, d)?;
            write_unsigned_integer(writer, n)?;
        }
        Real::IEEEFloat32(n) => {
            write_unsigned_integer(writer, 6)?;
            writer.write_f32::<LittleEndian>(n)?;
        }
        Real::IEEEFloat64(n) => {
            write_unsigned_integer(writer, 7)?;
            writer.write_f64::<LittleEndian>(n)?;
        }
    }
    Ok(())
}

/// Read a byte string.
/// Strings are stored with the byte length as an unsigned integer at the beginning.
pub fn read_byte_string<R: Read>(reader: &mut R) -> Result<Vec<u8>, OASISReadError> {
    // Read the length.
    let length = read_unsigned_integer(reader)?;
    let mut result = Vec::new();
    for _ in 0..length {
        result.push(reader.read_u8()?);
    }
    Ok(result)
}

/// Write a byte string.
pub fn write_byte_string<W: Write>(writer: &mut W, value: &[u8]) -> Result<(), OASISWriteError> {
    write_unsigned_integer(writer, value.len() as UInt)?;
    writer.write_all(value)?;
    Ok(())
}

/// Convert a byte string to an ASCII string.
/// Returns `None` if the byte string contains non-ascii characters.
pub fn bytes_to_ascii_string(bytes: Vec<u8>) -> Option<String> {
    // Test if all characters are between 0x20 and 0x7e (inclusive).
    let is_all_ascii = bytes.iter().all(|&c| 0x20 <= c && c <= 0x7e);
    if is_all_ascii {
        Some(String::from_utf8(bytes).unwrap())
    } else {
        None
    }
}

/// Read an ASCII string.
/// Encountering a non-printable ASCII character leads to a fatal error.
pub fn read_ascii_string<R: Read>(reader: &mut R) -> Result<String, OASISReadError> {
    let str = read_byte_string(reader)?;

    let ascii_str = bytes_to_ascii_string(str);

    if let Some(ascii_str) = ascii_str {
        Ok(ascii_str)
    } else {
        log::error!("Failed to read ASCII string.");
        Err(OASISReadError::FormatError) // TODO More precise error.
    }
}

/// Write an ASCII string.
/// Encountering a non-printable ASCII character leads to a fatal error.
pub fn write_ascii_string<W: Write>(writer: &mut W, value: &[u8]) -> Result<(), OASISWriteError> {
    // Test if all characters are between 0x20 and 0x7e (inclusive).
    let is_all_ascii = value.iter().all(|&c| 0x20 <= c && c <= 0x7e);
    if is_all_ascii {
        write_byte_string(writer, value)?;
        Ok(())
    } else {
        Err(OASISWriteError::FormatError) // TODO More precise error.
    }
}

/// Convert a byte string to an non-empty name string.
/// Returns `None` if the byte string contains non-ascii characters or a space (0x20)
/// or if the string is empty.
pub fn bytes_to_name_string(bytes: Vec<u8>) -> Option<String> {
    // Test if all characters are between 0x21 and 0x7e (inclusive).
    let is_all_ascii = bytes.iter().all(|&c| 0x21 <= c && c <= 0x7e);
    if is_all_ascii && !bytes.is_empty() {
        Some(String::from_utf8(bytes).unwrap())
    } else {
        None
    }
}

/// Read an name string.
/// A name string is a printable ASCII string with length greater than zero
/// and without any SPACE character.
/// Encountering a non-printable ASCII character leads to a fatal error.
pub fn read_name_string<R: Read>(reader: &mut R) -> Result<String, OASISReadError> {
    let str = read_byte_string(reader)?;

    if str.is_empty() {
        Err(OASISReadError::NameStringEmpty)
    } else {
        let name_str = bytes_to_name_string(str);

        if let Some(name_str) = name_str {
            Ok(name_str)
        } else {
            Err(OASISReadError::NameStringNotAscii)
        }
    }
}

/// Read an name string.
/// A name string is a printable ASCII string with length greater than zero
/// and without any SPACE character.
/// Encountering a non-printable ASCII character leads to a fatal error.
pub fn write_name_string<W: Write>(writer: &mut W, value: &[u8]) -> Result<(), OASISWriteError> {
    if value.is_empty() {
        Err(OASISWriteError::NameStringEmpty)
    } else {
        // Test if all characters are between 0x20 and 0x7e (inclusive).
        let is_all_ascii = value.iter().all(|&c| 0x21 <= c && c <= 0x7e);
        if is_all_ascii {
            write_byte_string(writer, value)?;
            Ok(())
        } else {
            Err(OASISWriteError::NameStringNotAscii)
        }
    }
}

/// A delta represents a two-dimensional vector.
/// Different representations are possible:
/// 1-delta: Horizontal or vertical displacement stored as a signed integer. Direction is given by the context.
/// 2-delta:
/// 3-delta:
/// g-delta:
#[derive(PartialEq, Eq, Copy, Clone, Hash, Debug)]
pub enum Delta {}

/// Read a 1-delta (one-dimensional coordinate).
pub fn read_1delta<R: Read>(reader: &mut R) -> Result<SInt, OASISReadError> {
    read_signed_integer(reader)
}

/// Write a 1-delat (one-dimensional coordinate).
pub fn write_1delta<W: Write>(writer: &mut W, delta: SInt) -> Result<(), OASISWriteError> {
    write_signed_integer(writer, delta)
}


/// Representation of a horizontal or vertical vector.
#[derive(PartialEq, Eq, Copy, Clone, Hash, Debug)]
pub enum Delta2 {
    East(UInt),
    North(UInt),
    West(UInt),
    South(UInt),
}

impl TryFrom<Vector<SInt>> for Delta2 {
    type Error = ();

    /// Convert a `Vector` into a `Delta2`.
    /// Returns an error if the vector cannot be encoded as a 2-delta.
    /// Only vectors which have at least one component set to zero can be encoded as a 2-delta.
    fn try_from(v: Vector<SInt>) -> Result<Self, Self::Error> {
        match (v.x, v.y) {
            (0, y) if y < 0 => Ok(Delta2::South(-y as UInt)),
            (0, y) => Ok(Delta2::North(y as UInt)),
            (x, 0) if x < 0 => Ok(Delta2::West(-x as UInt)),
            (x, 0) => Ok(Delta2::East(x as UInt)),
            _ => Err(())
        }
    }
}

impl Into<Vector<SInt>> for Delta2 {
    /// Convert a `Delta2` into a `Vector`.
    fn into(self) -> Vector<SInt> {
        match self {
            Delta2::East(m) => Vector::new(m as SInt, 0),
            Delta2::North(m) => Vector::new(0, m as SInt),
            Delta2::West(m) => Vector::new(-(m as SInt), 0),
            Delta2::South(m) => Vector::new(0, -(m as SInt)),
        }
    }
}

/// Read a 2-delta.
pub fn read_2delta<R: Read>(reader: &mut R) -> Result<Delta2, OASISReadError> {
    let u = read_unsigned_integer(reader)?;
    let dir = u & 0b11;
    let magnitude = u >> 2;

    // Directions: 0: east, 1: north, 2: west, 3: south
    let d = match dir {
        0 => Delta2::East(magnitude),
        1 => Delta2::North(magnitude),
        2 => Delta2::West(magnitude),
        3 => Delta2::South(magnitude),
        _ => unreachable!()
    };
    Ok(d)
}

/// Write a 2-delta.
pub fn write_2delta<W: Write>(writer: &mut W, d: Delta2) -> Result<(), OASISWriteError> {
    let u = match d {
        Delta2::East(m) => (m << 2) | 0b00,
        Delta2::North(m) => (m << 2) | 0b01,
        Delta2::West(m) => (m << 2) | 0b10,
        Delta2::South(m) => (m << 2) | 0b11,
    };
    write_unsigned_integer(writer, u)
}

/// Representation of a horizontal, vertical or diagonal vector.
#[derive(PartialEq, Eq, Copy, Clone, Hash, Debug)]
pub enum Delta3 {
    East(UInt),
    North(UInt),
    West(UInt),
    South(UInt),
    NorthEast(UInt),
    NorthWest(UInt),
    SouthWest(UInt),
    SouthEast(UInt),
}


impl TryFrom<Vector<SInt>> for Delta3 {
    type Error = ();

    /// Convert a `Vector` into a `Delta3`.
    /// Returns an error if the vector cannot be encoded as a 3-delta.
    /// Only vectors which have at least one component set to zero or have both components equal can be encoded as a 3-delta.
    fn try_from(v: Vector<SInt>) -> Result<Self, Self::Error> {
        match (v.x, v.y) {
            (0, y) if y < 0 => Ok(Delta3::South(-y as UInt)),
            (0, y) => Ok(Delta3::North(y as UInt)),
            (x, 0) if x < 0 => Ok(Delta3::West(-x as UInt)),
            (x, 0) => Ok(Delta3::East(x as UInt)),
            (x, y) if x == y && x < 0 => Ok(Delta3::SouthWest(-x as UInt)),
            (x, y) if x == y => Ok(Delta3::NorthEast(x as UInt)),
            (x, y) if y == -x && x < 0 => Ok(Delta3::NorthWest(y as UInt)),
            (x, y) if y == -x => Ok(Delta3::SouthEast(x as UInt)),
            _ => Err(())
        }
    }
}

impl Into<Vector<SInt>> for Delta3 {
    /// Convert a `Delta2` into a `Vector`.
    fn into(self) -> Vector<SInt> {
        match self {
            Delta3::East(m) => Vector::new(m as SInt, 0),
            Delta3::North(m) => Vector::new(0, m as SInt),
            Delta3::West(m) => Vector::new(-(m as SInt), 0),
            Delta3::South(m) => Vector::new(0, -(m as SInt)),
            Delta3::NorthEast(m) => Vector::new(m as SInt, m as SInt),
            Delta3::NorthWest(m) => Vector::new(-(m as SInt), m as SInt),
            Delta3::SouthWest(m) => Vector::new(-(m as SInt), -(m as SInt)),
            Delta3::SouthEast(m) => Vector::new(m as SInt, -(m as SInt)),
        }
    }
}

impl Delta3 {
    /// Decode from an `UInt`.
    fn decode_from_uint(u: UInt) -> Self {
        let dir = u & 0b111; // Direction.
        let m = u >> 3; // Magnitude.

        // Directions: 0: east, 1: north, 2: west, 3: south
        match dir {
            0 => Delta3::East(m),
            1 => Delta3::North(m),
            2 => Delta3::West(m),
            3 => Delta3::South(m),
            4 => Delta3::NorthEast(m),
            5 => Delta3::NorthWest(m),
            6 => Delta3::SouthWest(m),
            7 => Delta3::SouthEast(m),
            _ => unreachable!()
        }
    }

    /// Encode the `Delta3` into an `UInt`.
    fn encode_as_uint(self) -> UInt {
        match self {
            Delta3::East(m) => (m << 3) | 0,
            Delta3::North(m) => (m << 3) | 1,
            Delta3::West(m) => (m << 3) | 2,
            Delta3::South(m) => (m << 3) | 3,
            Delta3::NorthEast(m) => (m << 3) | 4,
            Delta3::NorthWest(m) => (m << 3) | 5,
            Delta3::SouthWest(m) => (m << 3) | 6,
            Delta3::SouthEast(m) => (m << 3) | 7,
        }
    }
}

/// Read a 3-delta.
pub fn read_3delta<R: Read>(reader: &mut R) -> Result<Delta3, OASISReadError> {
    let u = read_unsigned_integer(reader)?;
    Ok(Delta3::decode_from_uint(u))
}

/// Write a 3-delta.
pub fn write_3delta<W: Write>(writer: &mut W, d: Delta3) -> Result<(), OASISWriteError> {
    write_unsigned_integer(writer, d.encode_as_uint())
}


/// Representation of a horizontal, vertical, diagonal or arbitrary vector.
#[derive(PartialEq, Eq, Copy, Clone, Hash, Debug)]
pub enum DeltaG {
    Delta3(Delta3),
    Arbitrary(SInt, SInt),
}

impl From<Vector<SInt>> for DeltaG {
    /// Convert a `Vector` into a g-delta representation.
    fn from(v: Vector<SInt>) -> Self {
        // Take the 3-delta representation if possible.
        Delta3::try_from(v)
            .map(|d| DeltaG::Delta3(d))
            // Otherwise take the representation for arbitrary vectors.
            .unwrap_or(DeltaG::Arbitrary(v.x, v.y))
    }
}

impl Into<Vector<SInt>> for DeltaG {
    /// Convert a `DeltaG` into a `Vector`.
    fn into(self) -> Vector<SInt> {
        match self {
            DeltaG::Delta3(d) => d.into(),
            DeltaG::Arbitrary(x, y) => Vector::new(x, y)
        }
    }
}

/// Read a g-delta.
pub fn read_gdelta<R: Read>(reader: &mut R) -> Result<DeltaG, OASISReadError> {
    let u = read_unsigned_integer(reader)?;
    // Bit 0 of u tells the g-delta type.
    let gdelta_type = u & 0b1;

    let d = if gdelta_type == 0 {
        // Similar encoding to 3-delta.
        let d3 = Delta3::decode_from_uint(u >> 1);
        DeltaG::Delta3(d3)
    } else {
        // xy encoding.
        // Bit 1 of u tells the sign of x.
        let x_sign = u & 0b10;
        let x_mag = (u >> 2) as SInt;
        let x = if x_sign == 0 { x_mag } else { -x_mag };
        let y = read_signed_integer(reader)?;

        DeltaG::Arbitrary(x, y)
    };

    Ok(d)
}


/// Write a g-delta.
pub fn write_gdelta<W: Write>(writer: &mut W, d: DeltaG) -> Result<(), OASISWriteError> {
    match d {
        DeltaG::Delta3(d3) => {
            let u = d3.encode_as_uint() << 1;
            write_unsigned_integer(writer, u)?;
        }
        DeltaG::Arbitrary(x, y) => {
            // TODO: Check for overflows (also at other places).

            // Encode x as a unsigned integer.
            // Bit 1 holds the sign.
            // Bit 0 tells the type of g-delta encoding used.
            let ux = if x < 0 {
                let x_mag = -x as UInt;
                (x_mag << 2) | 0b11
            } else {
                let x_mag = x as UInt;
                (x_mag << 2) | 0b01
            };

            write_unsigned_integer(writer, ux)?; // Write encoded x coordinate.
            write_signed_integer(writer, y)?; // Write y coordinate.
        }
    };

    Ok(())
}


/// Test delta encodings with examples from the specification.
#[test]
fn test_read_delta_encodings() {
    assert_eq!(read_1delta(bits!("11111001 00100011")).unwrap(), -2300);
    assert_eq!(read_1delta(bits!("11111000 00100011")).unwrap(), 2300);

    assert_eq!(read_2delta(bits!("10011000 00101010")).unwrap(), Delta2::East(1350));
    assert_eq!(read_2delta(bits!("10011011 00101010")).unwrap(), Delta2::South(1350));

    assert_eq!(read_3delta(bits!("11001101 00000001")).unwrap(), Delta3::NorthWest(25));
    assert_eq!(read_3delta(bits!("11010111 00000111")).unwrap(), Delta3::SouthEast(122));

    assert_eq!(read_gdelta(bits!("11101001 00000011 01111010")).unwrap(), DeltaG::Arbitrary(122, 61));
    assert_eq!(read_gdelta(bits!("11101100 00000101")).unwrap(), DeltaG::Delta3(Delta3::SouthWest(46)));
    assert_eq!(read_gdelta(bits!("10111011 00000001 10110111 00001111")).unwrap(), DeltaG::Arbitrary(-46, -987));
}

/// Describe a equispaced n*m two-dimensional repetition as a lattice.
/// The offsets are computed as `(i*a, j*b)` for `i` in `0..n` and `j` in `0..m`.
/// `a` and `b` the distance vectors between two neighbouring points.
#[derive(PartialEq, Eq, Copy, Clone, Debug, Hash)]
pub struct RegularRepetition {
    /// First lattice vector.
    a: Vector<SInt>,
    /// Second lattice vector.
    b: Vector<SInt>,
    /// First dimension.
    n: UInt,
    /// Second dimension.
    m: UInt,
}

impl RegularRepetition {
    pub fn new(a: Vector<SInt>, b: Vector<SInt>, n: UInt, m: UInt) -> Self {
        return RegularRepetition { a, b, n, m };
    }

    /// Iterate over each offsets of this repetition.
    pub fn iter(self) -> impl Iterator<Item=Vector<SInt>> {
        (0..self.m).flat_map(move |j| {
            (0..self.n).map(move |i| self.a * i as SInt + self.b * j as SInt)
        })
    }

    /// Return the number of offsets in this repetition.
    pub fn len(&self) -> usize {
        (self.n * self.m) as usize
    }
}

/// Describe a non-equispaced repetition by storing a list of offsets.
#[derive(PartialEq, Eq, Clone, Debug, Hash)]
pub struct IrregularRepetition {
    /// Offset vectors of the repetition.
    offsets: Vec<Vector<SInt>>
}

impl IrregularRepetition {
    fn new(offsets: Vec<Vector<SInt>>) -> Self {
        assert!(offsets.len() >= 2);
        // First offset must be zero.
        if let Some(first) = offsets.first() {
            assert!(first.is_zero())
        }
        return IrregularRepetition { offsets };
    }

    /// Iterate over each offsets of this repetition.
    pub fn iter(&self) -> impl Iterator<Item=&Vector<SInt>> {
        self.offsets.iter()
    }

    /// Return the number of offsets in this repetition.
    pub fn len(&self) -> usize {
        self.offsets.len()
    }
}

#[derive(PartialEq, Eq, Clone, Debug, Hash)]
pub enum Repetition {
    ReusePrevious,
    Regular(RegularRepetition),
    Irregular(IrregularRepetition),
}

pub fn read_repetition<R: Read>(reader: &mut R) -> Result<Repetition, OASISReadError> {
    let repetition_type = read_unsigned_integer(reader)?;

    match repetition_type {
        0 => {
            // Re-use the previous repetition definition which is stored in a modal variable.
            Ok(Repetition::ReusePrevious)
        }
        1 => {
            // N-column by M-row.
            let x_dimension = read_unsigned_integer(reader)?;
            let y_dimension = read_unsigned_integer(reader)?;
            let x_space = read_unsigned_integer(reader)? as SInt;
            let y_space = read_unsigned_integer(reader)? as SInt;

            // n, m are always larger than 1.
            let n = x_dimension + 2;
            let m = y_dimension + 2;

            Ok(Repetition::Regular(
                RegularRepetition::new((x_space, 0).into(), (0, y_space).into(), n, m)
            ))
        }
        2 => {
            // Horizontal repetition. N-column by 1-row.
            let x_dimension = read_unsigned_integer(reader)?;
            let x_space = read_unsigned_integer(reader)? as SInt;

            let n = x_dimension + 2;

            Ok(Repetition::Regular(
                RegularRepetition::new((x_space, 0).into(), (0, 0).into(), n, 1)
            ))
        }
        3 => {
            // Vertical repetition. 1-column by M-row.
            let y_dimension = read_unsigned_integer(reader)?;
            let y_space = read_unsigned_integer(reader)? as SInt;

            let m = y_dimension + 2;

            Ok(Repetition::Regular(
                RegularRepetition::new((0, 0).into(), (0, y_space).into(), 1, m)
            ))
        }
        4 | 5 => {
            // N-column by 1-row with non-equidistant spacing.
            let x_dimension = read_unsigned_integer(reader)?;
            // Optionally read `grid`.
            let grid = if repetition_type == 5 { read_unsigned_integer(reader)? } else { 1 } as SInt;
            let n = x_dimension + 2;

            // Read spaces between the placements and calculate the offsets by integrating
            // the spaces.
            let mut offsets = Vec::new();
            offsets.reserve(n as usize); // Reserve expected space.
            let mut accumulator = Vector::zero();
            offsets.push(accumulator);

            for _ in 1..n {
                let spacing = read_unsigned_integer(reader)? as SInt;
                let diff = (spacing * grid, 0).into();
                accumulator += diff;
                offsets.push(accumulator);
            }

            Ok(
                Repetition::Irregular(IrregularRepetition::new(offsets))
            )
        }
        6 | 7 => {
            // 1-column by M-row with non-equidistant spacing.
            let y_dimension = read_unsigned_integer(reader)?;
            // Optionally read `grid`.
            let grid = if repetition_type == 7 { read_unsigned_integer(reader)? } else { 1 } as SInt;
            let m = y_dimension + 2;

            // Read spaces between the placements and calculate the offsets by integrating
            // the spaces.
            let mut offsets = Vec::new();
            offsets.reserve(m as usize); // Reserve expected space.
            let mut accumulator = Vector::zero();
            offsets.push(accumulator);

            for _ in 1..m {
                let spacing = read_unsigned_integer(reader)? as SInt;
                let diff = (0, spacing * grid).into();
                accumulator += diff;
                offsets.push(accumulator);
            }

            Ok(
                Repetition::Irregular(IrregularRepetition::new(offsets))
            )
        }
        8 => {
            // N*M Lattice defined by two lattice vectors.
            let n_dimension = read_unsigned_integer(reader)?;
            let m_dimension = read_unsigned_integer(reader)?;
            let n = n_dimension + 2;
            let m = m_dimension + 2;
            let n_displacement = read_gdelta(reader)?; // First basis vector.
            let m_displacement = read_gdelta(reader)?; // Second basis vector.

            // Create basis vectors of the lattice.
            let a = n_displacement.into();
            let b = m_displacement.into();

            Ok(
                Repetition::Regular(RegularRepetition::new(a, b, n, m))
            )
        }
        9 => {
            // p-element repetition along the vector`displacement`.
            // This is equivalent to a p*1 lattice with basis vectors d and (0, 0).
            let dimension = read_unsigned_integer(reader)?;
            let displacement = read_gdelta(reader)?;
            let d = displacement.into();
            let p = dimension + 2;

            Ok(
                Repetition::Regular(RegularRepetition::new(d, Vector::zero(), p, 1))
            )
        }
        10 | 11 => {
            // P-element repetition with arbitrary displacements between elements.
            let dimension = read_unsigned_integer(reader)?;
            // Optionally read grid parameter.
            let grid = if repetition_type == 11 { read_unsigned_integer(reader)? } else { 1 } as SInt;
            let p = dimension + 2;

            // Read spaces between the placements and calculate the offsets by integrating
            // the spaces.
            let mut offsets = Vec::new();
            offsets.reserve(p as usize); // Reserve expected space.
            let mut accumulator = Vector::zero();
            offsets.push(accumulator);

            for _ in 1..p {
                let d: Vector<SInt> = read_gdelta(reader)?.into();
                accumulator += d * grid;
                offsets.push(accumulator)
            }

            Ok(
                Repetition::Irregular(IrregularRepetition::new(offsets))
            )
        }
        t => Err(OASISReadError::IllegalRepetitionType(t))
    }
}

/// Compute the greatest common divisor of `a` and `b`.
fn gcd_euclid<T: num_traits::PrimInt>(a: T, b: T) -> T {
    let mut a = a;
    let mut b = b;
    while !b.is_zero() {
        let t = b;
        b = a % b;
        a = t;
    }
    a
}

#[test]
fn test_gcd() {
    assert_eq!(gcd_euclid(0, 0), 0);
    assert_eq!(gcd_euclid(0, 1), 1);
    assert_eq!(gcd_euclid(1, 0), 1);
    assert_eq!(gcd_euclid(2, 4), 2);
    assert_eq!(gcd_euclid(14, 21), 7);
}

/// Write a repetition.
/// Irregular repetitions must contain more than one offset.
pub fn write_repetition<W: Write>(writer: &mut W, repetition: &Repetition) -> Result<(), OASISWriteError> {
    match repetition {
        Repetition::ReusePrevious => {
            write_unsigned_integer(writer, 0)?;
        }
        Repetition::Regular(rep) => {
            let RegularRepetition { a, b, n, m } = *rep;
            match (a, b, n, m) {
                (_, _, 0, _) | (_, _, _, 0) => {
                    // Zero-sized repetition is not allowed.
                    return Err(OASISWriteError::FormatError);
                }
                (diff, _, p, 1) | (_, diff, 1, p) => {
                    // 1-dimensional repetitions. Could be type 2, 3 or 9.
                    if p < 2 {
                        return Err(OASISWriteError::FormatError);
                    }
                    let dimension = p - 2;

                    match (diff.x, diff.y) {
                        (x, 0) if x >= 0 => {
                            // Horizontal repetition, type 2.
                            write_unsigned_integer(writer, 2)?;
                            write_unsigned_integer(writer, dimension)?;
                            write_unsigned_integer(writer, x as UInt)?;
                        }
                        (0, y) if y >= 0 => {
                            // Vertical repetition, type 3.
                            write_unsigned_integer(writer, 3)?;
                            write_unsigned_integer(writer, dimension)?;
                            write_unsigned_integer(writer, y as UInt)?;
                        }
                        (_x, _y) => {
                            // Neither horizontal nor vertical, type 9.
                            write_unsigned_integer(writer, 9)?;
                            write_unsigned_integer(writer, dimension)?;
                            write_gdelta(writer, diff.into())?;
                        }
                    }
                }
                (a, b, n, m) => {
                    // Most general, type 1 (rectilinear grid) or 8.
                    if n < 2 || m < 2 {
                        return Err(OASISWriteError::FormatError);
                    }

                    let x_dimension = n - 2;
                    let y_dimension = m - 2;

                    match ((a.x, a.y), (b.x, b.y)) {
                        ((x_space, 0), (0, y_space))
                        | ((0, y_space), (x_space, 0))
                        if x_space >= 0 || y_space >= 0 => {
                            // Rectilinear grid with positive space. Type 1.
                            write_unsigned_integer(writer, 1)?;
                            write_unsigned_integer(writer, x_dimension)?;
                            write_unsigned_integer(writer, y_dimension)?;
                            write_unsigned_integer(writer, x_space as UInt)?;
                            write_unsigned_integer(writer, y_space as UInt)?;
                        }
                        _ => {
                            // Arbitrary lattice vectors. Type 8.
                            write_unsigned_integer(writer, 8)?;
                            write_unsigned_integer(writer, x_dimension)?;
                            write_unsigned_integer(writer, y_dimension)?;
                            write_gdelta(writer, a.into())?;
                            write_gdelta(writer, b.into())?;
                        }
                    }
                }
            }
        }
        Repetition::Irregular(irep) => {
            // Type 4, 5, 6, 7, 10 and 11.

            if irep.len() < 2 {
                return Err(OASISWriteError::FormatError);
            }

            let dimension = irep.len() as UInt - 2;

            // Extract grid by computing the greatest common divisor of all coordinates.
            // All coordinates will be divided by the GCD. This allows to store them potentially
            // in a more compact way.

            // Compute the GCD of all coordinates and
            // test if all x,y increments are positive.
            let mut gcd_x = 0;
            let mut gcd_y = 0;
            let mut is_all_xstep_positive = true;
            let mut is_all_ystep_positive = true;
            let mut v_prev = None;
            for &v in irep.iter() {
                // Incrementally compute the GCD of all coordinates.
                gcd_x = gcd_euclid(gcd_x, v.x);
                gcd_y = gcd_euclid(gcd_y, v.y);
                if let Some(prev) = v_prev {
                    let diff = v - prev;
                    if diff.x < 0 {
                        is_all_xstep_positive = false;
                    }
                    if diff.y < 0 {
                        is_all_ystep_positive = false;
                    }
                }
                v_prev = Some(v);
            }
            // Combine the GCD of x and y coordinates.
            let gcd = gcd_euclid(gcd_x, gcd_y);
            debug_assert!(gcd >= 0);
            // Set grid to 1 if the GCD happens to be 0 to avoid divisons by 0.
            let grid = if gcd == 0 { 1 } else { gcd } as UInt;

            // Detect if this is a strictly horizontal or vertical repetition.
            let is_x_coord_all_zero = gcd_x == 0; // If the gcd of some numbers is zero this implies that all the numbers are zero.
            let is_y_coord_all_zero = gcd_y == 0;

            if is_y_coord_all_zero && is_all_xstep_positive {
                // Horizontal repetition. Type 4 or 5.
                if grid == 1 {
                    // Type 4.
                    write_unsigned_integer(writer, 4)?;
                    write_unsigned_integer(writer, dimension)?;
                } else {
                    // Type 5.
                    write_unsigned_integer(writer, 5)?;
                    write_unsigned_integer(writer, dimension)?;
                    write_unsigned_integer(writer, grid)?;
                }

                // Iterate over all neighboured offsets.
                for (a, b) in irep.iter().zip(irep.iter().skip(1)) {
                    let diff = b.x - a.x;
                    debug_assert!(diff >= 0);
                    debug_assert_eq!(diff as UInt % grid, 0);
                    write_unsigned_integer(writer, diff as UInt / grid)?;
                }
            } else if is_x_coord_all_zero && is_all_ystep_positive {
                // Vertical repetition. Type 6 or 7.
                if grid == 1 {
                    // Type 6.
                    write_unsigned_integer(writer, 6)?;
                    write_unsigned_integer(writer, dimension)?;
                } else {
                    // Type 7.
                    write_unsigned_integer(writer, 7)?;
                    write_unsigned_integer(writer, dimension)?;
                    write_unsigned_integer(writer, grid)?;
                }

                // Iterate over all neighboured offsets.
                for (a, b) in irep.iter().zip(irep.iter().skip(1)) {
                    let diff = b.y - a.y;
                    debug_assert!(diff >= 0);
                    debug_assert_eq!(diff as UInt % grid, 0);
                    write_unsigned_integer(writer, diff as UInt / grid)?;
                }
            } else {
                // Arbitrary steps. Type 10 or 11.
                if grid == 1 {
                    // Type 10.
                    write_unsigned_integer(writer, 10)?;
                    write_unsigned_integer(writer, dimension)?;
                } else {
                    // Type 11.
                    write_unsigned_integer(writer, 11)?;
                    write_unsigned_integer(writer, dimension)?;
                    write_unsigned_integer(writer, grid)?;
                }
                let grid = grid as SInt;
                // Iterate over all neighboured offsets.
                for (a, b) in irep.iter().zip(irep.iter().skip(1)) {
                    let diff = *b - *a;
                    debug_assert_eq!(diff.x % grid, 0);
                    debug_assert_eq!(diff.y % grid, 0);
                    let diff = diff / grid;
                    write_gdelta(writer, diff.into())?;
                }
            }
        }
    };

    Ok(())
}


/// Test write and read functions for repetitions.
/// For each repetition type a value is written and read again and compared to the original.
#[test]
fn test_write_read_repetition() {
    /// Write and read a repetition and test that the read back result is correct.
    fn test(rep: Repetition) {
        let mut buf = Vec::new();
        write_repetition(&mut buf, &rep).unwrap();
        let rep2 = read_repetition(&mut buf[..].as_ref()).unwrap();
        assert_eq!(rep, rep2);
    }

    // Type 0.
    test(Repetition::ReusePrevious);

    // Type 1. 2-dimensional rectilinear grid with positive spacing.
    test(Repetition::Regular(
        RegularRepetition::new((1, 0).into(), (0, 2).into(), 7, 3)
    ));

    // Type 2. 1-dimensional, horizontal.
    test(Repetition::Regular(
        RegularRepetition::new((1, 0).into(), (0, 0).into(), 7, 1)
    ));

    // Type 3. 1-dimensional, vertical.
    test(Repetition::Regular(
        RegularRepetition::new((0, 0).into(), (0, 1).into(), 1, 7)
    ));

    // Type 4. 1-dimensional, horizontal, non-equidistant.
    test(Repetition::Irregular(
        IrregularRepetition::new([(0, 0), (1, 0)].iter().map(|t| t.into()).collect())
    ));

    // Type 5. 1-dimensional, horizontal, non-equidistant. Grid > 1.
    test(Repetition::Irregular(
        IrregularRepetition::new([(0, 0), (200, 0), (800, 0)].iter().map(|t| t.into()).collect())
    ));

    // Type 6. 1-dimensional, vertical, non-equidistant.
    test(Repetition::Irregular(
        IrregularRepetition::new([(0, 0), (0, 1)].iter().map(|t| t.into()).collect())
    ));

    // Type 7. 1-dimensional, vertical, non-equidistant. Grid > 1.
    test(Repetition::Irregular(
        IrregularRepetition::new([(0, 0), (0, 200), (0, 800)].iter().map(|t| t.into()).collect())
    ));

    // Type 8. 2-dimensional grid.
    // Negative spacing cannot be encoded as type 1 but type 8.
    test(Repetition::Regular(
        RegularRepetition::new((-1, 0).into(), (0, 2).into(), 7, 3)
    ));
    test(Repetition::Regular(
        RegularRepetition::new((1, 2).into(), (2, 3).into(), 7, 3)
    ));

    // Type 9. 1-dimensional, any direction.
    test(Repetition::Regular(
        RegularRepetition::new((1, 2).into(), (0, 0).into(), 7, 1)
    ));
    // Horizontal and vertical repetitions with a negative direction cannot be encoded
    // as type 2 or 3 but as type 9.
    test(Repetition::Regular(
        RegularRepetition::new((-1, 0).into(), (0, 0).into(), 7, 1)
    ));
    test(Repetition::Regular(
        RegularRepetition::new((0, -1).into(), (0, 0).into(), 7, 1)
    ));

    // Type 10. Non-equidistant. Grid == 1.
    test(Repetition::Irregular(
        IrregularRepetition::new([(0, 0), (0, 1), (1, 0), (1, 2)].iter().map(|t| t.into()).collect())
    ));

    // Type 11. Non-equidistant. Grid > 1.
    test(Repetition::Irregular(
        IrregularRepetition::new([(0, 0), (0, 100), (100, 0), (100, 200)].iter().map(|t| t.into()).collect())
    ));
}

/// Represent a list of coordinates for polygons or paths. The first coordinate is always implicitly (0, 0).
/// The further coordinates are stored as displacements between the points in the list.
#[derive(PartialEq, Eq, Clone, Debug, Hash)]
pub enum PointList {
    /// Type 0: Store horizontal and vertical distances to the previous point
    /// in alternating fashion. The first edge is vertical.
    ImplicitManhattanVerticalFirst(Vec<SInt>),
    /// Type 1: Store horizontal and vertical distances to the previous point
    /// in alternating fashion. The first edge is horizontal.
    ImplicitManhattanHorizontalFirst(Vec<SInt>),
    /// Type 2: Store differences between offsets. Differences can only be vertical or horizontal.
    ExplicitManhattan(Vec<Delta2>),
    /// Type 3: Store differences between offsets. Differences must be vertical, horizontal or diagonal.
    ExplicitOctangularManhattan(Vec<Delta3>),
    /// Type 4: Store differences between offsets.
    Explicit(Vec<DeltaG>),
    /// Type 5: Describe the path by the differences of differences between offsets ('second derivative').
    ExplicitDouble(Vec<DeltaG>),
}

impl PointList {
    /// TODO: Create a `PointList` by analyzing the sequence of points and choosing the most
    /// compact representation.
    pub fn _from_points_compressed(_offset: Vector<SInt>, _points: &Vec<Vector<SInt>>) -> PointList {
        unimplemented!()
    }

    /// Create a `PointList::Explicit` with the most generic representation of the point sequence.
    pub fn from_points_explicit(points: &Vec<Point<SInt>>) -> PointList {
        let (_, diffs) = points.iter().fold((None, Vec::new()),
                                            |(prev, mut acc), &current| {
                                                if let Some(prev) = prev {
                                                    let diff = current - prev;
                                                    acc.push(DeltaG::from(diff))
                                                }
                                                (Some(current), acc)
                                            });
        PointList::Explicit(diffs)
    }

    /// Convert the point list representation into explicit offsets.
    /// # Arguments
    /// * `offset` - Offset to be added to all points.
    /// * `for_polygon` - A `bool` which tells if the point list shall be converted into offsets for a polygon or a path.
    ///     For implicit encodings this will activate one more implicit vertex.
    pub fn points(&self, offset: Vector<SInt>, for_polygon: bool) -> Vec<Point<SInt>> {
        // Convert implicit manhattan points to explicit offsets.
        let implicit_manhattan_points = |diffs: &Vec<SInt>, vertical: bool| {
            let mut points: Vec<Point<_>> = Vec::new();
            if for_polygon {
                debug_assert!(diffs.len() >= 2);
            }
            points.reserve(diffs.len() + 2);
            let mut accumulator = Point::from(offset);
            points.push(accumulator);
            let mut vertical = vertical;
            for &d in diffs {
                let d = if vertical { (d, 0) } else { (0, d) };
                accumulator += Vector::from(d);
                points.push(accumulator);
                vertical = !vertical;
            }
            if for_polygon {
                // Derive implicit last vertex of polygon.
                let second_last = points.last().unwrap();
                let last = if vertical {
                    (0, second_last.y)
                } else {
                    (second_last.x, 0)
                };
                points.push(last.into());
            }
            points
        };

        match self {
            PointList::ImplicitManhattanVerticalFirst(diffs) => {
                implicit_manhattan_points(diffs, true)
            }
            PointList::ImplicitManhattanHorizontalFirst(diffs) => {
                implicit_manhattan_points(diffs, false)
            }
            PointList::ExplicitManhattan(diffs) => {
                let mut points = Vec::new();
                points.reserve(diffs.len() + 1);
                let mut accumulator = Point::zero();
                points.push(accumulator);
                for &d in diffs {
                    let v: Vector<_> = d.into();
                    accumulator += v;
                    points.push(accumulator);
                }
                points
            }
            PointList::ExplicitOctangularManhattan(diffs) => {
                let mut points = Vec::new();
                points.reserve(diffs.len() + 1);
                let mut accumulator = Point::from(offset);
                points.push(accumulator);
                for &d in diffs {
                    let v: Vector<_> = d.into();
                    accumulator += v;
                    points.push(accumulator);
                }
                points
            }
            PointList::Explicit(diffs) => {
                let mut points = Vec::new();
                points.reserve(diffs.len() + 1);
                let mut accumulator = Point::from(offset);
                points.push(accumulator);
                for &d in diffs {
                    let v: Vector<_> = d.into();
                    accumulator += v;
                    points.push(accumulator);
                }
                points
            }
            PointList::ExplicitDouble(ddiffs) => {
                let mut points = Vec::new();
                points.reserve(ddiffs.len() + 1);
                let mut accumulator1 = Point::zero();
                let mut accumulator2 = Point::from(offset);
                points.push(accumulator2);
                for &d in ddiffs {
                    let v: Vector<_> = d.into();
                    accumulator1 += v;
                    accumulator2 += accumulator1;
                    points.push(accumulator2)
                }
                points
            }
        }
    }
}

/// Test conversion between lists of points and `PointList`.
#[test]
fn test_pointlist_from_points_to_points() {
    let arbitrary: Vec<Point<_>> = vec![(1, 2), (7, 8), (-100, -200), (0, 0), (1, 1), (2, 2)]
        .iter().map(|t| t.into()).collect();
    let point_list = PointList::from_points_explicit(&arbitrary);
    let offset = arbitrary.first().unwrap().v();

    let back = point_list.points(offset, false);
    assert_eq!(back, arbitrary)
}

/// Read a point list.
pub fn read_point_list<R: Read>(reader: &mut R) -> Result<PointList, OASISReadError> {
    let pointlist_type = read_unsigned_integer(reader)?;
    let vertex_count = read_unsigned_integer(reader)?;

    match pointlist_type {
        0 | 1 => {
            // Implicit manhattan.
            let mut deltas = Vec::new();
            deltas.reserve(vertex_count as usize);
            for _ in 0..vertex_count {
                deltas.push(read_1delta(reader)?);
            }

            if pointlist_type == 0 {
                Ok(PointList::ImplicitManhattanVerticalFirst(deltas))
            } else {
                Ok(PointList::ImplicitManhattanHorizontalFirst(deltas))
            }
        }
        2 => {
            let mut deltas = Vec::new();
            deltas.reserve(vertex_count as usize);
            for _ in 0..vertex_count {
                deltas.push(read_2delta(reader)?);
            }
            Ok(PointList::ExplicitManhattan(deltas))
        }
        3 => {
            let mut deltas = Vec::new();
            deltas.reserve(vertex_count as usize);
            for _ in 0..vertex_count {
                deltas.push(read_3delta(reader)?);
            }
            Ok(PointList::ExplicitOctangularManhattan(deltas))
        }
        4 | 5 => {
            let mut deltas = Vec::new();
            deltas.reserve(vertex_count as usize);
            for _ in 0..vertex_count {
                deltas.push(read_gdelta(reader)?);
            }
            if pointlist_type == 4 {
                Ok(PointList::Explicit(deltas))
            } else {
                Ok(PointList::ExplicitDouble(deltas))
            }
        }
        _ => {
            log::error!("Invalid point-list type (must be in the range 0..5): {}", pointlist_type);
            Err(OASISReadError::FormatError) // TODO: More precise error.
        }
    }
}

#[test]
fn test_read_pointlist() {
    /// Convert a `Vec` of tuples into a `Vec` of `Vector`s.
    fn points(v: Vec<(SInt, SInt)>) -> Vec<Point<SInt>> {
        v.iter().map(|c| c.into()).collect()
    }

    fn test(bitstring: &str, expected_points: Vec<(SInt, SInt)>) {
        let pointlist = read_point_list(bits!(bitstring)).unwrap();
        assert_eq!(pointlist.points(Vector::zero(), true), points(expected_points));
    }

    // Type 0.
    test("00000000 00000100 00001100 00001000 00010001 00000101",
         vec![(0, 0), (6, 0), (6, 4), (-2, 4), (-2, 2), (0, 2)],
    );
    // Type 1.
    test("00000001 00000100 00010001 00000100 00000100 00000100",
         vec![(0, 0), (0, -8), (2, -8), (2, -6), (4, -6), (4, 0)],
    );
    // Type 2.
    test("00000010 00000101 00100000 00011001 00010010 00001011 00010010",
         vec![(0, 0), (8, 0), (8, 6), (4, 6), (4, 4), (0, 4)],
    );
    // Type 3.
    test("00000011 00000100 00010101 00100001 00110000 00010011",
         vec![(0, 0), (-2, 2), (-2, 6), (4, 6), (4, 4)],
    );
    // Type 4.
    test("00000100 00000010 01000100 00001001 00001101",
         vec![(0, 0), (-4, 0), (-2, -6)],
    );
    // Type 5.
    test("00000101 00001001 00000001 00000011 00101001 00000000 00000001 00000100 00000001 00000011 00000001 00000011 00101011 00000100 00101011 00000000 00000001 00000011 00000001 00000011",
         vec![(0, 0), (0, -1), (10, -2), (20, -1), (30, -1), (40, -2), (40, -1), (30, 0), (20, 0), (10, -1)],
    );
}


pub fn write_pointlist<W: Write>(writer: &mut W, pointlist: &PointList) -> Result<(), OASISWriteError> {
    let (pointlist_type, length) = match pointlist {
        PointList::ImplicitManhattanVerticalFirst(v) => (0, v.len()),
        PointList::ImplicitManhattanHorizontalFirst(v) => (1, v.len()),
        PointList::ExplicitManhattan(v) => (2, v.len()),
        PointList::ExplicitOctangularManhattan(v) => (3, v.len()),
        PointList::Explicit(v) => (4, v.len()),
        PointList::ExplicitDouble(v) => (5, v.len()),
    };

    write_unsigned_integer(writer, pointlist_type)?;
    write_unsigned_integer(writer, length as UInt)?;

    match pointlist {
        PointList::ImplicitManhattanVerticalFirst(v)
        | PointList::ImplicitManhattanHorizontalFirst(v) => {
            for &x in v {
                write_1delta(writer, x)?;
            }
        }
        PointList::ExplicitManhattan(v) => {
            for &x in v {
                write_2delta(writer, x)?;
            }
        }
        PointList::ExplicitOctangularManhattan(v) => {
            for &x in v {
                write_3delta(writer, x)?;
            }
        }
        PointList::Explicit(v) | PointList::ExplicitDouble(v) => {
            for &x in v {
                write_gdelta(writer, x)?;
            }
        }
    };
    Ok(())
}

// TODO: Conversion from polygon/paths to PointList.

#[derive(PartialEq, Clone, Debug)]
pub enum PropertyValue {
    Real(Real),
    UInt(UInt),
    SInt(SInt),
    /// ASCII string.
    AString(String),
    /// Byte string.
    BString(Vec<u8>),
    /// Name string.
    NString(String),
    /// Prop-string-reference-number, implied a-string.
    AStringRef(UInt),
    // TODO: Is this really a UInt???
    /// Prop-string-reference-number, implied b-string.
    BStringRef(UInt),
    // TODO: Is this really a UInt???
    /// Prop-string-reference-number, implied n-string.
    NStringRef(UInt), // TODO: Is this really a UInt???
}

// impl Into<db::property_storage::PropertyValue> for &PropertyValue {
//     fn into(self) -> db::property_storage::PropertyValue {
//         match self {
//             PropertyValue::UInt(v) => (*v).into(),
//             PropertyValue::SInt(v) => (*v).into(),
//             PropertyValue::AString(v) => v.clone().into(),
//             PropertyValue::NString(v) => v.clone().into(),
//             x => {
//                 dbg!(x);
//                 unimplemented!()
//             }
//         }
//     }
// }


pub fn read_property_value<R: Read>(reader: &mut R) -> Result<PropertyValue, OASISReadError> {
    let propertyvalue_type = read_unsigned_integer(reader)?;
    match propertyvalue_type {
        t @ 0..=7 =>
            Ok(PropertyValue::Real(read_real_without_type(reader, t)?)),
        8 => Ok(PropertyValue::UInt(read_unsigned_integer(reader)?)),
        9 => Ok(PropertyValue::SInt(read_signed_integer(reader)?)),
        10 => Ok(PropertyValue::AString(read_ascii_string(reader)?)),
        11 => Ok(PropertyValue::BString(read_byte_string(reader)?)),
        12 => Ok(PropertyValue::NString(read_name_string(reader)?)),
        13 => Ok(PropertyValue::AStringRef(read_unsigned_integer(reader)?)),
        14 => Ok(PropertyValue::BStringRef(read_unsigned_integer(reader)?)),
        15 => Ok(PropertyValue::NStringRef(read_unsigned_integer(reader)?)),
        _ => Err(OASISReadError::FormatError)
    }
}

pub fn _write_property_value<W: Write>(writer: &mut W, property_value: &PropertyValue) -> Result<(), OASISWriteError> {
    match property_value {
        PropertyValue::Real(r) => write_real(writer, *r)?,
        PropertyValue::UInt(u) => write_unsigned_integer(writer, *u)?,
        PropertyValue::SInt(s) => write_signed_integer(writer, *s)?,
        PropertyValue::AString(s) => write_ascii_string(writer, s.as_ref())?,
        PropertyValue::BString(s) => write_byte_string(writer, s.as_ref())?,
        PropertyValue::NString(s) => write_name_string(writer, s.as_ref())?,
        PropertyValue::AStringRef(u) | PropertyValue::BStringRef(u) | PropertyValue::NStringRef(u)
        => write_unsigned_integer(writer, *u)?
    };
    Ok(())
}