diff --git a/docs/writing-s57-charts.md b/docs/writing-s57-charts.md index 0335875..349a566 100644 --- a/docs/writing-s57-charts.md +++ b/docs/writing-s57-charts.md @@ -60,29 +60,31 @@ var document = new S57Document DataSetIdentification = new S57DataSetIdentification { RecordName = S57RecordName.FromRcnmRcid(S57RecordNameCodes.DataSetGeneralInfo, 1), - ExchangePurpose = 1, + ExchangePurpose = (int)S57ExchangePurpose.New, IntendedUsage = 5, DataSetName = "XX5EXAMP.000", EditionNumber = "1", UpdateNumber = "0", IssueDate = "20260101", S57EditionNumber = "03.1", - ProductSpecification = 1, - ApplicationProfile = 1, + ProductSpecification = (int)S57ProductSpecification.Enc, + ApplicationProfile = (int)S57ApplicationProfile.EncNew, ProducingAgency = 550, - DataStructure = 2, - AttfLexicalLevel = 1, - NatfLexicalLevel = 2 + DataStructure = (int)S57DataStructure.ChainNode, + AttfLexicalLevel = (int)S57LexicalLevel.Latin1, + NatfLexicalLevel = (int)S57LexicalLevel.Ucs2 }, DataSetParameters = new S57DataSetParameters { RecordName = S57RecordName.FromRcnmRcid(S57RecordNameCodes.DataSetGeoReference, 1), - HorizontalDatum = 2, + HorizontalDatum = (int)S57HorizontalDatum.WGS84, + VerticalDatum = (int)S57VerticalDatum.MeanSeaLevel, + SoundingDatum = (int)S57VerticalDatum.LowestAstronomicalTide, CompilationScale = 22000, - DepthUnits = 1, - HeightUnits = 1, - PositionalUnits = 1, - CoordinateUnits = 1, + DepthUnits = (int)S57DepthUnits.Metres, + HeightUnits = (int)S57HeightUnits.Metres, + PositionalUnits = (int)S57PositionalAccuracyUnits.Metres, + CoordinateUnits = (int)S57CoordinateUnits.LatitudeLongitude, CoordinateMultiplicationFactor = 10_000_000, SoundingMultiplicationFactor = 10 }, @@ -131,6 +133,27 @@ var document = new S57Document byte[] cell = S57DocumentWriter.Write(document); ``` +The coded `DSID` and `DSPM` subfields are `int` properties. Enums name their +values, and each value is the S-57 code, so cast in either direction: + +| Subfield | Property | Enum | +|---|---|---| +| `EXPP` | `ExchangePurpose` | `S57ExchangePurpose` | +| `PRSP` | `ProductSpecification` | `S57ProductSpecification` | +| `PROF` | `ApplicationProfile` | `S57ApplicationProfile` | +| `DSTR` | `DataStructure` | `S57DataStructure` | +| `AALL`, `NALL` | `AttfLexicalLevel`, `NatfLexicalLevel` | `S57LexicalLevel` | +| `HDAT` | `HorizontalDatum` | `S57HorizontalDatum` | +| `VDAT`, `SDAT` | `VerticalDatum`, `SoundingDatum` | `S57VerticalDatum` | +| `DUNI` | `DepthUnits` | `S57DepthUnits` | +| `HUNI` | `HeightUnits` | `S57HeightUnits` | +| `PUNI` | `PositionalUnits` | `S57PositionalAccuracyUnits` | +| `COUN` | `CoordinateUnits` | `S57CoordinateUnits` | + +A code an enum doesn't name, such as an AML product code, casts to an unnamed +value. To interpret the product of a cell you've read, use +`DataSetIdentification.Product` instead. + Coordinates and soundings are integers scaled by `COMF` and `SOMF`, as the reader gives them. A feature's long name (`AGEN`, `FIDN`, `FIDS`) goes in its `RecordName` and is written as its `FOID` field. A feature without one gets a @@ -154,6 +177,19 @@ being replaced. Put text like that in a national attribute with `NALL` set to 2. UCS-2 covers the Basic Multilingual Plane only, so characters outside it, such as emoji, can't be written at any level. +The writer uses the levels the document sets. To use the lowest levels that +encode the document's attribute values, pass the document through +`S57LexicalLevels.WithLowestLevels` before writing it. It throws +`ArgumentException` if an `ATTF` value needs UCS-2: + +```csharp +byte[] cell = S57DocumentWriter.Write(S57LexicalLevels.WithLowestLevels(document)); +``` + +For other text, `S57LexicalLevels.Lowest` returns the lowest level that encodes +a set of strings, and `S57LexicalLevels.CanEncode` checks one string. They make +the same checks as the writer. + The writer declares the levels in the DDR, as S-57 requires. It writes a level 2 `NATF` field with two-byte terminators. diff --git a/src/EncDotNet.S57/S57ApplicationProfile.cs b/src/EncDotNet.S57/S57ApplicationProfile.cs new file mode 100644 index 0000000..c4ec10b --- /dev/null +++ b/src/EncDotNet.S57/S57ApplicationProfile.cs @@ -0,0 +1,24 @@ +namespace EncDotNet.S57; + +/// +/// The application profile identification codes of the DSID subfield PROF (S-57 Edition 3.1, +/// Part 3 §7.3.1.1 and §1.4.2). +/// +/// +/// The values are the exact S-57 codes, so cast between this enum and +/// in either direction. NATO Additional +/// Military Layers (AML) data sets use other codes (see +/// ), which cast to unnamed values +/// rather than failing. +/// +public enum S57ApplicationProfile +{ + /// ENC new (EN, code 1): a base cell. + EncNew = 1, + + /// ENC revision (ER, code 2): an update cell. + EncRevision = 2, + + /// IHO data dictionary (DD, code 3). + DataDictionary = 3 +} diff --git a/src/EncDotNet.S57/S57CoordinateUnits.cs b/src/EncDotNet.S57/S57CoordinateUnits.cs new file mode 100644 index 0000000..54bc10b --- /dev/null +++ b/src/EncDotNet.S57/S57CoordinateUnits.cs @@ -0,0 +1,22 @@ +namespace EncDotNet.S57; + +/// +/// The coordinate unit codes of the DSPM subfield COUN (S-57 Edition 3.1, Part 3 §7.3.2.1 and +/// clause 3.2.1). +/// +/// +/// The values are the exact S-57 codes, so cast between this enum and +/// in either direction. A code S-57 doesn't +/// define casts to an unnamed value rather than failing. +/// +public enum S57CoordinateUnits +{ + /// Latitude and longitude (LL, code 1). + LatitudeLongitude = 1, + + /// Easting and northing (EN, code 2). + EastingNorthing = 2, + + /// Units on the chart or map (UC, code 3). + UnitsOnChart = 3 +} diff --git a/src/EncDotNet.S57/S57DataSetIdentification.cs b/src/EncDotNet.S57/S57DataSetIdentification.cs index e20565a..eee1cf7 100644 --- a/src/EncDotNet.S57/S57DataSetIdentification.cs +++ b/src/EncDotNet.S57/S57DataSetIdentification.cs @@ -12,7 +12,7 @@ public sealed record S57DataSetIdentification /// /// S-57 Edition 3.1, Part 3 §7.3.1.1 enumerates 1 = N (data set is new) and 2 = R (data set /// is a revision). The value is 0 when the subfield is absent; - /// writes 0 as 1. + /// writes 0 as 1. names the codes; cast between the two. /// public int ExchangePurpose { get; init; } @@ -41,12 +41,24 @@ public sealed record S57DataSetIdentification public int ProducingAgency { get; init; } /// Gets the data structure (DSTR). + /// + /// The values are the DSSI codes of S-57 Edition 3.1, Part 3 §7.3.1.2, which + /// names; cast between the two. + /// public int DataStructure { get; init; } /// Gets the lexical level for ATTF (AALL). + /// + /// names the levels; cast between the two. ATTF allows levels 0 + /// and 1 only. picks the lowest level for a set of values. + /// public int AttfLexicalLevel { get; init; } /// Gets the lexical level for NATF (NALL). + /// + /// names the levels; cast between the two. + /// picks the lowest level for a set of values. + /// public int NatfLexicalLevel { get; init; } /// Gets the comment (COMT). @@ -63,7 +75,8 @@ public sealed record S57DataSetIdentification /// Additional Military Layers (AML) producers declare 51-57 (see /// ). When the data set uses the ASCII lexical form, the mnemonics /// ENC and ODD are mapped to 1 and 2. The value is 0 when the subfield is - /// absent. interprets it. + /// absent. interprets it. To set it, cast from + /// (or ). /// public int ProductSpecification { get; init; } @@ -81,6 +94,7 @@ public sealed record S57DataSetIdentification /// SBO 18/19), and AML 3.0 uses 20 for both. When the data set uses the ASCII lexical form, /// the S-57 mnemonics are mapped to their numeric codes. The value is 0 when the subfield is /// absent. interprets it. + /// names the S-57 codes; cast between the two. /// public int ApplicationProfile { get; init; } diff --git a/src/EncDotNet.S57/S57DataSetParameters.cs b/src/EncDotNet.S57/S57DataSetParameters.cs index cccec6c..72115f5 100644 --- a/src/EncDotNet.S57/S57DataSetParameters.cs +++ b/src/EncDotNet.S57/S57DataSetParameters.cs @@ -9,27 +9,55 @@ public sealed record S57DataSetParameters public S57RecordName RecordName { get; init; } /// Gets the horizontal geodetic datum (HDAT). + /// + /// The values are those of the attribute HORDAT, which + /// names; cast between the two. 2 is WGS 84. + /// public int HorizontalDatum { get; init; } /// Gets the vertical datum (VDAT). + /// + /// The values are those of the attribute VERDAT, which + /// names; cast between the two. + /// public int VerticalDatum { get; init; } /// Gets the sounding datum (SDAT). + /// + /// The values are those of the attribute VERDAT, which + /// names; cast between the two. + /// public int SoundingDatum { get; init; } /// Gets the compilation scale (CSCL). public int CompilationScale { get; init; } /// Gets the units of depth measurement (DUNI). + /// + /// The values are those of the attribute DUNITS, which names; + /// cast between the two. + /// public int DepthUnits { get; init; } /// Gets the units of height measurement (HUNI). + /// + /// The values are those of the attribute HUNITS, which names; + /// cast between the two. + /// public int HeightUnits { get; init; } /// Gets the units of positional accuracy (PUNI). + /// + /// The values are those of the attribute PUNITS, which + /// names; cast between the two. + /// public int PositionalUnits { get; init; } /// Gets the coordinate units (COUN). + /// + /// names the codes of S-57 Edition 3.1, Part 3 §7.3.2.1; cast + /// between the two. + /// public int CoordinateUnits { get; init; } /// Gets the coordinate multiplication factor (COMF). diff --git a/src/EncDotNet.S57/S57DataStructure.cs b/src/EncDotNet.S57/S57DataStructure.cs new file mode 100644 index 0000000..d0fb913 --- /dev/null +++ b/src/EncDotNet.S57/S57DataStructure.cs @@ -0,0 +1,29 @@ +namespace EncDotNet.S57; + +/// +/// The data structure codes of the DSSI subfield DSTR (S-57 Edition 3.1, Part 3 §7.3.1.2 and +/// clause 3.1; Part 2 describes the topology levels). +/// +/// +/// The values are the exact S-57 codes, so cast between this enum and +/// in either direction. A code S-57 doesn't +/// define casts to an unnamed value rather than failing. The ENC product specification requires +/// . +/// +public enum S57DataStructure +{ + /// Cartographic spaghetti (CS, code 1). + CartographicSpaghetti = 1, + + /// Chain-node (CN, code 2). + ChainNode = 2, + + /// Planar graph (PG, code 3). + PlanarGraph = 3, + + /// Full topology (FT, code 4). + FullTopology = 4, + + /// Topology is not relevant (NO, code 255). + TopologyNotRelevant = 255 +} diff --git a/src/EncDotNet.S57/S57DepthUnits.cs b/src/EncDotNet.S57/S57DepthUnits.cs new file mode 100644 index 0000000..9d33da4 --- /dev/null +++ b/src/EncDotNet.S57/S57DepthUnits.cs @@ -0,0 +1,25 @@ +namespace EncDotNet.S57; + +/// +/// The depth units of the DSPM subfield DUNI, which takes its values from the attribute +/// DUNITS (S-57 Edition 3.1, Part 3 §7.3.2.1; Appendix A, chapter 2, attribute 89). +/// +/// +/// The values are the exact S-57 codes, so cast between this enum and +/// (or a DUNITS attribute value) in either +/// direction. A code S-57 doesn't define casts to an unnamed value rather than failing. +/// +public enum S57DepthUnits +{ + /// Metres (code 1). + Metres = 1, + + /// Fathoms and feet (code 2). + FathomsAndFeet = 2, + + /// Feet (code 3). + Feet = 3, + + /// Fathoms and fractions of fathoms (code 4). + FathomsAndFractions = 4 +} diff --git a/src/EncDotNet.S57/S57ExchangePurpose.cs b/src/EncDotNet.S57/S57ExchangePurpose.cs new file mode 100644 index 0000000..e11c6d0 --- /dev/null +++ b/src/EncDotNet.S57/S57ExchangePurpose.cs @@ -0,0 +1,18 @@ +namespace EncDotNet.S57; + +/// +/// The exchange purpose codes of the DSID subfield EXPP (S-57 Edition 3.1, Part 3 §7.3.1.1). +/// +/// +/// The values are the exact S-57 codes, so cast between this enum and +/// in either direction. A code S-57 doesn't +/// define casts to an unnamed value rather than failing. +/// +public enum S57ExchangePurpose +{ + /// The data set is new (N, code 1). + New = 1, + + /// The data set is a revision to an existing one (R, code 2). + Revision = 2 +} diff --git a/src/EncDotNet.S57/S57FieldEncoder.cs b/src/EncDotNet.S57/S57FieldEncoder.cs index a82b437..397df8e 100644 --- a/src/EncDotNet.S57/S57FieldEncoder.cs +++ b/src/EncDotNet.S57/S57FieldEncoder.cs @@ -172,18 +172,50 @@ public Iso8211Field ToField(string tag, bool twoByteTerminator = false) return new Iso8211Field { Tag = tag, Data = _buffer.WrittenSpan.ToArray() }; } - private void Encode(string value, string subfield, Encoding encoding) + /// + /// Gets whether can encode a value with an encoding, without throwing. + /// + /// + /// This makes the same checks as the encoder, so and the + /// writers can't disagree about which lexical level a string needs. + /// + public static bool CanEncode(string value, Encoding encoding) { if (ReferenceEquals(encoding, Ucs2)) { - // UCS-2 implementation level 1 covers the Basic Multilingual Plane only. - foreach (var c in value) - { - if (char.IsSurrogate(c)) - { - throw Invalid($"{subfield} value '{value}' has a character outside the Basic Multilingual Plane, which UCS-2 (lexical level 2) can't encode"); - } - } + return !HasSurrogate(value); + } + + try + { + encoding.GetByteCount(value); + return true; + } + catch (EncoderFallbackException) + { + return false; + } + } + + /// Gets the encoding of a lexical level (S-57 Part 3, clause 2.4). + public static Encoding ForLexicalLevel(S57LexicalLevel level) => level switch + { + S57LexicalLevel.Ascii => Ascii, + S57LexicalLevel.Latin1 => Latin1, + S57LexicalLevel.Ucs2 => Ucs2, + _ => throw new ArgumentOutOfRangeException(nameof(level), level, "S-57 defines lexical levels 0, 1 and 2 only.") + }; + + // UCS-2 implementation level 1 covers the Basic Multilingual Plane only, so neither half of + // a UTF-16 surrogate pair (nor an unpaired surrogate) can be encoded. + private static bool HasSurrogate(string value) => + value.AsSpan().IndexOfAnyInRange('\uD800', '\uDFFF') >= 0; + + private void Encode(string value, string subfield, Encoding encoding) + { + if (ReferenceEquals(encoding, Ucs2) && HasSurrogate(value)) + { + throw Invalid($"{subfield} value '{value}' has a character outside the Basic Multilingual Plane, which UCS-2 (lexical level 2) can't encode"); } try diff --git a/src/EncDotNet.S57/S57HeightUnits.cs b/src/EncDotNet.S57/S57HeightUnits.cs new file mode 100644 index 0000000..210362f --- /dev/null +++ b/src/EncDotNet.S57/S57HeightUnits.cs @@ -0,0 +1,20 @@ +namespace EncDotNet.S57; + +/// +/// The height and length units of the DSPM subfield HUNI, which takes its values from the +/// attribute HUNITS (S-57 Edition 3.1, Part 3 §7.3.2.1; Appendix A, chapter 2, +/// attribute 96). +/// +/// +/// The values are the exact S-57 codes, so cast between this enum and +/// (or an HUNITS attribute value) in either +/// direction. A code S-57 doesn't define casts to an unnamed value rather than failing. +/// +public enum S57HeightUnits +{ + /// Metres (code 1). + Metres = 1, + + /// Feet (code 2). + Feet = 2 +} diff --git a/src/EncDotNet.S57/S57HorizontalDatum.cs b/src/EncDotNet.S57/S57HorizontalDatum.cs new file mode 100644 index 0000000..52892c2 --- /dev/null +++ b/src/EncDotNet.S57/S57HorizontalDatum.cs @@ -0,0 +1,409 @@ +namespace EncDotNet.S57; + +/// +/// The horizontal geodetic datums of the DSPM subfield HDAT, which takes its values from the +/// attribute HORDAT (S-57 Edition 3.1, Part 3 §7.3.2.1; Appendix A, chapter 2, +/// attribute 400). +/// +/// +/// The values are the exact S-57 codes, so cast between this enum and +/// (or a HORDAT attribute value) in +/// either direction. A code S-57 doesn't define casts to an unnamed value rather than failing. +/// The ENC product specification requires . The member names follow the +/// datum names in Appendix A. +/// +public enum S57HorizontalDatum +{ + /// WGS 72 (code 1). + WGS72 = 1, + + /// WGS 84 (code 2). + WGS84 = 2, + + /// European 1950 (code 3). + European1950 = 3, + + /// Potsdam Datum (code 4). + PotsdamDatum = 4, + + /// Adindan (code 5). + Adindan = 5, + + /// Afgooye (code 6). + Afgooye = 6, + + /// Ain el Abd 1970 (code 7). + AinElAbd1970 = 7, + + /// Anna 1 Astro 1965 (code 8). + Anna1Astro1965 = 8, + + /// Antigua Island Astro 1943 (code 9). + AntiguaIslandAstro1943 = 9, + + /// Arc 1950 (code 10). + Arc1950 = 10, + + /// Arc 1960 (code 11). + Arc1960 = 11, + + /// Ascension Island 1958 (code 12). + AscensionIsland1958 = 12, + + /// Astro beacon "E" 1945 (code 13). + AstroBeaconE1945 = 13, + + /// Astro DOS 71/4 (code 14). + AstroDOS714 = 14, + + /// Astro Tern Island (FRIG) 1961 (code 15). + AstroTernIsland1961 = 15, + + /// Astronomical Station 1952 (code 16). + AstronomicalStation1952 = 16, + + /// Australian Geodetic 1966 (code 17). + AustralianGeodetic1966 = 17, + + /// Australian Geodetic 1984 (code 18). + AustralianGeodetic1984 = 18, + + /// Ayabelle Lighthouse (code 19). + AyabelleLighthouse = 19, + + /// Bellevue (IGN) (code 20). + BellevueIGN = 20, + + /// Bermuda 1957 (code 21). + Bermuda1957 = 21, + + /// Bissau (code 22). + Bissau = 22, + + /// Bogota Observatory (code 23). + BogotaObservatory = 23, + + /// Bukit Rimpah (code 24). + BukitRimpah = 24, + + /// Camp Area Astro (code 25). + CampAreaAstro = 25, + + /// Campo Inchauspe 1969 (code 26). + CampoInchauspe1969 = 26, + + /// Canton Astro 1966 (code 27). + CantonAstro1966 = 27, + + /// Cape (code 28). + Cape = 28, + + /// Cape Canaveral (code 29). + CapeCanaveral = 29, + + /// Carthage (code 30). + Carthage = 30, + + /// Chatam Island Astro 1971 (code 31). + ChatamIslandAstro1971 = 31, + + /// Chua Astro (code 32). + ChuaAstro = 32, + + /// Corrego Alegre (code 33). + CorregoAlegre = 33, + + /// Dabola (code 34). + Dabola = 34, + + /// Djakarta (Batavia) (code 35). + Djakarta = 35, + + /// DOS 1968 (code 36). + DOS1968 = 36, + + /// Easter Island 1967 (code 37). + EasterIsland1967 = 37, + + /// European 1979 (code 38). + European1979 = 38, + + /// Fort Thomas 1955 (code 39). + FortThomas1955 = 39, + + /// Gan 1970 (code 40). + Gan1970 = 40, + + /// Geodetic Datum 1949 (code 41). + GeodeticDatum1949 = 41, + + /// Graciosa Base SW 1948 (code 42). + GraciosaBaseSW1948 = 42, + + /// Guam 1963 (code 43). + Guam1963 = 43, + + /// Gunung Segara (code 44). + GunungSegara = 44, + + /// GUX 1 Astro (code 45). + GUX1Astro = 45, + + /// Herat North (code 46). + HeratNorth = 46, + + /// Hjorsey 1955 (code 47). + Hjorsey1955 = 47, + + /// Hong Kong 1963 (code 48). + HongKong1963 = 48, + + /// Hu-Tzu-Shan (code 49). + HuTzuShan = 49, + + /// Indian (code 50). + Indian = 50, + + /// Indian 1954 (code 51). + Indian1954 = 51, + + /// Indian 1975 (code 52). + Indian1975 = 52, + + /// Ireland 1965 (code 53). + Ireland1965 = 53, + + /// ISTS 061 Astro 1968 (code 54). + ISTS061Astro1968 = 54, + + /// ISTS 073 Astro 1969 (code 55). + ISTS073Astro1969 = 55, + + /// Johnston Island 1961 (code 56). + JohnstonIsland1961 = 56, + + /// Kandawala (code 57). + Kandawala = 57, + + /// Kerguelen Island 1949 (code 58). + KerguelenIsland1949 = 58, + + /// Kertau 1948 (code 59). + Kertau1948 = 59, + + /// Kusaie Astro 1951 (code 60). + KusaieAstro1951 = 60, + + /// L. C. 5 Astro 1961 (code 61). + LC5Astro1961 = 61, + + /// Leigon (code 62). + Leigon = 62, + + /// Liberia 1964 (code 63). + Liberia1964 = 63, + + /// Luzon (code 64). + Luzon = 64, + + /// Mahe 1971 (code 65). + Mahe1971 = 65, + + /// Massawa (code 66). + Massawa = 66, + + /// Merchich (code 67). + Merchich = 67, + + /// Midway Astro 1961 (code 68). + MidwayAstro1961 = 68, + + /// Minna (code 69). + Minna = 69, + + /// Montserrat Island Astro 1958 (code 70). + MontserratIslandAstro1958 = 70, + + /// M'Poraloko (code 71). + MPoraloko = 71, + + /// Nahrwan (code 72). + Nahrwan = 72, + + /// Naparima, BWI (code 73). + NaparimaBWI = 73, + + /// North American 1927 (code 74). + NorthAmerican1927 = 74, + + /// North American 1983 (code 75). + NorthAmerican1983 = 75, + + /// Observatorio Meteorologico 1939 (code 76). + ObservatorioMeteorologico1939 = 76, + + /// Old Egyptian 1907 (code 77). + OldEgyptian1907 = 77, + + /// Old Hawaiian (code 78). + OldHawaiian = 78, + + /// Oman (code 79). + Oman = 79, + + /// Ordnance Survey of Great Britain 1936 (code 80). + OrdnanceSurveyOfGreatBritain1936 = 80, + + /// Pico de las Nieves (code 81). + PicoDeLasNieves = 81, + + /// Pitcairn Astro 1967 (code 82). + PitcairnAstro1967 = 82, + + /// Point 58 (code 83). + Point58 = 83, + + /// Pointe Noire 1948 (code 84). + PointeNoire1948 = 84, + + /// Porto Santo 1936 (code 85). + PortoSanto1936 = 85, + + /// Provisional South American 1956 (code 86). + ProvisionalSouthAmerican1956 = 86, + + /// Provisional South Chilean 1963 (also known as Hito XVIII 1963) (code 87). + ProvisionalSouthChilean1963 = 87, + + /// Puerto Rico (code 88). + PuertoRico = 88, + + /// Qatar national (code 89). + QatarNational = 89, + + /// Qornoq (code 90). + Qornoq = 90, + + /// Reunion (code 91). + Reunion = 91, + + /// Rome 1940 (code 92). + Rome1940 = 92, + + /// Santo (DOS) 1965 (code 93). + SantoDOS1965 = 93, + + /// Sao Braz (code 94). + SaoBraz = 94, + + /// Sapper Hill 1943 (code 95). + SapperHill1943 = 95, + + /// Schwarzeck (code 96). + Schwarzeck = 96, + + /// Selvagem Grande 1938 (code 97). + SelvagemGrande1938 = 97, + + /// South American 1969 (code 98). + SouthAmerican1969 = 98, + + /// South Asia (code 99). + SouthAsia = 99, + + /// Tananarive Observatory 1925 (code 100). + TananariveObservatory1925 = 100, + + /// Timbalai 1948 (code 101). + Timbalai1948 = 101, + + /// Tokyo (code 102). + Tokyo = 102, + + /// Tristan Astro 1968 (code 103). + TristanAstro1968 = 103, + + /// Viti Levu 1916 (code 104). + VitiLevu1916 = 104, + + /// Wake-Eniwetok 1960 (code 105). + WakeEniwetok1960 = 105, + + /// Wake Island Astro 1952 (code 106). + WakeIslandAstro1952 = 106, + + /// Yacare (code 107). + Yacare = 107, + + /// Zanderij (code 108). + Zanderij = 108, + + /// American Samoa 1962 (code 109). + AmericanSamoa1962 = 109, + + /// Deception Island (code 110). + DeceptionIsland = 110, + + /// Indian 1960 (code 111). + Indian1960 = 111, + + /// Indonesian 1974 (code 112). + Indonesian1974 = 112, + + /// North Sahara 1959 (code 113). + NorthSahara1959 = 113, + + /// Pulkovo 1942 (code 114). + Pulkovo1942 = 114, + + /// S-42 (Pulkovo 1942) (code 115). + S42Pulkovo1942 = 115, + + /// S-JYSK (code 116). + SJYSK = 116, + + /// Voirol 1950 (code 117). + Voirol1950 = 117, + + /// Average Terrestrial System 1977 (code 118). + AverageTerrestrialSystem1977 = 118, + + /// Compensation Géodésique du Québec 1977 (code 119). + CompensationGeodesiqueDuQuebec1977 = 119, + + /// Finnish (KKJ) (code 120). + FinnishKKJ = 120, + + /// Ordnance Survey of Ireland (code 121). + OrdnanceSurveyOfIreland = 121, + + /// Revised Kertau (code 122). + RevisedKertau = 122, + + /// Revised Nahrwan (code 123). + RevisedNahrwan = 123, + + /// GGRS 76 (Greece) (code 124). + GGRS76 = 124, + + /// Nouvelle Triangulation de France (code 125). + NouvelleTriangulationDeFrance = 125, + + /// RT 90 (Sweden) (code 126). + RT90 = 126, + + /// Geocentric Datum of Australia (GDA) (code 127). + GeocentricDatumOfAustralia = 127, + + /// BJZ54 (A954 Beijing Coordinates) (code 128). + BJZ54 = 128, + + /// Modified BJZ54 (code 129). + ModifiedBJZ54 = 129, + + /// GDZ80 (code 130). + GDZ80 = 130, + + /// Local datum (code 131). + LocalDatum = 131 +} diff --git a/src/EncDotNet.S57/S57LexicalLevel.cs b/src/EncDotNet.S57/S57LexicalLevel.cs new file mode 100644 index 0000000..4a1f466 --- /dev/null +++ b/src/EncDotNet.S57/S57LexicalLevel.cs @@ -0,0 +1,27 @@ +namespace EncDotNet.S57; + +/// +/// The S-57 lexical levels, the character sets that the DSSI subfields AALL (for ATTF) and NALL +/// (for NATF) declare (S-57 Edition 3.1, Part 3, clause 2.4). +/// +/// +/// The values are the exact AALL and NALL codes, so cast between this enum and +/// or +/// in either direction. ATTF allows +/// levels 0 and 1 only; NATF allows all three. Use to pick +/// the lowest level that can encode a set of values. +/// +public enum S57LexicalLevel +{ + /// Level 0: ASCII, the IRV of ISO/IEC 646, which S-57 calls the basic character set. + Ascii = 0, + + /// Level 1: ISO 8859-1, Latin alphabet 1. + Latin1 = 1, + + /// + /// Level 2: UCS-2 (ISO/IEC 10646 implementation level 1), little-endian, which covers the + /// Basic Multilingual Plane only. + /// + Ucs2 = 2 +} diff --git a/src/EncDotNet.S57/S57LexicalLevels.cs b/src/EncDotNet.S57/S57LexicalLevels.cs new file mode 100644 index 0000000..8851462 --- /dev/null +++ b/src/EncDotNet.S57/S57LexicalLevels.cs @@ -0,0 +1,116 @@ +namespace EncDotNet.S57; + +/// +/// Provides methods to choose the S-57 lexical levels (DSSI AALL and NALL) for character data. +/// +/// +/// +/// These methods make the same checks as , so a level they pick +/// is one the writer can encode the values at (S-57 Edition 3.1, Part 3, clause 2.4). +/// +/// +/// UCS-2 covers the Basic Multilingual Plane only. A character outside it, which .NET holds as a +/// UTF-16 surrogate pair (an emoji, for example), can't be encoded at any lexical level, and an +/// unpaired surrogate can't either. +/// +/// +public static class S57LexicalLevels +{ + /// + /// Gets whether a value can be encoded at a lexical level. + /// + /// The value. is treated as an empty string. + /// The lexical level. + /// + /// if every character of is in the character + /// set of ; otherwise, . + /// + /// isn't 0, 1 or 2. + public static bool CanEncode(string? value, S57LexicalLevel level) => + S57FieldEncoder.CanEncode(value ?? string.Empty, S57FieldEncoder.ForLexicalLevel(level)); + + /// + /// Gets the lowest lexical level that can encode every one of a set of values. + /// + /// + /// The values, such as the ATTF or NATF attribute values of a data set. + /// values are treated as empty strings. + /// + /// + /// if every value is ASCII (including when there are no + /// values), if every value is ISO 8859-1, and otherwise + /// . + /// + /// is . + /// + /// A value has a character outside the Basic Multilingual Plane (a surrogate pair) or an + /// unpaired surrogate, which no lexical level can encode. + /// + public static S57LexicalLevel Lowest(IEnumerable values) + { + ArgumentNullException.ThrowIfNull(values); + + var level = S57LexicalLevel.Ascii; + foreach (var value in values) + { + // Levels are nested (ASCII within ISO 8859-1 within UCS-2), so a value never moves the + // level down, and each value is checked from the level reached so far. + while (!CanEncode(value, level)) + { + if (level == S57LexicalLevel.Ucs2) + { + throw new ArgumentException( + $"The value '{value}' has a character outside the Basic Multilingual Plane, which no S-57 lexical level can encode (S-57 Part 3, clause 2.4).", + nameof(values)); + } + + level++; + } + } + + return level; + } + + /// + /// Returns a copy of a document whose DSSI lexical levels (AALL and NALL) are the lowest that + /// can encode its feature records' ATTF and NATF values. + /// + /// The document. It must have a data set identification (DSID). + /// + /// A copy of whose + /// and + /// are set from + /// . The levels may be lower than the document's. + /// + /// + /// writes the levels the document holds. Call this before + /// writing a document built in memory to have the writer use the lowest levels instead. + /// + /// is . + /// + /// The document has no data set identification; an ATTF value needs UCS-2, which ATTF doesn't + /// allow; or a value has a character that no lexical level can encode. + /// + public static S57Document WithLowestLevels(S57Document document) + { + ArgumentNullException.ThrowIfNull(document); + + var dsid = document.DataSetIdentification + ?? throw new ArgumentException("The document has no data set identification (DSID).", nameof(document)); + + var attf = Lowest(document.FeatureRecords.SelectMany(f => f.Attributes).Select(a => a.Value)); + if (attf > S57LexicalLevel.Latin1) + { + throw new ArgumentException( + "An ATTF value has a character outside ISO 8859-1; ATTF allows only lexical levels 0 or 1 (S-57 Part 3, clause 2.4).", + nameof(document)); + } + + var natf = Lowest(document.FeatureRecords.SelectMany(f => f.NationalAttributes).Select(a => a.Value)); + + return document with + { + DataSetIdentification = dsid with { AttfLexicalLevel = (int)attf, NatfLexicalLevel = (int)natf } + }; + } +} diff --git a/src/EncDotNet.S57/S57PositionalAccuracyUnits.cs b/src/EncDotNet.S57/S57PositionalAccuracyUnits.cs new file mode 100644 index 0000000..c204030 --- /dev/null +++ b/src/EncDotNet.S57/S57PositionalAccuracyUnits.cs @@ -0,0 +1,29 @@ +namespace EncDotNet.S57; + +/// +/// The positional accuracy units of the DSPM subfield PUNI, which takes its values from the +/// attribute PUNITS (S-57 Edition 3.1, Part 3 §7.3.2.1; Appendix A, chapter 2, +/// attribute 189). +/// +/// +/// The values are the exact S-57 codes, so cast between this enum and +/// (or a PUNITS attribute value) in +/// either direction. A code S-57 doesn't define casts to an unnamed value rather than failing. +/// +public enum S57PositionalAccuracyUnits +{ + /// Metres (code 1). + Metres = 1, + + /// Degrees of arc (code 2). + DegreesOfArc = 2, + + /// Millimetres (code 3). + Millimetres = 3, + + /// Feet (code 4). + Feet = 4, + + /// Cables (code 5). + Cables = 5 +} diff --git a/src/EncDotNet.S57/S57ProductSpecification.cs b/src/EncDotNet.S57/S57ProductSpecification.cs new file mode 100644 index 0000000..fdd624b --- /dev/null +++ b/src/EncDotNet.S57/S57ProductSpecification.cs @@ -0,0 +1,34 @@ +namespace EncDotNet.S57; + +/// +/// The product specification codes of the DSID subfield PRSP (S-57 Edition 3.1, Part 3 §7.3.1.1 +/// and §1.4.1), for setting the code of a new data set. +/// +/// +/// +/// The values are the exact PRSP codes, so cast between this enum and +/// in either direction. To interpret +/// the code of a data set that has been read, use +/// instead: its groups the codes but doesn't hold them, so it can't +/// be cast to a PRSP code. +/// +/// +/// NATO Additional Military Layers (AML) products use the codes 51-57, which +/// names; its values are PRSP codes too. A code this enum doesn't +/// name, such as an AML code, casts to an unnamed value rather than failing. +/// +/// +public enum S57ProductSpecification +{ + /// An Electronic Navigational Chart (ENC, code 1). + Enc = 1, + + /// The IHO Object Catalogue Data Dictionary (ODD, code 2). + DataDictionary = 2, + + /// + /// An Inland ENC (code 10). This code is defined by the Inland ENC product specification, + /// not by S-57. + /// + InlandEnc = 10 +} diff --git a/src/EncDotNet.S57/S57VerticalDatum.cs b/src/EncDotNet.S57/S57VerticalDatum.cs new file mode 100644 index 0000000..f708a0e --- /dev/null +++ b/src/EncDotNet.S57/S57VerticalDatum.cs @@ -0,0 +1,105 @@ +namespace EncDotNet.S57; + +/// +/// The vertical datums of the DSPM subfields VDAT and SDAT, which take their values from the +/// attribute VERDAT (S-57 Edition 3.1, Part 3 §7.3.2.1; Appendix A, chapter 2, +/// attribute 185). +/// +/// +/// The values are the exact S-57 codes, so cast between this enum and +/// , +/// (or a VERDAT attribute value) in either direction. A code S-57 doesn't define casts to +/// an unnamed value rather than failing. +/// +public enum S57VerticalDatum +{ + /// Mean low water springs (code 1). + MeanLowWaterSprings = 1, + + /// Mean lower low water springs (code 2). + MeanLowerLowWaterSprings = 2, + + /// Mean sea level (code 3). + MeanSeaLevel = 3, + + /// Lowest low water (code 4). + LowestLowWater = 4, + + /// Mean low water (code 5). + MeanLowWater = 5, + + /// Lowest low water springs (code 6). + LowestLowWaterSprings = 6, + + /// Approximate mean low water springs (code 7). + ApproximateMeanLowWaterSprings = 7, + + /// Indian spring low water (code 8). + IndianSpringLowWater = 8, + + /// Low water springs (code 9). + LowWaterSprings = 9, + + /// Approximate lowest astronomical tide (code 10). + ApproximateLowestAstronomicalTide = 10, + + /// Nearly lowest low water (code 11). + NearlyLowestLowWater = 11, + + /// Mean lower low water (code 12). + MeanLowerLowWater = 12, + + /// Low water (code 13). + LowWater = 13, + + /// Approximate mean low water (code 14). + ApproximateMeanLowWater = 14, + + /// Approximate mean lower low water (code 15). + ApproximateMeanLowerLowWater = 15, + + /// Mean high water (code 16). + MeanHighWater = 16, + + /// Mean high water springs (code 17). + MeanHighWaterSprings = 17, + + /// High water (code 18). + HighWater = 18, + + /// Approximate mean sea level (code 19). + ApproximateMeanSeaLevel = 19, + + /// High water springs (code 20). + HighWaterSprings = 20, + + /// Mean higher high water (code 21). + MeanHigherHighWater = 21, + + /// Equinoctial spring low water (code 22). + EquinoctialSpringLowWater = 22, + + /// Lowest astronomical tide (code 23). + LowestAstronomicalTide = 23, + + /// Local datum (code 24). + LocalDatum = 24, + + /// International Great Lakes Datum 1985 (code 25). + InternationalGreatLakesDatum1985 = 25, + + /// Mean water level (code 26). + MeanWaterLevel = 26, + + /// Lower low water large tide (code 27). + LowerLowWaterLargeTide = 27, + + /// Higher high water large tide (code 28). + HigherHighWaterLargeTide = 28, + + /// Nearly highest high water (code 29). + NearlyHighestHighWater = 29, + + /// Highest astronomical tide (HAT) (code 30). + HighestAstronomicalTide = 30 +} diff --git a/tests/EncDotNet.UnitTests/S57DataSetCodeTests.cs b/tests/EncDotNet.UnitTests/S57DataSetCodeTests.cs new file mode 100644 index 0000000..4e9e533 --- /dev/null +++ b/tests/EncDotNet.UnitTests/S57DataSetCodeTests.cs @@ -0,0 +1,179 @@ +using EncDotNet.S57; + +namespace EncDotNet.UnitTests; + +// The codes are those of S-57 Edition 3.1, Part 3 §7.3.1.1, §7.3.1.2 and §7.3.2.1, and the +// attribute domains of Appendix A, chapter 2. +public class S57DataSetCodeTests +{ + [Fact] + public void ExchangePurpose_MatchesTheSpecification() + { + Assert.Equal(1, (int)S57ExchangePurpose.New); + Assert.Equal(2, (int)S57ExchangePurpose.Revision); + Assert.Equal(2, Enum.GetValues().Length); + } + + [Fact] + public void ProductSpecification_MatchesTheSpecification() + { + Assert.Equal(1, (int)S57ProductSpecification.Enc); + Assert.Equal(2, (int)S57ProductSpecification.DataDictionary); + Assert.Equal(10, (int)S57ProductSpecification.InlandEnc); + Assert.Equal(3, Enum.GetValues().Length); + } + + [Theory] + [InlineData(S57ProductSpecification.Enc, S57ProductKind.Enc)] + [InlineData(S57ProductSpecification.DataDictionary, S57ProductKind.DataDictionary)] + [InlineData(S57ProductSpecification.InlandEnc, S57ProductKind.InlandEnc)] + [InlineData((S57ProductSpecification)(int)EncDotNet.S57.Aml.AmlProduct.RAL, S57ProductKind.Aml)] + public void ProductSpecification_IsInterpretedAsItsProductKind(S57ProductSpecification code, S57ProductKind kind) + { + var dsid = new S57DataSetIdentification { ProductSpecification = (int)code }; + + Assert.Equal(kind, dsid.Product.Kind); + } + + [Fact] + public void ApplicationProfile_MatchesTheSpecification() + { + Assert.Equal(1, (int)S57ApplicationProfile.EncNew); + Assert.Equal(2, (int)S57ApplicationProfile.EncRevision); + Assert.Equal(3, (int)S57ApplicationProfile.DataDictionary); + Assert.Equal(3, Enum.GetValues().Length); + } + + [Fact] + public void DataStructure_MatchesTheSpecification() + { + Assert.Equal(1, (int)S57DataStructure.CartographicSpaghetti); + Assert.Equal(2, (int)S57DataStructure.ChainNode); + Assert.Equal(3, (int)S57DataStructure.PlanarGraph); + Assert.Equal(4, (int)S57DataStructure.FullTopology); + Assert.Equal(255, (int)S57DataStructure.TopologyNotRelevant); + Assert.Equal(5, Enum.GetValues().Length); + } + + [Fact] + public void CoordinateUnits_MatchesTheSpecification() + { + Assert.Equal(1, (int)S57CoordinateUnits.LatitudeLongitude); + Assert.Equal(2, (int)S57CoordinateUnits.EastingNorthing); + Assert.Equal(3, (int)S57CoordinateUnits.UnitsOnChart); + Assert.Equal(3, Enum.GetValues().Length); + } + + [Fact] + public void DepthUnits_MatchesDunits() + { + Assert.Equal(1, (int)S57DepthUnits.Metres); + Assert.Equal(2, (int)S57DepthUnits.FathomsAndFeet); + Assert.Equal(3, (int)S57DepthUnits.Feet); + Assert.Equal(4, (int)S57DepthUnits.FathomsAndFractions); + Assert.Equal(4, Enum.GetValues().Length); + } + + [Fact] + public void HeightUnits_MatchesHunits() + { + Assert.Equal(1, (int)S57HeightUnits.Metres); + Assert.Equal(2, (int)S57HeightUnits.Feet); + Assert.Equal(2, Enum.GetValues().Length); + } + + [Fact] + public void PositionalAccuracyUnits_MatchesPunits() + { + Assert.Equal(1, (int)S57PositionalAccuracyUnits.Metres); + Assert.Equal(2, (int)S57PositionalAccuracyUnits.DegreesOfArc); + Assert.Equal(3, (int)S57PositionalAccuracyUnits.Millimetres); + Assert.Equal(4, (int)S57PositionalAccuracyUnits.Feet); + Assert.Equal(5, (int)S57PositionalAccuracyUnits.Cables); + Assert.Equal(5, Enum.GetValues().Length); + } + + [Fact] + public void HorizontalDatum_MatchesHordat() + { + Assert.Equal(1, (int)S57HorizontalDatum.WGS72); + Assert.Equal(2, (int)S57HorizontalDatum.WGS84); + Assert.Equal(3, (int)S57HorizontalDatum.European1950); + Assert.Equal(74, (int)S57HorizontalDatum.NorthAmerican1927); + Assert.Equal(75, (int)S57HorizontalDatum.NorthAmerican1983); + Assert.Equal(127, (int)S57HorizontalDatum.GeocentricDatumOfAustralia); + Assert.Equal(131, (int)S57HorizontalDatum.LocalDatum); + + // HORDAT's domain is 1 to 131, with no gaps. + Assert.Equal(Enumerable.Range(1, 131), Enum.GetValues().Select(v => (int)v)); + } + + [Fact] + public void VerticalDatum_MatchesVerdat() + { + Assert.Equal(1, (int)S57VerticalDatum.MeanLowWaterSprings); + Assert.Equal(3, (int)S57VerticalDatum.MeanSeaLevel); + Assert.Equal(12, (int)S57VerticalDatum.MeanLowerLowWater); + Assert.Equal(23, (int)S57VerticalDatum.LowestAstronomicalTide); + Assert.Equal(24, (int)S57VerticalDatum.LocalDatum); + Assert.Equal(30, (int)S57VerticalDatum.HighestAstronomicalTide); + + // VERDAT's domain is 1 to 30, with no gaps. + Assert.Equal(Enumerable.Range(1, 30), Enum.GetValues().Select(v => (int)v)); + } + + [Fact] + public void LexicalLevel_MatchesTheSpecification() + { + Assert.Equal(0, (int)S57LexicalLevel.Ascii); + Assert.Equal(1, (int)S57LexicalLevel.Latin1); + Assert.Equal(2, (int)S57LexicalLevel.Ucs2); + } + + [Fact] + public void UnknownCodes_RoundTripThroughTheEnums() + { + var parameters = new S57DataSetParameters { HorizontalDatum = 200, CoordinateUnits = 9 }; + + var datum = (S57HorizontalDatum)parameters.HorizontalDatum; + var units = (S57CoordinateUnits)parameters.CoordinateUnits; + + Assert.False(Enum.IsDefined(datum)); + Assert.Equal(200, (int)datum); + Assert.Equal(9, (int)units); + } + + [Fact] + public void Codes_SetFromTheEnums_RoundTripThroughTheWriter() + { + var cell = S57WriterTestCells.SmallCell(); + cell = cell with + { + DataSetIdentification = cell.DataSetIdentification! with + { + ExchangePurpose = (int)S57ExchangePurpose.New, + ProductSpecification = (int)S57ProductSpecification.Enc, + ApplicationProfile = (int)S57ApplicationProfile.EncNew, + DataStructure = (int)S57DataStructure.ChainNode + }, + DataSetParameters = cell.DataSetParameters! with + { + HorizontalDatum = (int)S57HorizontalDatum.WGS84, + VerticalDatum = (int)S57VerticalDatum.MeanSeaLevel, + SoundingDatum = (int)S57VerticalDatum.LowestAstronomicalTide, + DepthUnits = (int)S57DepthUnits.Metres, + HeightUnits = (int)S57HeightUnits.Metres, + PositionalUnits = (int)S57PositionalAccuracyUnits.Metres, + CoordinateUnits = (int)S57CoordinateUnits.LatitudeLongitude + } + }; + + var read = S57DocumentReader.Read(S57DocumentWriter.Write(cell)); + + // The small cell already sets these codes, so it writes the same bytes as the golden. + Assert.Equal(S57DocumentWriter.Write(S57WriterTestCells.SmallCell()), S57DocumentWriter.Write(cell)); + Assert.Equal(S57DataStructure.ChainNode, (S57DataStructure)read.DataSetIdentification!.DataStructure); + Assert.Equal(S57HorizontalDatum.WGS84, (S57HorizontalDatum)read.DataSetParameters!.HorizontalDatum); + Assert.Equal(S57VerticalDatum.LowestAstronomicalTide, (S57VerticalDatum)read.DataSetParameters.SoundingDatum); + } +} diff --git a/tests/EncDotNet.UnitTests/S57LexicalLevelsTests.cs b/tests/EncDotNet.UnitTests/S57LexicalLevelsTests.cs new file mode 100644 index 0000000..d5bdbee --- /dev/null +++ b/tests/EncDotNet.UnitTests/S57LexicalLevelsTests.cs @@ -0,0 +1,141 @@ +using EncDotNet.S57; + +namespace EncDotNet.UnitTests; + +public class S57LexicalLevelsTests +{ + [Fact] + public void Lowest_OfNoValues_IsAscii() + { + Assert.Equal(S57LexicalLevel.Ascii, S57LexicalLevels.Lowest([])); + } + + [Fact] + public void Lowest_OfAsciiValues_IsAscii() + { + Assert.Equal(S57LexicalLevel.Ascii, S57LexicalLevels.Lowest(["North sea 1", "", null, "~\u007F"])); + } + + [Fact] + public void Lowest_OfLatin1Values_IsLatin1() + { + Assert.Equal(S57LexicalLevel.Latin1, S57LexicalLevels.Lowest(["North sea 1", "Bouée du Chêne 45°", "ÿ"])); + } + + [Fact] + public void Lowest_OfBmpValues_IsUcs2() + { + // The Latin-1 value after the Greek one doesn't lower the level. + Assert.Equal(S57LexicalLevel.Ucs2, S57LexicalLevels.Lowest(["Noordzee", "Βόρεια Θάλασσα", "Chêne"])); + Assert.Equal(S57LexicalLevel.Ucs2, S57LexicalLevels.Lowest(["Ā"])); + Assert.Equal(S57LexicalLevel.Ucs2, S57LexicalLevels.Lowest(["�"])); + } + + [Fact] + public void Lowest_OfNonBmpValue_Throws() + { + // Built here rather than as theory data, which would replace unpaired surrogates. + string[] values = + [ + "Harbour \U0001F6A2", // A surrogate pair. + "\uD800", // An unpaired high surrogate. + "\uDC00" // An unpaired low surrogate. + ]; + + foreach (var value in values) + { + Assert.Throws(() => S57LexicalLevels.Lowest(["ASCII", value])); + } + } + + [Fact] + public void Lowest_OfNull_Throws() + { + Assert.Throws(() => S57LexicalLevels.Lowest(null!)); + } + + [Theory] + [InlineData("abc", S57LexicalLevel.Ascii, true)] + [InlineData("é", S57LexicalLevel.Ascii, false)] + [InlineData("é", S57LexicalLevel.Latin1, true)] + [InlineData("Ω", S57LexicalLevel.Latin1, false)] + [InlineData("Ω", S57LexicalLevel.Ucs2, true)] + [InlineData("\U0001F6A2", S57LexicalLevel.Ucs2, false)] + [InlineData(null, S57LexicalLevel.Ascii, true)] + public void CanEncode_ChecksTheCharacterSet(string? value, S57LexicalLevel level, bool expected) + { + Assert.Equal(expected, S57LexicalLevels.CanEncode(value, level)); + } + + [Fact] + public void CanEncode_AtAnUndefinedLevel_Throws() + { + Assert.Throws(() => S57LexicalLevels.CanEncode("a", (S57LexicalLevel)3)); + } + + [Fact] + public void Lowest_AgreesWithTheWriter() + { + // A value one level up from the one picked can't be written at the level below it. + var cell = S57WriterTestCells.SmallCell(); + var natf = cell.FeatureRecords.SelectMany(f => f.NationalAttributes).Select(a => a.Value).ToList(); + var level = S57LexicalLevels.Lowest(natf); + + Assert.Equal(S57LexicalLevel.Ucs2, level); + Assert.Throws(() => S57DocumentWriter.Write(S57WriterTestCells.SmallCell(natfLexicalLevel: 1))); + } + + [Fact] + public void WithLowestLevels_WritesTheGoldenCell() + { + // The golden cell has Latin-1 ATTF values and Greek NATF values, at AALL 1 and NALL 2. + var cell = S57LexicalLevels.WithLowestLevels(S57WriterTestCells.SmallCell(0, 0)); + + Assert.Equal(1, cell.DataSetIdentification!.AttfLexicalLevel); + Assert.Equal(2, cell.DataSetIdentification.NatfLexicalLevel); + Assert.Equal(S57DocumentWriter.Write(S57WriterTestCells.SmallCell()), S57DocumentWriter.Write(cell)); + } + + [Theory] + [InlineData("North sea 1", "Noordzee 1", S57LexicalLevel.Ascii, S57LexicalLevel.Ascii)] + [InlineData("Mer du Nord °", "Noordzee 1", S57LexicalLevel.Latin1, S57LexicalLevel.Ascii)] + [InlineData("North sea 1", "Nordsee ü", S57LexicalLevel.Ascii, S57LexicalLevel.Latin1)] + [InlineData("Mer du Nord °", "Βόρεια Θάλασσα", S57LexicalLevel.Latin1, S57LexicalLevel.Ucs2)] + public void WithLowestLevels_RoundTripsThroughTheWriter( + string attf, string natf, S57LexicalLevel expectedAttf, S57LexicalLevel expectedNatf) + { + var cell = WithText(S57WriterTestCells.SmallCell(1, 2), attf, natf); + + var lowest = S57LexicalLevels.WithLowestLevels(cell); + var read = S57DocumentReader.Read(S57DocumentWriter.Write(lowest)); + + Assert.Equal(expectedAttf, (S57LexicalLevel)read.DataSetIdentification!.AttfLexicalLevel); + Assert.Equal(expectedNatf, (S57LexicalLevel)read.DataSetIdentification.NatfLexicalLevel); + Assert.Equal(lowest.FeatureRecords.SelectMany(f => f.Attributes), read.FeatureRecords.SelectMany(f => f.Attributes)); + Assert.Equal(lowest.FeatureRecords.SelectMany(f => f.NationalAttributes), read.FeatureRecords.SelectMany(f => f.NationalAttributes)); + } + + [Fact] + public void WithLowestLevels_AttfNeedingUcs2_Throws() + { + var cell = WithText(S57WriterTestCells.SmallCell(), "Βόρεια Θάλασσα", "Noordzee"); + + Assert.Throws(() => S57LexicalLevels.WithLowestLevels(cell)); + } + + [Fact] + public void WithLowestLevels_WithoutDsid_Throws() + { + Assert.Throws(() => S57LexicalLevels.WithLowestLevels(new S57Document())); + } + + // Replaces every ATTF and NATF value with one value each, keeping the attribute codes. + private static S57Document WithText(S57Document cell, string attf, string natf) => cell with + { + FeatureRecords = cell.FeatureRecords.Select(f => f with + { + Attributes = f.Attributes.Select(a => a with { Value = attf }).ToList(), + NationalAttributes = f.NationalAttributes.Select(a => a with { Value = natf }).ToList() + }).ToList() + }; +}