opencellid 0.2.0

Rust client library for the OpenCellID API — sync and async clients with tracing, structured errors, and bounded I/O.
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
//! Domain types: cells, bounding boxes, radio technologies, measurements.

use serde::{Deserialize, Deserializer, Serialize};

use crate::error::{Error, Result};

/// Mobile Country Code (100..=999).
///
/// A `pub type` alias rather than a newtype to keep call-site ergonomics simple.
/// Range checks are not enforced at the type level; out-of-range values are
/// rejected by the OpenCellID server.
pub type Mcc = u16;
/// Mobile Network Code (0..=999 for GSM/UMTS/LTE/NR/NB-IoT, 0..=32767 for CDMA).
pub type Mnc = u16;
/// Location / Tracking Area Code.
pub type Lac = u32;
/// Cell identifier. Width depends on technology (up to 36 bits for NR).
pub type CellId = u64;

/// Radio access technology of a cell.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
#[non_exhaustive]
pub enum Radio {
    /// 2G GSM.
    Gsm,
    /// 3G UMTS / WCDMA.
    Umts,
    /// 4G LTE.
    Lte,
    /// Narrowband IoT.
    #[serde(rename = "NBIOT")]
    NbIot,
    /// 5G New Radio.
    Nr,
    /// CDMA family.
    Cdma,
}

impl Radio {
    /// String value accepted by the OpenCellID API.
    pub fn as_api_str(self) -> &'static str {
        match self {
            Self::Gsm => "GSM",
            Self::Umts => "UMTS",
            Self::Lte => "LTE",
            Self::NbIot => "NBIOT",
            Self::Nr => "NR",
            Self::Cdma => "CDMA",
        }
    }
}

/// Identifies a single cell tower.
///
/// Bundling the four-tuple into a struct prevents accidental swaps of `mcc` and `mnc`
/// at call sites (a common mistake when both are bare integers).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct CellKey {
    /// Mobile country code.
    pub mcc: Mcc,
    /// Mobile network code.
    pub mnc: Mnc,
    /// Location / tracking area code.
    pub lac: Lac,
    /// Cell identifier.
    pub cell_id: CellId,
    /// Optional radio technology to disambiguate cells that share identifiers.
    pub radio: Option<Radio>,
}

impl CellKey {
    /// Construct a key without a radio hint.
    ///
    /// # Examples
    ///
    /// ```
    /// use opencellid::{CellKey, Radio};
    /// let key = CellKey::new(250, 1, 7800, 12345).with_radio(Radio::Lte);
    /// assert_eq!(key.mcc, 250);
    /// ```
    pub fn new(mcc: Mcc, mnc: Mnc, lac: Lac, cell_id: CellId) -> Self {
        Self { mcc, mnc, lac, cell_id, radio: None }
    }

    /// Add a radio technology hint.
    pub fn with_radio(mut self, radio: Radio) -> Self {
        self.radio = Some(radio);
        self
    }
}

/// Geographic bounding box. Latitudes in `[-90, 90]`, longitudes in `[-180, 180]`.
///
/// Construct via [`Bbox::new`], which enforces the invariant
/// `lat_min < lat_max && lon_min < lon_max`. Fields are accessor-only because the
/// invariant must hold for any value of this type.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Bbox {
    lat_min: f64,
    lon_min: f64,
    lat_max: f64,
    lon_max: f64,
}

impl Bbox {
    /// Construct and validate a bounding box.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidInput`] if any coordinate is out of range or if the
    /// minimum coordinates are not strictly less than the maxima.
    ///
    /// # Examples
    ///
    /// ```
    /// use opencellid::Bbox;
    /// let bbox = Bbox::new(55.0, 37.0, 56.0, 38.0)?;
    /// assert_eq!(bbox.lat_min(), 55.0);
    /// # Ok::<(), opencellid::Error>(())
    /// ```
    pub fn new(lat_min: f64, lon_min: f64, lat_max: f64, lon_max: f64) -> Result<Self> {
        if !lat_min.is_finite() || !lat_max.is_finite() || !lon_min.is_finite() || !lon_max.is_finite() {
            return Err(Error::InvalidInput("bbox coordinates must be finite".into()));
        }
        if !(-90.0..=90.0).contains(&lat_min) || !(-90.0..=90.0).contains(&lat_max) {
            return Err(Error::InvalidInput("latitude out of range".into()));
        }
        if !(-180.0..=180.0).contains(&lon_min) || !(-180.0..=180.0).contains(&lon_max) {
            return Err(Error::InvalidInput("longitude out of range".into()));
        }
        if lat_min >= lat_max || lon_min >= lon_max {
            return Err(Error::InvalidInput(
                "min coordinates must be strictly less than max".into(),
            ));
        }
        Ok(Self { lat_min, lon_min, lat_max, lon_max })
    }

    /// Minimum latitude (south).
    pub fn lat_min(&self) -> f64 { self.lat_min }
    /// Minimum longitude (west).
    pub fn lon_min(&self) -> f64 { self.lon_min }
    /// Maximum latitude (north).
    pub fn lat_max(&self) -> f64 { self.lat_max }
    /// Maximum longitude (east).
    pub fn lon_max(&self) -> f64 { self.lon_max }

    /// Format as `latmin,lonmin,latmax,lonmax` (the wire format expected by `BBOX=`).
    pub fn to_query_value(self) -> String {
        format!(
            "{},{},{},{}",
            format_coordinate(self.lat_min),
            format_coordinate(self.lon_min),
            format_coordinate(self.lat_max),
            format_coordinate(self.lon_max),
        )
    }
}

/// Format a finite floating-point coordinate without scientific notation so that the
/// OpenCellID server accepts it. Trims trailing zeros from a fixed-precision rendering.
pub(crate) fn format_coordinate(v: f64) -> String {
    let mut s = format!("{v:.7}");
    if s.contains('.') {
        // Strip trailing zeros, then a trailing dot if any.
        while s.ends_with('0') {
            s.pop();
        }
        if s.ends_with('.') {
            s.pop();
        }
    }
    s
}

/// Deserialise OpenCellID's integer-encoded boolean (`0`/`1`) into a Rust `bool`.
fn deserialize_bool_from_int<'de, D>(d: D) -> std::result::Result<bool, D::Error>
where
    D: Deserializer<'de>,
{
    use serde::de::Error as _;
    let v = serde_json::Value::deserialize(d)?;
    match v {
        serde_json::Value::Bool(b) => Ok(b),
        serde_json::Value::Number(n) => match n.as_u64() {
            Some(0) => Ok(false),
            Some(1) => Ok(true),
            _ => Err(D::Error::custom("expected 0 or 1 for boolean field")),
        },
        serde_json::Value::String(s) => match s.as_str() {
            "0" => Ok(false),
            "1" => Ok(true),
            other => Err(D::Error::custom(format!("expected 0/1, got {other:?}"))),
        },
        other => Err(D::Error::custom(format!("expected boolean, got {other}"))),
    }
}

/// A cell tower record returned by `cell/get` and `cell/getInArea`.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[non_exhaustive]
pub struct Cell {
    /// Latitude of the cell position.
    pub lat: f64,
    /// Longitude of the cell position.
    pub lon: f64,
    /// Mobile country code.
    pub mcc: Mcc,
    /// Mobile network code.
    pub mnc: Mnc,
    /// Location / tracking area code.
    pub lac: Lac,
    /// Cell identifier.
    #[serde(rename = "cellid", alias = "cellId")]
    pub cell_id: CellId,
    /// Estimated coverage range in meters.
    #[serde(default)]
    pub range: u32,
    /// Number of measurements aggregated for this position.
    #[serde(default)]
    pub samples: u32,
    /// `true` if the position is community-derived (may shift with new measurements);
    /// `false` if it is operator-precise.
    #[serde(default, deserialize_with = "deserialize_bool_from_int")]
    pub changeable: bool,
    /// Average signal strength in dBm (negative for received signal strength).
    #[serde(rename = "averageSignalStrength", default)]
    pub avg_signal: i32,
    /// Radio access technology, when available.
    #[serde(default)]
    pub radio: Option<Radio>,
}

/// Result of `cell/getInAreaSize` — number of cells matching a query.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[non_exhaustive]
pub struct CellCount {
    /// Number of cells in the requested area.
    pub count: u64,
}

/// A single cell measurement payload for `measure/add` / `measure/uploadJson`.
///
/// Construct via [`Measurement::new`] and chain optional fields through the
/// `with_*` setters.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[non_exhaustive]
pub struct Measurement {
    /// Latitude where the cell was observed.
    pub lat: f64,
    /// Longitude where the cell was observed.
    pub lon: f64,
    /// Mobile country code.
    pub mcc: Mcc,
    /// Mobile network code.
    pub mnc: Mnc,
    /// Location area code.
    pub lac: Lac,
    /// Cell identifier.
    #[serde(rename = "cellid")]
    pub cell_id: CellId,
    /// Radio technology — sent on the wire as `act`.
    #[serde(rename = "act", serialize_with = "serialize_radio_as_str")]
    pub radio: Radio,
    /// Signal strength in dBm.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub signal: Option<i32>,
    /// Measurement timestamp (`yyyy-MM-dd HH:mm:ss` or epoch milliseconds as string).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub measured_at: Option<String>,
    /// GPS accuracy rating (0..=35000 meters).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rating: Option<u32>,
    /// Speed at measurement time (m/s).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub speed: Option<f32>,
    /// Heading at measurement time (degrees).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub direction: Option<f32>,
    /// Timing advance (GSM/LTE).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ta: Option<u32>,
    /// Primary scrambling code (UMTS).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub psc: Option<u16>,
    /// Tracking area code (LTE / NR).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tac: Option<u32>,
    /// Physical cell identifier (LTE).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pci: Option<u16>,
}

fn serialize_radio_as_str<S>(r: &Radio, s: S) -> std::result::Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    s.serialize_str(r.as_api_str())
}

impl Measurement {
    /// Build a measurement with the required fields.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidInput`] if `lat` or `lon` is non-finite.
    pub fn new(
        lat: f64,
        lon: f64,
        mcc: Mcc,
        mnc: Mnc,
        lac: Lac,
        cell_id: CellId,
        radio: Radio,
    ) -> Result<Self> {
        if !lat.is_finite() || !lon.is_finite() {
            return Err(Error::InvalidInput("lat/lon must be finite".into()));
        }
        Ok(Self {
            lat, lon, mcc, mnc, lac, cell_id, radio,
            signal: None, measured_at: None, rating: None, speed: None,
            direction: None, ta: None, psc: None, tac: None, pci: None,
        })
    }

    /// Attach a signal-strength measurement (dBm).
    pub fn with_signal(mut self, signal: i32) -> Self {
        self.signal = Some(signal);
        self
    }

    /// Attach a measurement timestamp.
    pub fn with_measured_at(mut self, ts: impl Into<String>) -> Self {
        self.measured_at = Some(ts.into());
        self
    }

    /// Attach a GPS rating in meters.
    pub fn with_rating(mut self, rating: u32) -> Self {
        self.rating = Some(rating);
        self
    }

    /// Attach speed (m/s). Non-finite values are rejected at submission time
    /// via [`Self::validate`] rather than here, keeping the builder chain
    /// infallible.
    pub fn with_speed(mut self, speed: f32) -> Self {
        self.speed = Some(speed);
        self
    }

    /// Attach heading in degrees. See [`Self::with_speed`] for finiteness
    /// handling.
    pub fn with_direction(mut self, direction: f32) -> Self {
        self.direction = Some(direction);
        self
    }

    /// Validate that all numeric fields are finite. Called by the client
    /// before serialising the request; downstream code may also call it
    /// explicitly.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidInput`] if any optional float field is
    /// non-finite. (Required `lat`/`lon` are checked in [`Self::new`].)
    pub fn validate(&self) -> Result<()> {
        for (name, v) in [("speed", self.speed), ("direction", self.direction)] {
            if let Some(v) = v {
                if !v.is_finite() {
                    return Err(Error::InvalidInput(format!("{name} must be finite")));
                }
            }
        }
        Ok(())
    }

    /// Attach a Timing Advance value (GSM/LTE).
    pub fn with_ta(mut self, ta: u32) -> Self {
        self.ta = Some(ta);
        self
    }

    /// Attach a Primary Scrambling Code (UMTS).
    pub fn with_psc(mut self, psc: u16) -> Self {
        self.psc = Some(psc);
        self
    }

    /// Attach a Tracking Area Code (LTE / NR).
    pub fn with_tac(mut self, tac: u32) -> Self {
        self.tac = Some(tac);
        self
    }

    /// Attach a Physical Cell ID (LTE).
    pub fn with_pci(mut self, pci: u16) -> Self {
        self.pci = Some(pci);
        self
    }
}

/// Wrapper for `measure/uploadJson` payloads.
///
/// The `measurements` field is intentionally public so that callers can build
/// the batch with normal `Vec` ergonomics (`push`, `extend`, etc.). The total
/// serialised size is bounded by the upload endpoint at ~2 MiB; very large
/// batches are rejected when [`crate::Client::upload_json`] is called.
#[derive(Debug, Clone, Default, Serialize)]
#[non_exhaustive]
pub struct MeasurementsPayload {
    /// Array of measurements.
    pub measurements: Vec<Measurement>,
}

impl MeasurementsPayload {
    /// Create an empty payload.
    pub fn new() -> Self {
        Self::default()
    }
}

/// What to download from the OpenCellID `/ocid/downloads` endpoint.
///
/// OpenCellID enforces a hard limit of **two downloads per file per token per
/// day**. Plan accordingly.
///
/// # Examples
///
/// ```
/// use opencellid::DumpKind;
/// let kg = DumpKind::Country(437);
/// let world = DumpKind::World;
/// let diff = DumpKind::Daily { date_utc: "2026-05-10".into() };
/// assert!(matches!(world, DumpKind::World));
/// # let _ = (kg, diff);
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DumpKind {
    /// World-wide export (`type=full`, `file=cell_towers.csv.gz`). Hundreds of
    /// MB. Contains cells observed in the past 18 months.
    World,
    /// Country export (`type=mcc`, `file=<MCC>.csv.gz`). E.g. `Country(437)`
    /// for Kyrgyzstan.
    Country(Mcc),
    /// Daily differential (`type=diff`,
    /// `file=OCID-diff-cell-export-<date_utc>-T000000.csv.gz`). `date_utc` is
    /// `YYYY-MM-DD` in UTC.
    Daily {
        /// Date string in `YYYY-MM-DD` UTC.
        date_utc: String,
    },
}

impl DumpKind {
    /// Construct a `DumpKind::Daily` after validating the date shape.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidInput`] if `date_utc` is not in `YYYY-MM-DD` form.
    /// Calendar correctness (e.g. `2026-02-30`) is **not** verified here.
    pub fn daily(date_utc: impl Into<String>) -> Result<Self> {
        let date_utc = date_utc.into();
        if !is_iso_date(&date_utc) {
            return Err(Error::InvalidInput(format!(
                "expected YYYY-MM-DD UTC date, got {date_utc:?}"
            )));
        }
        Ok(Self::Daily { date_utc })
    }

    /// Wire-format `(type, file)` query-parameter pair for `/ocid/downloads`.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidInput`] when [`DumpKind::Country`] holds an MCC outside
    ///   the ITU-allocated range `200..=999`.
    /// - [`Error::InvalidInput`] when [`DumpKind::Daily`] holds a malformed
    ///   `date_utc` (only relevant if the variant was constructed without
    ///   [`Self::daily`] — `#[non_exhaustive]` makes that hard from outside
    ///   the crate, but callers inside the crate or in tests can still produce
    ///   one).
    pub fn type_and_file(&self) -> Result<(&'static str, String)> {
        match self {
            Self::World => Ok(("full", "cell_towers.csv.gz".to_string())),
            Self::Country(mcc) => {
                if !(200..=999).contains(mcc) {
                    return Err(Error::InvalidInput(format!(
                        "MCC {mcc} is outside the ITU range 200..=999"
                    )));
                }
                Ok(("mcc", format!("{mcc}.csv.gz")))
            }
            Self::Daily { date_utc } => {
                if !is_iso_date(date_utc) {
                    return Err(Error::InvalidInput(format!(
                        "expected YYYY-MM-DD UTC date, got {date_utc:?}"
                    )));
                }
                Ok((
                    "diff",
                    format!("OCID-diff-cell-export-{date_utc}-T000000.csv.gz"),
                ))
            }
        }
    }
}

/// `YYYY-MM-DD` shape check — does not validate calendar correctness, only
/// the ASCII shape OpenCellID expects.
pub(crate) fn is_iso_date(s: &str) -> bool {
    let bytes = s.as_bytes();
    bytes.len() == 10
        && bytes
            .iter()
            .enumerate()
            .all(|(i, b)| if i == 4 || i == 7 { *b == b'-' } else { b.is_ascii_digit() })
}

/// One row of a downloaded CSV dump.
///
/// **Note:** the dump CSV uses different column names from the API JSON.
/// `mnc`/`lac`/`cell_id` here are wired to the dump's `net`/`area`/`cell`
/// columns through serde renaming, so the Rust field names stay consistent
/// with [`Cell`] / [`Measurement`] across the crate.
#[cfg(feature = "csv")]
#[cfg_attr(docsrs, doc(cfg(feature = "csv")))]
#[derive(Debug, Clone, PartialEq, serde::Deserialize)]
#[non_exhaustive]
pub struct DumpRow {
    /// Radio access technology.
    pub radio: Radio,
    /// Mobile country code.
    pub mcc: Mcc,
    /// Mobile network code (`net` column on the wire).
    #[serde(rename = "net")]
    pub mnc: Mnc,
    /// Location / tracking area code (`area` column on the wire).
    #[serde(rename = "area")]
    pub lac: Lac,
    /// Cell identifier (`cell` column on the wire).
    #[serde(rename = "cell")]
    pub cell_id: CellId,
    /// PSC (UMTS, 0..=511) / PCI (LTE, 0..=503), if present.
    #[serde(default, deserialize_with = "deserialize_optional_u16")]
    pub unit: Option<u16>,
    /// Longitude.
    pub lon: f64,
    /// Latitude.
    pub lat: f64,
    /// Estimated coverage radius in meters.
    pub range: u32,
    /// Number of measurements aggregated into this row.
    pub samples: u32,
    /// `true` if the position is community-derived; `false` if operator-precise.
    #[serde(deserialize_with = "deserialize_bool_from_int")]
    pub changeable: bool,
    /// Unix timestamp the row was first created on the server.
    pub created: u64,
    /// Unix timestamp of the latest update.
    pub updated: u64,
    /// Average signal strength.
    #[serde(rename = "averageSignal", default)]
    pub average_signal: i32,
}

#[cfg(feature = "csv")]
fn deserialize_optional_u16<'de, D>(d: D) -> std::result::Result<Option<u16>, D::Error>
where
    D: Deserializer<'de>,
{
    use serde::de::Error as _;
    let v = Option::<serde_json::Value>::deserialize(d)?;
    match v {
        None | Some(serde_json::Value::Null) => Ok(None),
        Some(serde_json::Value::String(ref s)) if s.is_empty() => Ok(None),
        Some(serde_json::Value::String(s)) => s
            .parse::<u16>()
            .map(Some)
            .map_err(|e| D::Error::custom(format!("expected u16, got {s:?}: {e}"))),
        Some(serde_json::Value::Number(n)) => n
            .as_u64()
            .and_then(|x| u16::try_from(x).ok())
            .map(Some)
            .ok_or_else(|| D::Error::custom("integer out of u16 range")),
        Some(other) => Err(D::Error::custom(format!("expected u16, got {other}"))),
    }
}

/// Metadata for one daily-differential file advertised on `/downloads.php`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct DumpListing {
    /// Server-assigned filename, e.g.
    /// `OCID-diff-cell-export-2026-05-10-T000000.csv.gz`.
    pub filename: String,
    /// Date portion of the filename in `YYYY-MM-DD` (UTC).
    pub date_utc: String,
}

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

    #[test]
    fn bbox_validates_ranges() {
        assert!(Bbox::new(0.0, 0.0, 1.0, 1.0).is_ok());
        assert!(Bbox::new(-91.0, 0.0, 0.0, 1.0).is_err());
        assert!(Bbox::new(1.0, 0.0, 0.0, 1.0).is_err());
        assert!(Bbox::new(f64::NAN, 0.0, 1.0, 1.0).is_err());
    }

    #[test]
    fn bbox_query_format() {
        let b = Bbox::new(10.0, 20.0, 11.0, 21.0).unwrap();
        assert_eq!(b.to_query_value(), "10,20,11,21");
    }

    #[test]
    fn radio_serializes_uppercase() {
        assert_eq!(serde_json::to_string(&Radio::NbIot).unwrap(), "\"NBIOT\"");
        assert_eq!(serde_json::to_string(&Radio::Lte).unwrap(), "\"LTE\"");
    }

    #[test]
    fn cell_changeable_accepts_int_and_bool() {
        let body = r#"{"lat":1.0,"lon":2.0,"mcc":1,"mnc":1,"lac":1,"cellid":1,"changeable":1}"#;
        let c: Cell = serde_json::from_str(body).unwrap();
        assert!(c.changeable);

        let body = r#"{"lat":1.0,"lon":2.0,"mcc":1,"mnc":1,"lac":1,"cellid":1,"changeable":false}"#;
        let c: Cell = serde_json::from_str(body).unwrap();
        assert!(!c.changeable);
    }

    #[test]
    fn cell_id_alias() {
        for body in [
            r#"{"lat":1.0,"lon":2.0,"mcc":1,"mnc":1,"lac":1,"cellid":42}"#,
            r#"{"lat":1.0,"lon":2.0,"mcc":1,"mnc":1,"lac":1,"cellId":42}"#,
        ] {
            let c: Cell = serde_json::from_str(body).unwrap();
            assert_eq!(c.cell_id, 42);
        }
    }

    #[test]
    fn measurement_serializes_act_and_cellid() {
        let m = Measurement::new(1.0, 2.0, 250, 1, 7, 42, Radio::Lte).unwrap();
        let json = serde_json::to_value(&m).unwrap();
        assert_eq!(json["cellid"], 42);
        assert_eq!(json["act"], "LTE");
        assert!(json.get("signal").is_none(), "None fields must be skipped");
    }

    #[test]
    fn measurement_rejects_non_finite_position() {
        assert!(Measurement::new(f64::NAN, 0.0, 1, 1, 1, 1, Radio::Lte).is_err());
        assert!(Measurement::new(0.0, f64::INFINITY, 1, 1, 1, 1, Radio::Lte).is_err());
    }

    #[test]
    fn measurement_with_setters_compose() {
        let m = Measurement::new(1.0, 2.0, 250, 1, 7, 42, Radio::Lte)
            .unwrap()
            .with_signal(-95)
            .with_rating(50)
            .with_ta(3)
            .with_speed(12.5);
        assert_eq!(m.signal, Some(-95));
        assert_eq!(m.rating, Some(50));
        assert_eq!(m.ta, Some(3));
        assert_eq!(m.speed, Some(12.5));
    }

    #[test]
    fn measurement_validate_catches_non_finite_optional_fields() {
        let m = Measurement::new(1.0, 2.0, 250, 1, 7, 42, Radio::Lte)
            .unwrap()
            .with_speed(f32::NAN);
        assert!(m.validate().is_err());

        let m = Measurement::new(1.0, 2.0, 250, 1, 7, 42, Radio::Lte)
            .unwrap()
            .with_direction(f32::INFINITY);
        assert!(m.validate().is_err());

        let m = Measurement::new(1.0, 2.0, 250, 1, 7, 42, Radio::Lte)
            .unwrap()
            .with_speed(12.5)
            .with_direction(180.0);
        assert!(m.validate().is_ok());
    }

    #[test]
    fn format_coordinate_avoids_scientific() {
        assert_eq!(format_coordinate(1e-7), "0.0000001");
        assert_eq!(format_coordinate(1.0), "1");
        assert_eq!(format_coordinate(55.7558), "55.7558");
        assert_eq!(format_coordinate(-180.0), "-180");
    }

    #[test]
    fn dump_kind_type_and_file() {
        assert_eq!(
            DumpKind::World.type_and_file().unwrap(),
            ("full", "cell_towers.csv.gz".to_string())
        );
        assert_eq!(
            DumpKind::Country(437).type_and_file().unwrap(),
            ("mcc", "437.csv.gz".to_string())
        );
        assert_eq!(
            DumpKind::Daily { date_utc: "2026-05-10".into() }.type_and_file().unwrap(),
            ("diff", "OCID-diff-cell-export-2026-05-10-T000000.csv.gz".to_string())
        );
    }

    #[test]
    fn dump_kind_rejects_bad_date() {
        for bad in ["2026/05/10", "2026-5-10", "garbage", "10-05-2026", "2026-05-10x"] {
            let r = DumpKind::Daily { date_utc: bad.into() }.type_and_file();
            assert!(r.is_err(), "expected error for {bad:?}");
        }
    }

    #[cfg(feature = "csv")]
    #[test]
    fn dump_row_deserializes_csv_record() {
        let csv = "radio,mcc,net,area,cell,unit,lon,lat,range,samples,changeable,created,updated,averageSignal\n\
                   LTE,250,1,7,42,127,37.6,55.7,1000,12,1,1700000000,1700001000,-95\n";
        let mut rdr = csv::ReaderBuilder::new()
            .has_headers(true)
            .from_reader(csv.as_bytes());
        let row: DumpRow = rdr.deserialize().next().unwrap().unwrap();
        assert_eq!(row.radio, Radio::Lte);
        assert_eq!(row.mcc, 250);
        assert_eq!(row.mnc, 1);
        assert_eq!(row.lac, 7);
        assert_eq!(row.cell_id, 42);
        assert_eq!(row.unit, Some(127));
        assert!(row.changeable);
        assert_eq!(row.average_signal, -95);
        assert_eq!(row.created, 1_700_000_000);
        assert_eq!(row.updated, 1_700_001_000);
    }

    #[cfg(feature = "csv")]
    #[test]
    fn dump_row_handles_empty_unit() {
        let csv = "radio,mcc,net,area,cell,unit,lon,lat,range,samples,changeable,created,updated,averageSignal\n\
                   GSM,262,2,801,86355,,13.2,52.5,902,1,1,1700000000,1700001000,0\n";
        let mut rdr = csv::ReaderBuilder::new()
            .has_headers(true)
            .from_reader(csv.as_bytes());
        let row: DumpRow = rdr.deserialize().next().unwrap().unwrap();
        assert_eq!(row.unit, None);
    }

    #[test]
    fn dump_kind_country_rejects_out_of_range_mcc() {
        assert!(DumpKind::Country(0).type_and_file().is_err());
        assert!(DumpKind::Country(199).type_and_file().is_err());
        assert!(DumpKind::Country(200).type_and_file().is_ok());
        assert!(DumpKind::Country(999).type_and_file().is_ok());
    }

    #[test]
    fn dump_kind_daily_constructor_validates() {
        assert!(DumpKind::daily("2026-05-10").is_ok());
        assert!(DumpKind::daily("not-a-date").is_err());
        assert!(DumpKind::daily("2026/05/10").is_err());
    }

    proptest! {
        #[test]
        fn bbox_invariant_holds_when_constructor_succeeds(
            lat_min in -90.0f64..90.0,
            lat_max in -90.0f64..90.0,
            lon_min in -180.0f64..180.0,
            lon_max in -180.0f64..180.0,
        ) {
            if let Ok(b) = Bbox::new(lat_min, lon_min, lat_max, lon_max) {
                prop_assert!(b.lat_min() < b.lat_max());
                prop_assert!(b.lon_min() < b.lon_max());
                prop_assert!((-90.0..=90.0).contains(&b.lat_min()));
                prop_assert!((-90.0..=90.0).contains(&b.lat_max()));
                prop_assert!((-180.0..=180.0).contains(&b.lon_min()));
                prop_assert!((-180.0..=180.0).contains(&b.lon_max()));
            }
        }

        #[test]
        fn bbox_rejects_inverted(
            lat in -90.0f64..90.0,
            lon in -180.0f64..180.0,
        ) {
            prop_assert!(Bbox::new(lat, lon, lat, lon).is_err());
            prop_assert!(Bbox::new(lat + 1.0, lon, lat, lon + 1.0).is_err());
        }
    }
}