1use std::fmt;
2
3use serde::de::Deserializer;
4use serde::ser::Serializer;
5use serde::{Deserialize, Serialize};
6use thiserror::Error;
7
8pub const MAX_COLUMNS: u32 = 16_384;
10pub const MAX_ROWS: u32 = 1_048_576;
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
15pub enum CellRefError {
16 #[error("cell reference is empty")]
18 Empty,
19 #[error("cell reference must contain ASCII characters only")]
21 NonAscii,
22 #[error("cell reference has invalid A1 syntax")]
24 InvalidSyntax,
25 #[error("cell reference column is outside 1..=16384")]
27 ColumnOutOfRange,
28 #[error("cell reference row is outside 1..=1048576")]
30 RowOutOfRange,
31 #[error("worksheet cell reference is not canonical")]
33 NonCanonical,
34}
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub struct ParsedCellRef {
39 column: u32,
40 row: u32,
41 absolute_column: bool,
42 absolute_row: bool,
43 canonical: bool,
44}
45
46impl ParsedCellRef {
47 pub const fn column(self) -> u32 {
49 self.column
50 }
51
52 pub const fn row(self) -> u32 {
54 self.row
55 }
56
57 pub const fn absolute_column(self) -> bool {
59 self.absolute_column
60 }
61
62 pub const fn absolute_row(self) -> bool {
64 self.absolute_row
65 }
66
67 pub const fn is_canonical(self) -> bool {
69 self.canonical
70 }
71}
72
73pub fn parse_a1_reference(input: &str) -> Result<ParsedCellRef, CellRefError> {
79 if input.is_empty() {
80 return Err(CellRefError::Empty);
81 }
82 if !input.is_ascii() {
83 return Err(CellRefError::NonAscii);
84 }
85
86 let bytes = input.as_bytes();
87 let mut index = 0usize;
88 let absolute_column = bytes.get(index) == Some(&b'$');
89 if absolute_column {
90 index += 1;
91 }
92
93 let column_start = index;
94 let mut column = 0u32;
95 let mut uppercase_column = true;
96 while let Some(byte) = bytes.get(index).copied() {
97 if !byte.is_ascii_alphabetic() {
98 break;
99 }
100 uppercase_column &= byte.is_ascii_uppercase();
101 let digit = u32::from(byte.to_ascii_uppercase() - b'A') + 1;
102 column = column
103 .checked_mul(26)
104 .and_then(|value| value.checked_add(digit))
105 .ok_or(CellRefError::ColumnOutOfRange)?;
106 if column > MAX_COLUMNS {
107 return Err(CellRefError::ColumnOutOfRange);
108 }
109 index += 1;
110 }
111 if index == column_start {
112 return Err(CellRefError::InvalidSyntax);
113 }
114
115 let absolute_row = bytes.get(index) == Some(&b'$');
116 if absolute_row {
117 index += 1;
118 }
119
120 let row_start = index;
121 let mut row = 0u32;
122 while let Some(byte) = bytes.get(index).copied() {
123 if !byte.is_ascii_digit() {
124 break;
125 }
126 row = row
127 .checked_mul(10)
128 .and_then(|value| value.checked_add(u32::from(byte - b'0')))
129 .ok_or(CellRefError::RowOutOfRange)?;
130 if row > MAX_ROWS {
131 return Err(CellRefError::RowOutOfRange);
132 }
133 index += 1;
134 }
135 if index == row_start || index != bytes.len() {
136 return Err(CellRefError::InvalidSyntax);
137 }
138 if row == 0 {
139 return Err(CellRefError::RowOutOfRange);
140 }
141
142 let canonical =
143 !absolute_column && !absolute_row && uppercase_column && bytes[row_start] != b'0';
144 Ok(ParsedCellRef {
145 column,
146 row,
147 absolute_column,
148 absolute_row,
149 canonical,
150 })
151}
152
153#[derive(Clone, Copy, PartialEq, Eq)]
155pub struct CompactCellRef {
156 buf: [u8; 10],
157 len: u8,
158}
159
160impl CompactCellRef {
161 pub fn new(input: &str) -> Result<Self, CellRefError> {
163 let parsed = parse_a1_reference(input)?;
164 if !parsed.is_canonical() {
165 return Err(CellRefError::NonCanonical);
166 }
167 let mut buf = [0u8; 10];
168 buf[..input.len()].copy_from_slice(input.as_bytes());
169 Ok(Self {
170 buf,
171 len: input.len() as u8,
172 })
173 }
174
175 pub fn as_str(&self) -> &str {
177 unsafe { std::str::from_utf8_unchecked(&self.buf[..usize::from(self.len)]) }
179 }
180
181 pub fn from_coordinates(column: u32, row: u32) -> Result<Self, CellRefError> {
183 if !(1..=MAX_COLUMNS).contains(&column) {
184 return Err(CellRefError::ColumnOutOfRange);
185 }
186 if !(1..=MAX_ROWS).contains(&row) {
187 return Err(CellRefError::RowOutOfRange);
188 }
189
190 let mut buf = [0u8; 10];
191 let mut position = 0usize;
192 let mut column_buf = [0u8; 3];
193 let mut column_len = 0usize;
194 let mut remaining_column = column;
195 while remaining_column > 0 {
196 remaining_column -= 1;
197 column_buf[column_len] = b'A' + (remaining_column % 26) as u8;
198 column_len += 1;
199 remaining_column /= 26;
200 }
201 for index in (0..column_len).rev() {
202 buf[position] = column_buf[index];
203 position += 1;
204 }
205
206 let mut row_buf = [0u8; 7];
207 let mut row_len = 0usize;
208 let mut remaining_row = row;
209 while remaining_row > 0 {
210 row_buf[row_len] = b'0' + (remaining_row % 10) as u8;
211 row_len += 1;
212 remaining_row /= 10;
213 }
214 for index in (0..row_len).rev() {
215 buf[position] = row_buf[index];
216 position += 1;
217 }
218
219 Ok(Self {
220 buf,
221 len: position as u8,
222 })
223 }
224}
225
226impl fmt::Display for CompactCellRef {
227 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
228 formatter.write_str(self.as_str())
229 }
230}
231
232impl fmt::Debug for CompactCellRef {
233 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
234 write!(formatter, "CompactCellRef(\"{}\")", self.as_str())
235 }
236}
237
238impl TryFrom<&str> for CompactCellRef {
239 type Error = CellRefError;
240
241 fn try_from(input: &str) -> Result<Self, Self::Error> {
242 Self::new(input)
243 }
244}
245
246impl TryFrom<String> for CompactCellRef {
247 type Error = CellRefError;
248
249 fn try_from(input: String) -> Result<Self, Self::Error> {
250 Self::new(&input)
251 }
252}
253
254impl AsRef<str> for CompactCellRef {
255 fn as_ref(&self) -> &str {
256 self.as_str()
257 }
258}
259
260impl PartialEq<&str> for CompactCellRef {
261 fn eq(&self, other: &&str) -> bool {
262 self.as_str() == *other
263 }
264}
265
266impl PartialEq<str> for CompactCellRef {
267 fn eq(&self, other: &str) -> bool {
268 self.as_str() == other
269 }
270}
271
272impl Serialize for CompactCellRef {
273 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
274 serializer.serialize_str(self.as_str())
275 }
276}
277
278impl<'de> Deserialize<'de> for CompactCellRef {
279 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
280 struct CompactCellRefVisitor;
281
282 impl serde::de::Visitor<'_> for CompactCellRefVisitor {
283 type Value = CompactCellRef;
284
285 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
286 formatter.write_str("a canonical A1 cell reference")
287 }
288
289 fn visit_str<E: serde::de::Error>(self, value: &str) -> Result<CompactCellRef, E> {
290 CompactCellRef::new(value).map_err(E::custom)
291 }
292
293 fn visit_string<E: serde::de::Error>(self, value: String) -> Result<CompactCellRef, E> {
294 self.visit_str(&value)
295 }
296 }
297
298 deserializer.deserialize_str(CompactCellRefVisitor)
299 }
300}
301
302#[cfg(test)]
303mod tests {
304 use super::*;
305
306 #[test]
307 fn parser_accepts_excel_boundaries_and_absolute_core_refs() {
308 let min = parse_a1_reference("A1").unwrap();
309 assert_eq!((min.column(), min.row()), (1, 1));
310
311 let max = parse_a1_reference("$XFD$1048576").unwrap();
312 assert_eq!((max.column(), max.row()), (16_384, 1_048_576));
313 }
314
315 #[test]
316 fn parser_rejects_bounds_zero_overflow_utf8_and_trailing_junk() {
317 for invalid in [
318 "",
319 "A0",
320 "XFE1",
321 "A1048577",
322 "A42949672960",
323 "A1junk",
324 "A1$",
325 "$$A1",
326 "한글A1",
327 ] {
328 assert!(parse_a1_reference(invalid).is_err(), "accepted {invalid:?}");
329 }
330 }
331
332 #[test]
333 fn compact_ref_rejects_aliases_and_arbitrary_invalid_strings_without_panic() {
334 for invalid in ["a1", "A01", "$A$1", "A1junk", "한글", "ABCDEFGHIJK"] {
335 assert!(
336 CompactCellRef::new(invalid).is_err(),
337 "accepted {invalid:?}"
338 );
339 }
340 assert_eq!(
341 CompactCellRef::new("XFD1048576").unwrap().as_str(),
342 "XFD1048576"
343 );
344 }
345
346 #[test]
347 fn parser_and_compact_ref_never_panic_for_varied_utf8() {
348 let alphabet = ['A', 'z', '$', '0', '9', '_', '/', '\0', 'é', '한', '💾'];
349 let mut state = 0x9e37_79b9u32;
350 for length in 0..=128 {
351 let mut input = String::new();
352 for _ in 0..length {
353 state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
354 input.push(alphabet[state as usize % alphabet.len()]);
355 }
356 let _ = parse_a1_reference(&input);
357 let _ = CompactCellRef::new(&input);
358 }
359
360 let oversized_digits = "0".repeat(16 * 1024);
361 assert!(parse_a1_reference(&oversized_digits).is_err());
362 assert!(CompactCellRef::new(&oversized_digits).is_err());
363 }
364
365 #[test]
366 fn compact_ref_coordinates_are_fallible_at_exact_boundaries() {
367 assert_eq!(
368 CompactCellRef::from_coordinates(16_384, 1_048_576)
369 .unwrap()
370 .as_str(),
371 "XFD1048576"
372 );
373 for (column, row) in [(0, 1), (1, 0), (16_385, 1), (1, 1_048_577)] {
374 assert!(CompactCellRef::from_coordinates(column, row).is_err());
375 }
376 }
377
378 #[test]
379 fn compact_ref_deserialization_rejects_noncanonical_aliases() {
380 for invalid in ["\"a1\"", "\"A01\"", "\"$A$1\"", "\"A1junk\""] {
381 assert!(quick_xml::de::from_str::<CompactCellRef>(invalid).is_err());
382 }
383 }
384}