herolib_otoml 0.3.13

OTOML - Canonical TOML serialization format with compact binary representation.
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
//! # olocation - Canonical Geographic Location Type
//!
//! A deterministic, compact geographic location primitive representing a point
//! on Earth with an explicit uncertainty radius.
//!
//! ## Format
//!
//! Text: `(lat,lon,radius)` where lat/lon are decimal degrees, radius is meters
//! Binary: `[i32, i32, u16]` (10 bytes total)
//!
//! ## Example
//!
//! ```rust
//! use herolib_otoml::OLocation;
//!
//! // Create from decimal degrees and radius in meters
//! let zurich = OLocation::new(47.376887, 8.541694, 1000).unwrap();
//!
//! // Display as canonical string
//! assert_eq!(zurich.to_string(), "(47.376887,8.541694,1000)");
//!
//! // Parse from string
//! let parsed: OLocation = "(47.376887,8.541694,1000)".parse().unwrap();
//!
//! // Calculate distance between two locations
//! let london = OLocation::new(51.507351, -0.127758, 500).unwrap();
//! let distance_km = zurich.distance(&london) / 1000.0;
//! println!("Zurich to London: {:.1} km", distance_km);
//! ```

use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
use std::str::FromStr;

use super::error::{OtomlError, Result};

/// Earth's mean radius in meters (WGS-84 approximation).
const EARTH_RADIUS_METERS: f64 = 6_371_000.0;

/// Micro-degrees per degree.
const MICRO_DEGREES: i32 = 1_000_000;

/// Maximum latitude in micro-degrees (90 degrees).
const MAX_LAT_MICRO: i32 = 90_000_000;

/// Maximum longitude in micro-degrees (180 degrees).
const MAX_LON_MICRO: i32 = 180_000_000;

/// Canonical geographic location with uncertainty radius.
///
/// Represents a point on Earth (WGS-84) with an explicit accuracy bound.
/// The true position lies within `radius` meters of the given lat/lon.
///
/// ## Internal Storage
/// - Latitude: `i32` micro-degrees (-90,000,000 to 90,000,000)
/// - Longitude: `i32` micro-degrees (-180,000,000 to 180,000,000)
/// - Radius: `u16` meters (0 to 65,535)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct OLocation {
    /// Latitude in micro-degrees (1e-6 degrees).
    lat_micro: i32,
    /// Longitude in micro-degrees (1e-6 degrees).
    lon_micro: i32,
    /// Uncertainty radius in meters.
    radius: u16,
}

impl OLocation {
    /// Create a new OLocation from decimal degrees and radius in meters.
    ///
    /// # Arguments
    /// * `lat` - Latitude in decimal degrees (-90.0 to 90.0)
    /// * `lon` - Longitude in decimal degrees (-180.0 to 180.0)
    /// * `radius` - Uncertainty radius in meters (0 to 65,535)
    ///
    /// # Example
    /// ```
    /// use herolib_otoml::OLocation;
    ///
    /// // Central Zurich with 1km uncertainty
    /// let loc = OLocation::new(47.376887, 8.541694, 1000).unwrap();
    ///
    /// // Exact point (radius = 0)
    /// let exact = OLocation::new(51.5074, -0.1278, 0).unwrap();
    /// ```
    pub fn new(lat: f64, lon: f64, radius: u16) -> Result<Self> {
        // Validate latitude
        if !(-90.0..=90.0).contains(&lat) {
            return Err(OtomlError::InvalidLocation(format!(
                "latitude {} out of range (-90 to 90)",
                lat
            )));
        }

        // Validate longitude
        if !(-180.0..=180.0).contains(&lon) {
            return Err(OtomlError::InvalidLocation(format!(
                "longitude {} out of range (-180 to 180)",
                lon
            )));
        }

        // Check for NaN/infinity
        if lat.is_nan() || lat.is_infinite() {
            return Err(OtomlError::InvalidLocation(
                "latitude cannot be NaN or infinity".to_string(),
            ));
        }
        if lon.is_nan() || lon.is_infinite() {
            return Err(OtomlError::InvalidLocation(
                "longitude cannot be NaN or infinity".to_string(),
            ));
        }

        // Convert to micro-degrees with round-half-away-from-zero
        let lat_micro = round_half_away_from_zero(lat * MICRO_DEGREES as f64) as i32;
        let lon_micro = round_half_away_from_zero(lon * MICRO_DEGREES as f64) as i32;

        Ok(OLocation {
            lat_micro,
            lon_micro,
            radius,
        })
    }

    /// Create from micro-degrees directly (for binary deserialization).
    ///
    /// # Arguments
    /// * `lat_micro` - Latitude in micro-degrees
    /// * `lon_micro` - Longitude in micro-degrees
    /// * `radius` - Uncertainty radius in meters
    pub fn from_micro(lat_micro: i32, lon_micro: i32, radius: u16) -> Result<Self> {
        if !(-MAX_LAT_MICRO..=MAX_LAT_MICRO).contains(&lat_micro) {
            return Err(OtomlError::InvalidLocation(format!(
                "latitude micro-degrees {} out of range",
                lat_micro
            )));
        }
        if !(-MAX_LON_MICRO..=MAX_LON_MICRO).contains(&lon_micro) {
            return Err(OtomlError::InvalidLocation(format!(
                "longitude micro-degrees {} out of range",
                lon_micro
            )));
        }

        Ok(OLocation {
            lat_micro,
            lon_micro,
            radius,
        })
    }

    /// Get latitude in decimal degrees.
    pub fn lat(&self) -> f64 {
        self.lat_micro as f64 / MICRO_DEGREES as f64
    }

    /// Get longitude in decimal degrees.
    pub fn lon(&self) -> f64 {
        self.lon_micro as f64 / MICRO_DEGREES as f64
    }

    /// Get latitude in micro-degrees.
    pub fn lat_micro(&self) -> i32 {
        self.lat_micro
    }

    /// Get longitude in micro-degrees.
    pub fn lon_micro(&self) -> i32 {
        self.lon_micro
    }

    /// Get uncertainty radius in meters.
    pub fn radius(&self) -> u16 {
        self.radius
    }

    /// Check if this is an exact point (radius = 0).
    pub fn is_exact(&self) -> bool {
        self.radius == 0
    }

    /// Calculate great-circle distance to another location in meters.
    ///
    /// Uses the Haversine formula for accurate distance on Earth's surface.
    /// Returns the distance between the center points (ignores radius).
    ///
    /// # Example
    /// ```
    /// use herolib_otoml::OLocation;
    ///
    /// let zurich = OLocation::new(47.376887, 8.541694, 0).unwrap();
    /// let london = OLocation::new(51.507351, -0.127758, 0).unwrap();
    ///
    /// let distance_km = zurich.distance(&london) / 1000.0;
    /// assert!((distance_km - 778.0).abs() < 5.0); // ~778 km
    /// ```
    pub fn distance(&self, other: &OLocation) -> f64 {
        haversine_distance(self.lat(), self.lon(), other.lat(), other.lon())
    }

    /// Calculate distance considering uncertainty radii.
    ///
    /// Returns the minimum possible distance between the uncertainty circles.
    /// If circles overlap, returns 0.
    ///
    /// # Example
    /// ```
    /// use herolib_otoml::OLocation;
    ///
    /// let loc1 = OLocation::new(47.376887, 8.541694, 1000).unwrap();
    /// let loc2 = OLocation::new(47.380000, 8.545000, 500).unwrap();
    ///
    /// // Minimum distance between uncertainty circles
    /// let min_dist = loc1.distance_with_uncertainty(&loc2);
    /// ```
    pub fn distance_with_uncertainty(&self, other: &OLocation) -> f64 {
        let center_distance = self.distance(other);
        let combined_radius = self.radius as f64 + other.radius as f64;

        if center_distance <= combined_radius {
            0.0
        } else {
            center_distance - combined_radius
        }
    }

    /// Check if this location's uncertainty circle overlaps with another.
    pub fn overlaps(&self, other: &OLocation) -> bool {
        self.distance_with_uncertainty(other) == 0.0
    }

    /// Check if a point (given as lat/lon) is within this location's uncertainty circle.
    pub fn contains_point(&self, lat: f64, lon: f64) -> Result<bool> {
        let point = OLocation::new(lat, lon, 0)?;
        Ok(self.distance(&point) <= self.radius as f64)
    }
}

impl Default for OLocation {
    fn default() -> Self {
        OLocation {
            lat_micro: 0,
            lon_micro: 0,
            radius: 0,
        }
    }
}

impl fmt::Display for OLocation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let lat = self.lat();
        let lon = self.lon();

        // Format with up to 6 decimal places, no trailing zeros
        let lat_str = format_decimal(lat, 6);
        let lon_str = format_decimal(lon, 6);

        write!(f, "({},{},{})", lat_str, lon_str, self.radius)
    }
}

impl FromStr for OLocation {
    type Err = OtomlError;

    fn from_str(s: &str) -> Result<Self> {
        let s = s.trim();

        // Must start with ( and end with )
        if !s.starts_with('(') || !s.ends_with(')') {
            return Err(OtomlError::InvalidLocation(format!(
                "invalid format, expected (lat,lon,radius), got '{}'",
                s
            )));
        }

        let inner = &s[1..s.len() - 1];
        let parts: Vec<&str> = inner.split(',').collect();

        if parts.len() != 3 {
            return Err(OtomlError::InvalidLocation(format!(
                "expected 3 components (lat,lon,radius), got {}",
                parts.len()
            )));
        }

        let lat: f64 = parts[0]
            .trim()
            .parse()
            .map_err(|_| OtomlError::InvalidLocation(format!("invalid latitude '{}'", parts[0])))?;

        let lon: f64 = parts[1].trim().parse().map_err(|_| {
            OtomlError::InvalidLocation(format!("invalid longitude '{}'", parts[1]))
        })?;

        let radius: u16 = parts[2]
            .trim()
            .parse()
            .map_err(|_| OtomlError::InvalidLocation(format!("invalid radius '{}'", parts[2])))?;

        OLocation::new(lat, lon, radius)
    }
}

impl Ord for OLocation {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        // Canonical ordering: latitude, then longitude, then radius
        self.lat_micro
            .cmp(&other.lat_micro)
            .then(self.lon_micro.cmp(&other.lon_micro))
            .then(self.radius.cmp(&other.radius))
    }
}

impl PartialOrd for OLocation {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Serialize for OLocation {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        // Serialize as string in canonical form
        serializer.serialize_str(&self.to_string())
    }
}

impl<'de> Deserialize<'de> for OLocation {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        OLocation::from_str(&s).map_err(serde::de::Error::custom)
    }
}

/// Haversine formula for great-circle distance.
fn haversine_distance(lat1: f64, lon1: f64, lat2: f64, lon2: f64) -> f64 {
    let lat1_rad = lat1.to_radians();
    let lat2_rad = lat2.to_radians();
    let delta_lat = (lat2 - lat1).to_radians();
    let delta_lon = (lon2 - lon1).to_radians();

    let a = (delta_lat / 2.0).sin().powi(2)
        + lat1_rad.cos() * lat2_rad.cos() * (delta_lon / 2.0).sin().powi(2);

    let c = 2.0 * a.sqrt().asin();

    EARTH_RADIUS_METERS * c
}

/// Round half away from zero (standard rounding).
fn round_half_away_from_zero(x: f64) -> f64 {
    if x >= 0.0 {
        (x + 0.5).floor()
    } else {
        (x - 0.5).ceil()
    }
}

/// Format a decimal number with maximum precision, removing trailing zeros.
fn format_decimal(value: f64, max_decimals: usize) -> String {
    let formatted = format!("{:.prec$}", value, prec = max_decimals);

    // Remove trailing zeros after decimal point
    if formatted.contains('.') {
        let trimmed = formatted.trim_end_matches('0').trim_end_matches('.');
        if trimmed.is_empty() || trimmed == "-" {
            "0".to_string()
        } else {
            trimmed.to_string()
        }
    } else {
        formatted
    }
}

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

    #[test]
    fn test_new() {
        let loc = OLocation::new(47.376887, 8.541694, 1000).unwrap();
        assert!((loc.lat() - 47.376887).abs() < 0.000001);
        assert!((loc.lon() - 8.541694).abs() < 0.000001);
        assert_eq!(loc.radius(), 1000);
    }

    #[test]
    fn test_display() {
        let loc = OLocation::new(47.376887, 8.541694, 1000).unwrap();
        assert_eq!(loc.to_string(), "(47.376887,8.541694,1000)");

        // Negative coordinates
        let loc = OLocation::new(-33.86882, 151.209296, 3000).unwrap();
        assert_eq!(loc.to_string(), "(-33.86882,151.209296,3000)");

        // Exact point
        let loc = OLocation::new(0.0, 0.0, 0).unwrap();
        assert_eq!(loc.to_string(), "(0,0,0)");
    }

    #[test]
    fn test_parse() {
        let loc: OLocation = "(47.376887,8.541694,5)".parse().unwrap();
        assert!((loc.lat() - 47.376887).abs() < 0.000001);
        assert!((loc.lon() - 8.541694).abs() < 0.000001);
        assert_eq!(loc.radius(), 5);

        // With whitespace
        let loc: OLocation = "( 51.507351 , -0.127758 , 1000 )".parse().unwrap();
        assert!((loc.lat() - 51.507351).abs() < 0.000001);

        // Negative coordinates
        let loc: OLocation = "(-33.868820,151.209296,3000)".parse().unwrap();
        assert!((loc.lat() - -33.86882).abs() < 0.000001);
    }

    #[test]
    fn test_roundtrip() {
        let original = "(47.376887,8.541694,1000)";
        let loc: OLocation = original.parse().unwrap();
        assert_eq!(loc.to_string(), original);
    }

    #[test]
    fn test_validation() {
        // Valid edge cases
        assert!(OLocation::new(90.0, 180.0, 0).is_ok());
        assert!(OLocation::new(-90.0, -180.0, 65535).is_ok());

        // Invalid latitude
        assert!(OLocation::new(91.0, 0.0, 0).is_err());
        assert!(OLocation::new(-91.0, 0.0, 0).is_err());

        // Invalid longitude
        assert!(OLocation::new(0.0, 181.0, 0).is_err());
        assert!(OLocation::new(0.0, -181.0, 0).is_err());

        // NaN/infinity
        assert!(OLocation::new(f64::NAN, 0.0, 0).is_err());
        assert!(OLocation::new(0.0, f64::INFINITY, 0).is_err());
    }

    #[test]
    fn test_distance_same_point() {
        let loc = OLocation::new(47.376887, 8.541694, 0).unwrap();
        assert_eq!(loc.distance(&loc), 0.0);
    }

    #[test]
    fn test_distance_zurich_london() {
        let zurich = OLocation::new(47.376887, 8.541694, 0).unwrap();
        let london = OLocation::new(51.507351, -0.127758, 0).unwrap();

        let distance_km = zurich.distance(&london) / 1000.0;

        // Known distance is approximately 778 km
        assert!(
            (distance_km - 778.0).abs() < 5.0,
            "Expected ~778 km, got {} km",
            distance_km
        );
    }

    #[test]
    fn test_distance_antipodal() {
        // North pole to south pole
        let north = OLocation::new(90.0, 0.0, 0).unwrap();
        let south = OLocation::new(-90.0, 0.0, 0).unwrap();

        let distance_km = north.distance(&south) / 1000.0;

        // Half Earth circumference ~20,000 km
        assert!(
            (distance_km - 20015.0).abs() < 100.0,
            "Expected ~20015 km, got {} km",
            distance_km
        );
    }

    #[test]
    fn test_distance_equator() {
        // Two points on equator, 90 degrees apart
        let p1 = OLocation::new(0.0, 0.0, 0).unwrap();
        let p2 = OLocation::new(0.0, 90.0, 0).unwrap();

        let distance_km = p1.distance(&p2) / 1000.0;

        // Quarter of Earth circumference ~10,000 km
        assert!(
            (distance_km - 10007.5).abs() < 50.0,
            "Expected ~10007.5 km, got {} km",
            distance_km
        );
    }

    #[test]
    fn test_distance_with_uncertainty() {
        let loc1 = OLocation::new(47.376887, 8.541694, 1000).unwrap();
        let loc2 = OLocation::new(47.376887, 8.541694, 500).unwrap();

        // Same center, circles overlap
        assert_eq!(loc1.distance_with_uncertainty(&loc2), 0.0);
        assert!(loc1.overlaps(&loc2));
    }

    #[test]
    fn test_distance_with_uncertainty_no_overlap() {
        // Two points far apart
        let zurich = OLocation::new(47.376887, 8.541694, 1000).unwrap();
        let london = OLocation::new(51.507351, -0.127758, 1000).unwrap();

        let center_dist = zurich.distance(&london);
        let min_dist = zurich.distance_with_uncertainty(&london);

        // Minimum distance should be center distance minus both radii
        assert!((min_dist - (center_dist - 2000.0)).abs() < 1.0);
        assert!(!zurich.overlaps(&london));
    }

    #[test]
    fn test_contains_point() {
        let loc = OLocation::new(47.376887, 8.541694, 1000).unwrap();

        // Center point is contained
        assert!(loc.contains_point(47.376887, 8.541694).unwrap());

        // Nearby point within radius
        assert!(loc.contains_point(47.377, 8.542).unwrap());

        // Far point not contained
        assert!(!loc.contains_point(48.0, 9.0).unwrap());
    }

    #[test]
    fn test_is_exact() {
        let exact = OLocation::new(47.376887, 8.541694, 0).unwrap();
        assert!(exact.is_exact());

        let uncertain = OLocation::new(47.376887, 8.541694, 100).unwrap();
        assert!(!uncertain.is_exact());
    }

    #[test]
    fn test_ordering() {
        let loc1 = OLocation::new(47.0, 8.0, 100).unwrap();
        let loc2 = OLocation::new(48.0, 8.0, 100).unwrap();
        let loc3 = OLocation::new(47.0, 9.0, 100).unwrap();
        let loc4 = OLocation::new(47.0, 8.0, 200).unwrap();

        assert!(loc1 < loc2); // Higher latitude
        assert!(loc1 < loc3); // Higher longitude
        assert!(loc1 < loc4); // Higher radius
    }

    #[test]
    fn test_from_micro() {
        let loc = OLocation::from_micro(47_376_887, 8_541_694, 1000).unwrap();
        assert_eq!(loc.lat_micro(), 47_376_887);
        assert_eq!(loc.lon_micro(), 8_541_694);
        assert!((loc.lat() - 47.376887).abs() < 0.000001);
    }

    #[test]
    fn test_serde_roundtrip() {
        use serde::{Deserialize, Serialize};

        #[derive(Serialize, Deserialize, PartialEq, Debug)]
        struct Event {
            name: String,
            location: OLocation,
        }

        let event = Event {
            name: "Meeting".to_string(),
            location: OLocation::new(47.376887, 8.541694, 1000).unwrap(),
        };

        let otoml = crate::dump_otoml(&event).unwrap();
        assert!(otoml.contains("location = \"(47.376887,8.541694,1000)\""));

        let parsed: Event = crate::load_otoml(&otoml).unwrap();
        assert_eq!(event, parsed);
    }

    #[test]
    fn test_micro_degree_precision() {
        // 1 micro-degree at equator is approximately 11.1 cm
        let p1 = OLocation::new(0.0, 0.0, 0).unwrap();
        let p2 = OLocation::new(0.000001, 0.0, 0).unwrap();

        let distance_cm = p1.distance(&p2) * 100.0;

        // Should be approximately 11 cm
        assert!(
            (distance_cm - 11.1).abs() < 1.0,
            "Expected ~11.1 cm, got {} cm",
            distance_cm
        );
    }

    #[test]
    fn test_format_decimal() {
        assert_eq!(format_decimal(47.376887, 6), "47.376887");
        assert_eq!(format_decimal(47.0, 6), "47");
        assert_eq!(format_decimal(47.5, 6), "47.5");
        assert_eq!(format_decimal(-33.86882, 6), "-33.86882");
        assert_eq!(format_decimal(0.0, 6), "0");
    }

    #[test]
    fn test_known_cities() {
        // Test with known city coordinates
        let cities = vec![
            ("Zurich", 47.376887, 8.541694),
            ("London", 51.507351, -0.127758),
            ("Sydney", -33.868820, 151.209296),
            ("New York", 40.712776, -74.005974),
            ("Tokyo", 35.689487, 139.691711),
        ];

        for (name, lat, lon) in cities {
            let loc = OLocation::new(lat, lon, 100).unwrap();
            assert!(
                (loc.lat() - lat).abs() < 0.000001,
                "{} latitude mismatch",
                name
            );
            assert!(
                (loc.lon() - lon).abs() < 0.000001,
                "{} longitude mismatch",
                name
            );
        }
    }

    #[test]
    fn test_binary_roundtrip() {
        use serde::{Deserialize, Serialize};

        #[derive(Serialize, Deserialize, PartialEq, Debug)]
        struct Poi {
            name: String,
            location: OLocation,
        }

        let poi = Poi {
            name: "Zurich HB".to_string(),
            location: OLocation::new(47.378177, 8.540192, 50).unwrap(),
        };

        let bytes = crate::dump_obin(&poi).unwrap();
        let parsed: Poi = crate::load_obin(&bytes).unwrap();

        assert_eq!(poi, parsed);
    }

    #[test]
    fn test_default() {
        let loc = OLocation::default();
        assert_eq!(loc.lat(), 0.0);
        assert_eq!(loc.lon(), 0.0);
        assert_eq!(loc.radius(), 0);
        assert!(loc.is_exact());
    }

    #[test]
    fn test_hash() {
        use std::collections::HashSet;

        let l1 = OLocation::new(47.376887, 8.541694, 100).unwrap();
        let l2 = OLocation::new(47.376887, 8.541694, 100).unwrap();
        let l3 = OLocation::new(47.376887, 8.541694, 200).unwrap();

        let mut set = HashSet::new();
        set.insert(l1);
        set.insert(l2); // duplicate
        set.insert(l3); // different radius

        assert_eq!(set.len(), 2);
    }

    #[test]
    fn test_clone_and_copy() {
        let l1 = OLocation::new(47.376887, 8.541694, 100).unwrap();
        let l2 = l1; // Copy
        let l3 = l1.clone();

        assert_eq!(l1, l2);
        assert_eq!(l1, l3);
    }

    #[test]
    fn test_extreme_coordinates() {
        // North Pole
        let north = OLocation::new(90.0, 0.0, 0).unwrap();
        assert_eq!(north.lat(), 90.0);

        // South Pole
        let south = OLocation::new(-90.0, 0.0, 0).unwrap();
        assert_eq!(south.lat(), -90.0);

        // Dateline
        let west = OLocation::new(0.0, -180.0, 0).unwrap();
        assert_eq!(west.lon(), -180.0);

        let east = OLocation::new(0.0, 180.0, 0).unwrap();
        assert_eq!(east.lon(), 180.0);

        // Null Island (0, 0)
        let null = OLocation::new(0.0, 0.0, 0).unwrap();
        assert_eq!(null.lat(), 0.0);
        assert_eq!(null.lon(), 0.0);
    }

    #[test]
    fn test_max_radius() {
        let loc = OLocation::new(0.0, 0.0, u16::MAX).unwrap();
        assert_eq!(loc.radius(), 65535);
    }

    #[test]
    fn test_overlaps_edge_cases() {
        // Exactly touching circles
        let l1 = OLocation::new(0.0, 0.0, 1000).unwrap();
        let l2 = OLocation::new(0.0, 0.018, 1000).unwrap(); // ~2km apart at equator

        let center_dist = l1.distance(&l2);
        println!("Center distance: {} m", center_dist);

        // If center distance <= combined radius, they overlap
        let combined = l1.radius() as f64 + l2.radius() as f64;
        if center_dist <= combined {
            assert!(l1.overlaps(&l2));
        } else {
            assert!(!l1.overlaps(&l2));
        }
    }

    #[test]
    fn test_from_micro_edge_cases() {
        // Max latitude
        let max_lat = OLocation::from_micro(90_000_000, 0, 0).unwrap();
        assert_eq!(max_lat.lat(), 90.0);

        // Min latitude
        let min_lat = OLocation::from_micro(-90_000_000, 0, 0).unwrap();
        assert_eq!(min_lat.lat(), -90.0);

        // Max longitude
        let max_lon = OLocation::from_micro(0, 180_000_000, 0).unwrap();
        assert_eq!(max_lon.lon(), 180.0);

        // Min longitude
        let min_lon = OLocation::from_micro(0, -180_000_000, 0).unwrap();
        assert_eq!(min_lon.lon(), -180.0);

        // Out of range
        assert!(OLocation::from_micro(91_000_000, 0, 0).is_err());
        assert!(OLocation::from_micro(0, 181_000_000, 0).is_err());
    }

    #[test]
    fn test_negative_coordinates() {
        // Southern hemisphere
        let sydney = OLocation::new(-33.868820, 151.209296, 100).unwrap();
        assert!(sydney.lat() < 0.0);
        assert!(sydney.lon() > 0.0);

        // Western hemisphere
        let new_york = OLocation::new(40.712776, -74.005974, 100).unwrap();
        assert!(new_york.lat() > 0.0);
        assert!(new_york.lon() < 0.0);

        // Southwest quadrant
        let buenos_aires = OLocation::new(-34.603722, -58.381592, 100).unwrap();
        assert!(buenos_aires.lat() < 0.0);
        assert!(buenos_aires.lon() < 0.0);
    }

    #[test]
    fn test_contains_point_edge() {
        let loc = OLocation::new(0.0, 0.0, 1000).unwrap();

        // Points at various angles around the center
        let angles: [f64; 8] = [0.0, 45.0, 90.0, 135.0, 180.0, 225.0, 270.0, 315.0];
        for angle in angles {
            let rad = angle.to_radians();
            // Point ~500m away (well within 1000m radius)
            let delta: f64 = 0.0045; // ~500m
            let lat = delta * rad.cos();
            let lon = delta * rad.sin();
            assert!(
                loc.contains_point(lat, lon).unwrap(),
                "Point at {}° should be contained",
                angle
            );
        }
    }
}