Skip to main content

proj_epsg_format/
lib.rs

1//! Binary format definition for proj-rust's embedded EPSG registry
2//! (`proj-core/data/epsg.bin`).
3//!
4//! This crate is the single source of truth for the container layout shared
5//! by the `proj-core` reader (`epsg_db`) and the `gen-registry` writer in
6//! `gen-reference`. Any change here is a format change: bump [`VERSION`],
7//! regenerate the registry, and let the CI reproducibility check
8//! (`scripts/check-registry-generation.sh`) prove writer and reader agree.
9//!
10//! The container is little-endian throughout: a fixed header (magic, version,
11//! twelve section counts) followed by packed variable-length records per
12//! section. Strings are `u16` length-prefixed UTF-8.
13
14#![forbid(unsafe_code)]
15
16/// `"EPSG"` in big-endian byte order.
17pub const MAGIC: u32 = 0x4550_5347;
18/// Container format version; bump on any layout or semantic change.
19pub const VERSION: u16 = 12;
20/// Fixed header: magic (4) + version (2) + reserved (2) + twelve `u32`
21/// section counts.
22pub const HEADER_SIZE: usize = 56;
23
24// Fixed-size record prefixes. "Base" sizes exclude the trailing
25// length-prefixed strings.
26pub const ELLIPSOID_RECORD_SIZE: usize = 20;
27pub const DATUM_RECORD_SIZE: usize = 12;
28/// Geographic CRS: code, datum code, authority axis order tag.
29pub const GEO_CRS_RECORD_BASE_SIZE: usize = 9;
30/// Geocentric CRS: code, datum code, base geographic CRS code.
31pub const GEOCENTRIC_CRS_RECORD_BASE_SIZE: usize = 12;
32pub const PROJ_CRS_RECORD_BASE_SIZE: usize = 80;
33pub const VERTICAL_CRS_RECORD_BASE_SIZE: usize = 16;
34pub const COMPOUND_CRS_RECORD_BASE_SIZE: usize = 28;
35
36// Authority axis order tags. The registry's CRS definitions are always east
37// then north; these record the order the authority itself assigns, for
38// identifiers defined to use it. Unsupported means axes `AxisOrder` cannot
39// state, such as south and west.
40pub const AXIS_ORDER_EAST_NORTH: u8 = 0;
41pub const AXIS_ORDER_NORTH_EAST: u8 = 1;
42pub const AXIS_ORDER_UNSUPPORTED: u8 = 2;
43/// Offset of the axis order tag in a geographic CRS record.
44pub const GEO_CRS_AXIS_ORDER_OFFSET: usize = 8;
45/// Offset of the axis order tag in a projected CRS record.
46pub const PROJ_CRS_AXIS_ORDER_OFFSET: usize = 13;
47
48// Datum→WGS84 relationship tags (definition metadata only; operation
49// selection never synthesizes transforms from these). Since version 9,
50// records carry only the WGS84-compatibility tag; per-datum Helmert values
51// are a generation-time input for deriving it and are not stored.
52pub const DATUM_SHIFT_UNKNOWN: u8 = 0;
53pub const DATUM_SHIFT_IDENTITY: u8 = 1;
54
55// Projection method tags.
56pub const METHOD_WEB_MERCATOR: u8 = 1;
57pub const METHOD_TRANSVERSE_MERCATOR: u8 = 2;
58pub const METHOD_MERCATOR: u8 = 3;
59pub const METHOD_LCC: u8 = 4;
60pub const METHOD_ALBERS: u8 = 5;
61pub const METHOD_POLAR_STEREO: u8 = 6;
62pub const METHOD_EQUIDISTANT_CYL: u8 = 7;
63pub const METHOD_LAEA: u8 = 8;
64pub const METHOD_OBLIQUE_STEREO: u8 = 9;
65pub const METHOD_HOTINE_OBLIQUE_MERCATOR_A: u8 = 10;
66pub const METHOD_HOTINE_OBLIQUE_MERCATOR_B: u8 = 11;
67pub const METHOD_CASSINI_SOLDNER: u8 = 12;
68pub const METHOD_LAEA_SPHERICAL: u8 = 13;
69pub const METHOD_COLOMBIA_URBAN: u8 = 14;
70pub const METHOD_LCC_MICHIGAN: u8 = 15;
71pub const METHOD_LCC_1SP_VARIANT_B: u8 = 16;
72pub const METHOD_KROVAK_NORTH_ORIENTATED: u8 = 17;
73pub const METHOD_KROVAK_MODIFIED_NORTH_ORIENTATED: u8 = 18;
74pub const METHOD_EQUAL_EARTH: u8 = 19;
75pub const METHOD_AMERICAN_POLYCONIC: u8 = 20;
76pub const METHOD_AZIMUTHAL_EQUIDISTANT: u8 = 21;
77pub const METHOD_GUAM: u8 = 22;
78pub const METHOD_POLAR_STEREO_VARIANT_C: u8 = 23;
79pub const METHOD_LABORDE: u8 = 24;
80
81// Coordinate operation step tags.
82pub const OP_IDENTITY: u8 = 0;
83pub const OP_HELMERT: u8 = 1;
84pub const OP_GRID_SHIFT: u8 = 2;
85pub const OP_CONCATENATED: u8 = 3;
86/// General geocentric affine map: three translations followed by a row-major
87/// scaled 3×3 matrix. Used for EPSG full-matrix Helmert methods.
88pub const OP_GEOCENTRIC_AFFINE: u8 = 4;
89
90// Operation flag bits.
91pub const FLAG_DEPRECATED: u8 = 1 << 0;
92pub const FLAG_PREFERRED: u8 = 1 << 1;
93pub const FLAG_APPROXIMATE: u8 = 1 << 2;
94/// EPSG records a same-CRS-pair replacement for this operation
95/// (`supersession` table); ranking prefers the replacement.
96pub const FLAG_SUPERSEDED: u8 = 1 << 3;
97
98// Grid resource tags.
99pub const GRID_FORMAT_NTV2: u8 = 1;
100pub const GRID_FORMAT_GTX: u8 = 2;
101pub const GRID_FORMAT_GEOTIFF: u8 = 3;
102pub const GRID_INTERPOLATION_BILINEAR: u8 = 1;
103pub const VERTICAL_OFFSET_GEOID_HEIGHT_METERS: u8 = 1;
104
105// Compound CRS component tags.
106pub const HORIZONTAL_CRS_GEOGRAPHIC: u8 = 1;
107pub const HORIZONTAL_CRS_PROJECTED: u8 = 2;
108pub const VERTICAL_COMPONENT_ELLIPSOIDAL: u8 = 1;
109pub const VERTICAL_COMPONENT_REGISTRY_CRS: u8 = 2;
110
111/// Little-endian read primitives for the trusted, CI-reproducibility-gated
112/// embedded blob. Offsets are validated by construction (record walking), so
113/// these index directly and panic on a malformed blob rather than returning
114/// errors — a corrupt embedded registry is a build defect, not user input.
115pub mod read {
116    pub fn u16(data: &[u8], offset: usize) -> u16 {
117        u16::from_le_bytes([data[offset], data[offset + 1]])
118    }
119
120    pub fn u32(data: &[u8], offset: usize) -> u32 {
121        u32::from_le_bytes([
122            data[offset],
123            data[offset + 1],
124            data[offset + 2],
125            data[offset + 3],
126        ])
127    }
128
129    pub fn f64(data: &[u8], offset: usize) -> f64 {
130        f64::from_le_bytes([
131            data[offset],
132            data[offset + 1],
133            data[offset + 2],
134            data[offset + 3],
135            data[offset + 4],
136            data[offset + 5],
137            data[offset + 6],
138            data[offset + 7],
139        ])
140    }
141}
142
143/// Little-endian write primitives. Float canonicalization (NaN bit patterns,
144/// decimal normalization) is generator policy and lives with the generator.
145pub mod write {
146    /// Returned when a string cannot be represented by the registry's `u16`
147    /// byte-length prefix.
148    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
149    pub struct StringTooLongError {
150        len: usize,
151    }
152
153    impl StringTooLongError {
154        pub fn byte_len(self) -> usize {
155            self.len
156        }
157    }
158
159    impl std::fmt::Display for StringTooLongError {
160        fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
161            write!(
162                formatter,
163                "string is {} bytes, exceeding the registry limit of {}",
164                self.len,
165                u16::MAX
166            )
167        }
168    }
169
170    impl std::error::Error for StringTooLongError {}
171
172    pub fn u16(buf: &mut Vec<u8>, value: u16) {
173        buf.extend_from_slice(&value.to_le_bytes());
174    }
175
176    pub fn u32(buf: &mut Vec<u8>, value: u32) {
177        buf.extend_from_slice(&value.to_le_bytes());
178    }
179
180    /// `u16` length-prefixed UTF-8 string.
181    pub fn string_u16(buf: &mut Vec<u8>, value: &str) -> Result<(), StringTooLongError> {
182        let bytes = value.as_bytes();
183        let len =
184            u16::try_from(bytes.len()).map_err(|_| StringTooLongError { len: bytes.len() })?;
185        u16(buf, len);
186        buf.extend_from_slice(bytes);
187        Ok(())
188    }
189}
190
191#[cfg(test)]
192mod tests {
193    #[test]
194    fn read_write_roundtrip() {
195        let mut buf = Vec::new();
196        super::write::u16(&mut buf, 0xBEEF);
197        super::write::u32(&mut buf, 0xDEAD_BEEF);
198        super::write::string_u16(&mut buf, "EPSG").unwrap();
199
200        assert_eq!(super::read::u16(&buf, 0), 0xBEEF);
201        assert_eq!(super::read::u32(&buf, 2), 0xDEAD_BEEF);
202        assert_eq!(super::read::u16(&buf, 6), 4);
203        assert_eq!(&buf[8..12], b"EPSG");
204    }
205
206    #[test]
207    fn oversized_string_write_is_atomic() {
208        let mut buf = vec![1, 2, 3];
209        let oversized = "x".repeat(usize::from(u16::MAX) + 1);
210
211        let error = super::write::string_u16(&mut buf, &oversized).unwrap_err();
212
213        assert_eq!(error.byte_len(), oversized.len());
214        assert_eq!(buf, [1, 2, 3]);
215    }
216}