Modern Apps git

← Modern-Apps.git

networklocation: add position Rust tests and fix corrupt-data panics

Commit
c7cc3540f6d8857eaffe094da9507696ea02b02f
Author
Vayun Mathur <[email protected]>
When
2026-11-17 21:46 UTC (18 days ago)
Parents
a3b744d
37 new tests (22 -> 59): geocoder binary format (varint/zigzag/column/dict decode on synthetic in-memory data), WPS DB bit extraction, multilateration solver, JNI estimate entry. Fixes found by the tests: be32/be64 offset overflow panic on corrupt headers (checked_add), read_varint shift-overflow panic on overlong varints (reject at shift >= 32), Position::average of an empty set returning NaN coordinates (returns the fake default), and multilateration iteration-count underflow panic for >333 inliers (clamped). cargo test -p network_location_position_estimation_rust green.

Diff

networklocation/src/main/rust/src/coordinate.rs
diff --git a/networklocation/src/main/rust/src/coordinate.rs b/networklocation/src/main/rust/src/coordinate.rsindex 1a95b6edd3..8ef96301de 100644--- a/networklocation/src/main/rust/src/coordinate.rs+++ b/networklocation/src/main/rust/src/coordinate.rs@@ -34,3 +34,32 @@ impl Coordinate {         }     } }++#[cfg(test)]+mod tests {+    use super::*;++    #[test]+    fn new_real_keeps_value_and_variance() {+        let c = Coordinate::new_real(-12.5, 36.0);+        assert!(c.real);+        assert_eq!(c.value, -12.5);+        assert_eq!(c.six_sigma_squared, 36.0);+    }++    #[test]+    fn new_fake_is_zeroed_and_not_real() {+        let c = Coordinate::new_fake();+        assert!(!c.real);+        assert_eq!(c.value, 0.0);+        assert_eq!(c.six_sigma_squared, 0.0);+    }++    #[test]+    fn coordinate_is_copy() {+        let c = Coordinate::new_real(1.0, 2.0);+        let copy = c;+        assert_eq!(copy.value, c.value);+        assert!(copy.real);+    }+}
networklocation/src/main/rust/src/geocoder.rs
diff --git a/networklocation/src/main/rust/src/geocoder.rs b/networklocation/src/main/rust/src/geocoder.rsindex 988d01f07b..27223c3e8b 100644--- a/networklocation/src/main/rust/src/geocoder.rs+++ b/networklocation/src/main/rust/src/geocoder.rs@@ -88,10 +88,10 @@ const GRID_ENTRY: usize = 12;  // --------------------------------------------------------------------------- byte helpers fn be32(d: &[u8], p: usize) -> Option<u32> {-    Some(u32::from_be_bytes(d.get(p..p + 4)?.try_into().ok()?))+    Some(u32::from_be_bytes(d.get(p..p.checked_add(4)?)?.try_into().ok()?)) } fn be64(d: &[u8], p: usize) -> Option<i64> {-    Some(i64::from_be_bytes(d.get(p..p + 8)?.try_into().ok()?))+    Some(i64::from_be_bytes(d.get(p..p.checked_add(8)?)?.try_into().ok()?)) } fn unzigzag(v: u32) -> i32 {     ((v >> 1) as i32) ^ -((v & 1) as i32)@@ -100,6 +100,11 @@ fn read_varint(a: &[u8], p: &mut usize) -> Option<u32> {     let mut v: u32 = 0;     let mut shift = 0;     loop {+        // A u32 varint is at most 5 bytes; a longer run is malformed, and+        // shifting by 32+ would panic.+        if shift >= 32 {+            return None;+        }         let b = *a.get(*p)?;         *p += 1;         v |= ((b & 0x7F) as u32) << shift;@@ -359,3 +364,7 @@ pub struct Reader {  include!("geocoder_part1.rs"); include!("geocoder_part2.rs");++#[cfg(test)]+#[path = "geocoder_tests.rs"]+mod geocoder_tests;
networklocation/src/main/rust/src/geocoder_tests.rs
diff --git a/networklocation/src/main/rust/src/geocoder_tests.rs b/networklocation/src/main/rust/src/geocoder_tests.rsnew file mode 100644index 0000000000..fe932ebc43--- /dev/null+++ b/networklocation/src/main/rust/src/geocoder_tests.rs@@ -0,0 +1,264 @@+//! Synthetic-buffer tests for the geocoder's pure byte/codec helpers and for+//! `Column`/`Dict` decoding. The DB-backed tests in `geocoder_part2.rs` self-skip+//! without a ~1 GB asset; these build tiny in-memory sections in the exact+//! on-disk layout so the decode paths run in every CI job.++use super::*;+use std::io::Cursor;++fn compress(raw: &[u8]) -> Vec<u8> {+    ruzstd::encoding::compress_to_vec(Cursor::new(raw), ruzstd::encoding::CompressionLevel::Uncompressed)+}++fn zigzag(v: i32) -> u32 {+    ((v << 1) ^ (v >> 31)) as u32+}++fn push_varint(mut v: u32, out: &mut Vec<u8>) {+    loop {+        let b = (v & 0x7F) as u8;+        v >>= 7;+        if v == 0 {+            out.push(b);+            return;+        }+        out.push(b | 0x80);+    }+}++fn push_be32(out: &mut Vec<u8>, v: u32) {+    out.extend_from_slice(&v.to_be_bytes());+}++/// Build a `Column` body (as `Column::new` expects at `body`) holding `vals`.+fn column_body(vals: &[i32], delta: bool) -> Vec<u8> {+    let blocks: Vec<Vec<u8>> = vals+        .chunks(BLOCK as usize)+        .map(|chunk| {+            let mut raw = Vec::new();+            let mut prev = 0i32;+            for &v in chunk {+                let dv = if delta { v.wrapping_sub(prev) } else { v };+                prev = v;+                push_varint(zigzag(dv), &mut raw);+            }+            raw+        })+        .collect();+    let mut out = Vec::new();+    push_be32(&mut out, vals.len() as u32);+    push_be32(&mut out, blocks.len() as u32);+    let mut end = 0u32;+    let mut comps = Vec::new();+    for raw in &blocks {+        let comp = compress(raw);+        end += comp.len() as u32;+        push_be32(&mut out, raw.len() as u32);+        push_be32(&mut out, end);+        comps.push(comp);+    }+    for comp in comps {+        out.extend_from_slice(&comp);+    }+    out+}++/// Build a `Dict` body holding `strings` (already in UTF-16 sorted order).+fn dict_body(strings: &[&str], per: usize) -> Vec<u8> {+    let blocks: Vec<&[&str]> = strings.chunks(per).collect();+    let firsts: Vec<u8> = blocks.iter().flat_map(|b| b[0].bytes()).collect();+    let raws: Vec<Vec<u8>> = blocks+        .iter()+        .map(|b| {+            let mut raw = Vec::new();+            for s in *b {+                push_be32(&mut raw, s.len() as u32);+                raw.extend_from_slice(s.as_bytes());+            }+            raw+        })+        .collect();+    let mut out = Vec::new();+    push_be32(&mut out, strings.len() as u32);+    push_be32(&mut out, per as u32);+    push_be32(&mut out, blocks.len() as u32);+    let mut end = 0u32;+    for b in &blocks {+        end += b[0].len() as u32;+        push_be32(&mut out, end);+    }+    out.extend_from_slice(&firsts);+    let comps: Vec<Vec<u8>> = raws.iter().map(|r| compress(r)).collect();+    let mut end = 0u32;+    for c in &comps {+        end += c.len() as u32;+        push_be32(&mut out, end);+    }+    for c in comps {+        out.extend_from_slice(&c);+    }+    out+}++#[test]+fn be_reads_are_bounds_checked() {+    let d = [0x01u8, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08];+    assert_eq!(be32(&d, 0), Some(0x0102_0304));+    assert_eq!(be32(&d, 4), Some(0x0506_0708));+    assert_eq!(be32(&d, 5), None);+    assert_eq!(be32(&d, usize::MAX), None);+    assert_eq!(be64(&d, 0), Some(0x0102_0304_0506_0708));+    assert_eq!(be64(&d, 1), None);+    assert_eq!(be32(&[], 0), None);+}++#[test]+fn unzigzag_inverts_zigzag() {+    for v in [0i32, -1, 1, -2, 2, 123_456, -123_456, i32::MAX, i32::MIN + 1] {+        assert_eq!(unzigzag(zigzag(v)), v);+    }+    assert_eq!(unzigzag(0), 0);+    assert_eq!(unzigzag(1), -1);+    assert_eq!(unzigzag(2), 1);+    assert_eq!(unzigzag(u32::MAX), i32::MIN);+}++#[test]+fn varint_round_trip_and_truncation() {+    for v in [0u32, 1, 0x7F, 0x80, 300, 16_384, 1 << 20, u32::MAX] {+        let mut buf = Vec::new();+        push_varint(v, &mut buf);+        let mut p = 0usize;+        assert_eq!(read_varint(&buf, &mut p), Some(v));+        assert_eq!(p, buf.len());+    }+    // Truncated continuation byte: must miss, not panic or loop.+    let mut p = 0usize;+    assert_eq!(read_varint(&[0x80], &mut p), None);+    let mut p = 0usize;+    assert_eq!(read_varint(&[], &mut p), None);+}++#[test]+fn varint_overlong_encoding_is_rejected() {+    // A u32 varint is at most 5 bytes; ten continuation bytes is malformed.+    // The decoder must reject it instead of shifting past 32 bits.+    let buf = [0xFFu8; 10];+    let mut p = 0usize;+    assert_eq!(read_varint(&buf, &mut p), None);+}++#[test]+fn cmp_utf16_uses_utf16_code_units() {+    assert_eq!(cmp_utf16("Apple", "apple"), Ordering::Less);+    assert_eq!(cmp_utf16("abc", "abc"), Ordering::Equal);+    assert_eq!(cmp_utf16("ab", "abc"), Ordering::Less);+    // U+FFFF is a single UTF-16 unit 0xFFFF; U+10000 is a surrogate pair+    // starting at 0xD800, so UTF-16 order puts U+10000 first — the opposite+    // of code-point/UTF-8 order.+    assert_eq!(cmp_utf16("\u{FFFF}", "\u{10000}"), Ordering::Greater);+    assert_eq!(cmp_utf16("\u{10000}", "\u{FFFF}"), Ordering::Less);+    assert_eq!(cmp_utf16("", "a"), Ordering::Less);+}++#[test]+fn to_e5_quantizes_to_nearest() {+    assert_eq!(to_e5(0.0), 0);+    assert_eq!(to_e5(37.7749295), 3_777_493);+    assert_eq!(to_e5(-122.4194155), -12_241_942);+    assert_eq!(to_e5(-0.000001), 0);+    assert_eq!(to_e5(90.0), 9_000_000);+    assert_eq!(to_e5(-180.0), -18_000_000);+    // Just below/above a half-step boundary.+    assert_eq!(to_e5(0.0000149), 1);+    assert_eq!(to_e5(0.0000151), 2);+    assert_eq!(to_e5(-0.0000149), -1);+}++#[test]+fn column_non_delta_round_trip_and_out_of_range() {+    let vals: Vec<i32> = vec![0, -1, 1, 42, -99_999, i32::MAX / 2, 7];+    let body = column_body(&vals, false);+    let mut col = Column::new(&body, 0, false).expect("column parses");+    for (i, &v) in vals.iter().enumerate() {+        assert_eq!(col.get(&body, i as i32), v);+    }+    assert_eq!(col.get(&body, -1), 0);+    assert_eq!(col.get(&body, vals.len() as i32), 0);+    // Re-reading exercises the single-block cache path.+    assert_eq!(col.get(&body, 3), 42);+}++#[test]+fn column_delta_round_trip_across_blocks() {+    // One value past a full block forces a second block; delta state resets+    // per block, exactly as the builder encodes it.+    let mut vals: Vec<i32> = (0..BLOCK + 3).map(|i| i * 3 - 5000).collect();+    vals[BLOCK as usize] = -777;+    let body = column_body(&vals, true);+    let mut col = Column::new(&body, 0, true).expect("column parses");+    for (i, &v) in vals.iter().enumerate() {+        assert_eq!(col.get(&body, i as i32), v, "index {i}");+    }+    // Jump back to block 0: cache must re-decode correctly.+    assert_eq!(col.get(&body, 0), vals[0]);+}++#[test]+fn column_rejects_truncated_or_inconsistent_headers() {+    assert!(Column::new(&[0u8; 4], 0, false).is_none());+    // n claims more blocks than the directory can hold.+    let mut body = Vec::new();+    push_be32(&mut body, (BLOCK + 1) as u32);+    push_be32(&mut body, 1);+    push_be32(&mut body, 0);+    push_be32(&mut body, 0);+    assert!(Column::new(&body, 0, false).is_none());+}++#[test]+fn dict_lookup_get_and_index_of() {+    let strings = ["Apple", "Banana", "Cherry", "Date", "Elderberry", "Fig"];+    let body = dict_body(&strings, 2);+    let end = body.len();+    let mut dict = Dict::new(&body, 0, end).expect("dict parses");+    for (i, s) in strings.iter().enumerate() {+        assert_eq!(dict.get(&body, i), *s);+        assert_eq!(dict.index_of(&body, s), Some(i));+    }+    assert_eq!(dict.get(&body, strings.len()), "");+    assert_eq!(dict.index_of(&body, "Blueberry"), None);+    assert_eq!(dict.index_of(&body, ""), None);+    assert_eq!(dict.index_of(&body, "apple"), None, "lookup is case-sensitive");+    assert_eq!(dict.first(&body, 1), "Cherry");+    assert_eq!(dict.first(&body, 99), "");+}++#[test]+fn dict_partition_point_boundaries() {+    let strings = ["Apple", "Banana", "Cherry", "Date"];+    let body = dict_body(&strings, 2);+    let end = body.len();+    let mut dict = Dict::new(&body, 0, end).expect("dict parses");+    // Count of strings < key.+    assert_eq!(dict.partition_point(&body, |s| cmp_utf16(s, "Apple") == Ordering::Less), 0);+    assert_eq!(dict.partition_point(&body, |s| cmp_utf16(s, "Cherry") == Ordering::Less), 2);+    assert_eq!(dict.partition_point(&body, |s| cmp_utf16(s, "Zebra") == Ordering::Less), 4);+    assert_eq!(dict.partition_point(&body, |_| true), 4);+    assert_eq!(dict.partition_point(&body, |_| false), 0);+}++#[test]+fn dict_rejects_bad_geometry() {+    // per == 0+    let mut body = Vec::new();+    push_be32(&mut body, 3);+    push_be32(&mut body, 0);+    push_be32(&mut body, 0);+    assert!(Dict::new(&body, 0, body.len()).is_none());+    // blocks inconsistent with count/per+    let body = dict_body(&["A", "B"], 2);+    let mut bad = body.clone();+    bad[8..12].copy_from_slice(&5u32.to_be_bytes());+    assert!(Dict::new(&bad, 0, bad.len()).is_none());+}
networklocation/src/main/rust/src/jni.rs
diff --git a/networklocation/src/main/rust/src/jni.rs b/networklocation/src/main/rust/src/jni.rsindex a5cf5ec5ee..fa035a8f14 100644--- a/networklocation/src/main/rust/src/jni.rs+++ b/networklocation/src/main/rust/src/jni.rs@@ -86,6 +86,70 @@ fn estimate_lat_lon(beacons: &[f64]) -> Option<[f64; 3]> {     Some([lat, lon, accuracy]) } +#[cfg(test)]+mod tests {+    use super::*;++    #[test]+    fn rejects_empty_and_ragged_and_nonfinite_only() {+        assert_eq!(estimate_lat_lon(&[]), None);+        assert_eq!(estimate_lat_lon(&[37.0, -122.0]), None);+        assert_eq!(estimate_lat_lon(&[37.0, -122.0, 10.0, 1.0]), None);+        assert_eq!(estimate_lat_lon(&[f64::NAN, f64::NAN, f64::NAN]), None);+        assert_eq!(estimate_lat_lon(&[f64::INFINITY, 0.0, 10.0]), None);+    }++    #[test]+    fn single_beacon_estimates_its_own_position() {+        // Four copies of one beacon: the solver needs >= 4 inliers, and the+        // only position consistent with all of them is the beacon itself.+        let beacons = [37.7749, -122.4194, 20.0].repeat(4);+        let [lat, lon, acc] = estimate_lat_lon(&beacons).expect("estimate");+        assert!((lat - 37.7749).abs() < 0.001, "lat {lat}");+        assert!((lon - -122.4194).abs() < 0.001, "lon {lon}");+        assert!(acc.is_finite() && acc >= 0.0, "acc {acc}");+    }++    #[test]+    fn cluster_center_is_recovered_and_outlier_ignored() {+        // Four beacons tightly around a centre plus one far outlier; the+        // robust solver should land near the cluster, not the mean.+        let mut beacons = Vec::new();+        for (lat, lon) in [+            (37.7750, -122.4195),+            (37.7748, -122.4193),+            (37.7750, -122.4193),+            (37.7748, -122.4195),+        ] {+            beacons.extend_from_slice(&[lat, lon, 15.0]);+        }+        beacons.extend_from_slice(&[38.5000, -121.5000, 15.0]);+        let [lat, lon, _] = estimate_lat_lon(&beacons).expect("estimate");+        assert!((lat - 37.7749).abs() < 0.002, "lat {lat}");+        assert!((lon - -122.4194).abs() < 0.002, "lon {lon}");+    }++    #[test]+    fn leading_nan_beacon_does_not_poison_reference() {+        let mut beacons = vec![f64::NAN, f64::NAN, f64::NAN];+        beacons.extend_from_slice(&[51.5074, -0.1278, 25.0].repeat(4));+        let [lat, lon, _] = estimate_lat_lon(&beacons).expect("estimate");+        assert!((lat - 51.5074).abs() < 0.001, "lat {lat}");+        assert!((lon - -0.1278).abs() < 0.001, "lon {lon}");+    }++    #[test]+    fn tiny_accuracy_is_clamped_not_zero_weight() {+        // acc = 0 would give six_sigma_squared = 0 and an infinitely+        // confident beacon; the clamp keeps the estimate finite and sane.+        let beacons = [40.7128, -74.0060, 0.0].repeat(4);+        let [lat, lon, acc] = estimate_lat_lon(&beacons).expect("estimate");+        assert!((lat - 40.7128).abs() < 0.001);+        assert!((lon - -74.0060).abs() < 0.001);+        assert!(acc.is_finite());+    }+}+ /// `estimatePosition(beacons)`. `beacons` is interleaved /// `[lat0,lon0,acc0,lat1,lon1,acc1,...]` (degrees, degrees, metres); returns a /// 3-element `[lat, lon, accuracyMeters]` array, or null when there are no
networklocation/src/main/rust/src/lib.rs
diff --git a/networklocation/src/main/rust/src/lib.rs b/networklocation/src/main/rust/src/lib.rsindex 242d0be179..4ca44bfdbb 100644--- a/networklocation/src/main/rust/src/lib.rs+++ b/networklocation/src/main/rust/src/lib.rs@@ -372,3 +372,58 @@ mod tests {         assert!(average_delta.z.six_sigma_squared < 100.0);     } }++#[cfg(test)]+mod solver_tests {+    use super::*;+    use crate::coordinate::Coordinate;++    fn beacon(x: f64, y: f64, z: f64, distance: f64, var: f64) -> Measurement {+        Measurement {+            position: Position {+                x: Coordinate::new_real(x, var),+                y: Coordinate::new_real(y, var),+                z: Coordinate::new_real(z, var),+            },+            distance,+            weight: 0.0,+        }+    }++    #[test]+    fn empty_measurements_give_no_estimate() {+        assert!(estimate_position(&[]).is_none());+    }++    #[test]+    fn symmetric_beacons_estimate_the_center() {+        // Four beacons on a circle around the origin, each exactly 100 m+        // from it: the origin is the unique consistent position.+        let measurements = [+            beacon(100.0, 0.0, 0.0, 100.0, 100.0),+            beacon(-100.0, 0.0, 0.0, 100.0, 100.0),+            beacon(0.0, 100.0, 0.0, 100.0, 100.0),+            beacon(0.0, -100.0, 0.0, 100.0, 100.0),+        ];+        let est = estimate_position(&measurements).expect("estimate");+        assert_eq!(est.inliers_size, 4);+        assert!(est.position.x.value.abs() < 10.0, "x {}", est.position.x.value);+        assert!(est.position.y.value.abs() < 10.0, "y {}", est.position.y.value);+    }++    #[test]+    fn three_consistent_beacons_estimate_the_center() {+        // min_inliers scales with the input (min(len, 4)), so a consistent+        // triple is enough; the 4-inlier floor only binds on larger inputs+        // (covered by `tests::not_enough_inliers`).+        let measurements = [+            beacon(100.0, 0.0, 0.0, 100.0, 100.0),+            beacon(-100.0, 0.0, 0.0, 100.0, 100.0),+            beacon(0.0, 100.0, 0.0, 100.0, 100.0),+        ];+        let est = estimate_position(&measurements).expect("estimate");+        assert_eq!(est.inliers_size, 3);+        assert!(est.position.x.value.abs() < 10.0, "x {}", est.position.x.value);+        assert!(est.position.y.value.abs() < 10.0, "y {}", est.position.y.value);+    }+}
networklocation/src/main/rust/src/mmap.rs
diff --git a/networklocation/src/main/rust/src/mmap.rs b/networklocation/src/main/rust/src/mmap.rsindex f9bea640f1..2cdf8c4126 100644--- a/networklocation/src/main/rust/src/mmap.rs+++ b/networklocation/src/main/rust/src/mmap.rs@@ -99,3 +99,40 @@ impl Drop for Map {         unsafe { libc::munmap(self.addr, self.len) };     } }++#[cfg(test)]+mod tests {+    use super::*;+    use std::io::Write;++    fn temp_file(bytes: &[u8]) -> (std::path::PathBuf, File) {+        let path = std::env::temp_dir().join(format!("mmap-test-{}-{:?}", std::process::id(), bytes.len()));+        let mut f = File::create(&path).unwrap();+        f.write_all(bytes).unwrap();+        f.sync_all().unwrap();+        let reopened = File::open(&path).unwrap();+        (path, reopened)+    }++    #[test]+    fn maps_whole_file_and_offset_region() {+        let data: Vec<u8> = (0u8..=255).collect();+        let (path, file) = temp_file(&data);+        let whole = Map::new(&file, 0, data.len()).expect("whole map");+        assert_eq!(whole.as_slice(), &data[..]);+        let tail = Map::new(&file, 100, 56).expect("offset map");+        assert_eq!(tail.as_slice(), &data[100..156]);+        // Unaligned offset exercises the page-slack path on unix.+        let odd = Map::new(&file, 7, 13).expect("unaligned map");+        assert_eq!(odd.as_slice(), &data[7..20]);+        drop((whole, tail, odd));+        let _ = std::fs::remove_file(path);+    }++    #[test]+    fn zero_length_and_beyond_eof_are_rejected() {+        let (path, file) = temp_file(&[1, 2, 3, 4]);+        assert!(Map::new(&file, 0, 0).is_none());+        let _ = std::fs::remove_file(path);+    }+}
networklocation/src/main/rust/src/multilateration.rs
diff --git a/networklocation/src/main/rust/src/multilateration.rs b/networklocation/src/main/rust/src/multilateration.rsindex 92d489cb0f..e9a709e9b9 100644--- a/networklocation/src/main/rust/src/multilateration.rs+++ b/networklocation/src/main/rust/src/multilateration.rs@@ -28,7 +28,9 @@ pub fn multilateration(         * six_sigma_squared_estimation_iterations_per_point;     let mut previous_estimated_position = estimated_position; -    let iterations_per_phase = iterations / 3;+    // At least one iteration per phase: with `iterations < 3` this would be 0+    // and `(iterations_per_phase * 3) - 1` underflows below.+    let iterations_per_phase = (iterations / 3).max(1);     // Make sure we don't have any extra iterations.     let iterations = (iterations_per_phase * 3) + six_sigma_squared_estimation_iterations; @@ -409,3 +411,50 @@ mod tests {         assert_eq!(expected.x.six_sigma_squared, result.x.six_sigma_squared)     } }++#[cfg(test)]+mod extra_tests {+    use crate::{+        coordinate::Coordinate, measurement::Measurement, multilateration::multilateration,+        position::Position,+    };++    fn at(x: f64, distance: f64) -> Measurement {+        Measurement {+            position: Position {+                x: Coordinate::new_real(x, 1.0),+                ..Default::default()+            },+            distance,+            weight: 0.0,+        }+    }++    #[test]+    fn empty_measurements_return_fake_position_without_panicking() {+        let result = multilateration(&mut [], None, 50);+        assert_eq!(result.number_of_real(), 0);+        assert!(result.x.value.is_finite());+    }++    #[test]+    fn zero_iterations_still_returns_finite_position() {+        let mut m = vec![at(0.0, 1.0), at(10.0, 1.0)];+        let result = multilateration(&mut m, None, 0);+        assert!(result.x.value.is_finite());+        assert!(result.x.six_sigma_squared.is_finite());+    }++    #[test]+    fn explicit_initial_guess_is_respected_when_consistent() {+        // Beacon at x=10 reporting distance 3: positions 7 and 13 both fit;+        // starting from 7 must not be dragged across the beacon.+        let mut m = vec![at(10.0, 3.0)];+        let guess = Position {+            x: Coordinate::new_real(7.0, 1.0),+            ..Default::default()+        };+        let result = multilateration(&mut m, Some(guess), 50);+        assert!((result.x.value - 7.0).abs() < 2.0, "x {}", result.x.value);+    }+}
networklocation/src/main/rust/src/position.rs
diff --git a/networklocation/src/main/rust/src/position.rs b/networklocation/src/main/rust/src/position.rsindex 2a106d52a1..c92d2c267f 100644--- a/networklocation/src/main/rust/src/position.rs+++ b/networklocation/src/main/rust/src/position.rs@@ -30,6 +30,9 @@ impl Default for Position { impl Position {     /// Gets the average position.     pub fn average(positions: &[Position]) -> Self {+        if positions.is_empty() {+            return Self::default();+        }         let positions_len = positions.len() as f64;          Position {@@ -58,3 +61,63 @@ impl Position {         u8::from(self.x.real) + u8::from(self.y.real) + u8::from(self.z.real)     } }++#[cfg(test)]+mod tests {+    use super::*;++    fn real(x: f64, y: f64, z: f64, s: f64) -> Position {+        Position {+            x: Coordinate::new_real(x, s),+            y: Coordinate::new_real(y, s),+            z: Coordinate::new_real(z, s),+        }+    }++    #[test]+    fn default_is_all_fake() {+        let p = Position::default();+        assert!(!p.is_all_real());+        assert_eq!(p.number_of_real(), 0);+        assert_eq!((p.x.value, p.y.value, p.z.value), (0.0, 0.0, 0.0));+    }++    #[test]+    fn real_counts() {+        assert_eq!(real(1.0, 2.0, 3.0, 1.0).number_of_real(), 3);+        assert!(real(1.0, 2.0, 3.0, 1.0).is_all_real());+        let mut p = real(1.0, 2.0, 3.0, 1.0);+        p.z = Coordinate::new_fake();+        assert_eq!(p.number_of_real(), 2);+        assert!(!p.is_all_real());+        p.x = Coordinate::new_fake();+        assert_eq!(p.number_of_real(), 1);+    }++    #[test]+    fn average_of_two_positions() {+        let avg = Position::average(&[real(0.0, 10.0, -4.0, 4.0), real(10.0, 20.0, 4.0, 8.0)]);+        assert_eq!((avg.x.value, avg.y.value, avg.z.value), (5.0, 15.0, 0.0));+        assert_eq!(avg.x.six_sigma_squared, 6.0);+        assert!(avg.is_all_real());+    }++    #[test]+    fn average_of_single_is_identity() {+        let p = real(3.0, -7.0, 11.0, 25.0);+        let avg = Position::average(&[p]);+        assert_eq!((avg.x.value, avg.y.value, avg.z.value), (3.0, -7.0, 11.0));+        assert_eq!(avg.y.six_sigma_squared, 25.0);+    }++    #[test]+    fn average_of_empty_is_fake_not_nan() {+        // The mean of no positions must not poison downstream math with NaN;+        // the honest answer is the all-fake default.+        let avg = Position::average(&[]);+        assert!(!avg.is_all_real());+        assert_eq!(avg.number_of_real(), 0);+        assert!(avg.x.value.is_finite() && avg.y.value.is_finite() && avg.z.value.is_finite());+        assert_eq!((avg.x.value, avg.y.value, avg.z.value), (0.0, 0.0, 0.0));+    }+}
networklocation/src/main/rust/src/wpsdb.rs
diff --git a/networklocation/src/main/rust/src/wpsdb.rs b/networklocation/src/main/rust/src/wpsdb.rsindex 7880a53cd0..533b0a47be 100644--- a/networklocation/src/main/rust/src/wpsdb.rs+++ b/networklocation/src/main/rust/src/wpsdb.rs@@ -433,4 +433,8 @@ pub extern "system" fn Java_com_vayunmathur_networklocation_WpsStoreNative_open< }  include!("wpsdb_part1.rs");-include!("wpsdb_part2.rs");\ No newline at end of file+include!("wpsdb_part2.rs");++#[cfg(test)]+#[path = "wpsdb_tests.rs"]+mod wpsdb_tests;\ No newline at end of file
networklocation/src/main/rust/src/wpsdb_tests.rs
diff --git a/networklocation/src/main/rust/src/wpsdb_tests.rs b/networklocation/src/main/rust/src/wpsdb_tests.rsnew file mode 100644index 0000000000..fab2046288--- /dev/null+++ b/networklocation/src/main/rust/src/wpsdb_tests.rs@@ -0,0 +1,78 @@+//! Bit-level tests for the WPSDB payload codec. The store round-trip tests in+//! `wpsdb_part2.rs` cover the reader end to end; these pin `extract_bits`+//! directly, including unaligned and 64-bit-wide reads that a corrupt store+//! could otherwise turn into a panic or a silent mis-decode.++use super::*;++#[test]+fn extract_bits_single_byte_fields() {+    let buf = [0b1011_0011u8];+    assert_eq!(extract_bits(&buf, 0, 1), 1);+    assert_eq!(extract_bits(&buf, 1, 1), 1);+    assert_eq!(extract_bits(&buf, 2, 1), 0);+    assert_eq!(extract_bits(&buf, 0, 4), 0b0011);+    assert_eq!(extract_bits(&buf, 4, 4), 0b1011);+    assert_eq!(extract_bits(&buf, 0, 8), 0b1011_0011);+    assert_eq!(extract_bits(&buf, 0, 0), 0);+}++#[test]+fn extract_bits_crosses_byte_boundaries_unaligned() {+    // Value 0b10101011_1100 written LSB-first starting at bit offset 3.+    let mut bits = [0u8; 4];+    let value: u64 = 0b1010_1011_1100;+    for k in 0..12u32 {+        if (value >> k) & 1 == 1 {+            let p = 3 + k as usize;+            bits[p >> 3] |= 1 << (p & 7);+        }+    }+    assert_eq!(extract_bits(&bits, 3, 12), value);+    assert_eq!(extract_bits(&bits, 3, 1), value & 1);+    assert_eq!(extract_bits(&bits, 14, 1), (value >> 11) & 1);+}++#[test]+fn extract_bits_full_width_and_known_pattern() {+    let buf = [0xFFu8, 0x00, 0xA5, 0x5A, 0x12, 0x34, 0x56, 0x78, 0x9A];+    assert_eq!(extract_bits(&buf, 0, 64), 0x7856_3412_5AA5_00FF);+    assert_eq!(extract_bits(&buf, 4, 64), 0xA785_6341_25AA_500F);+    assert_eq!(extract_bits(&buf, 0, 35) & 1, 1);+    // Every all-ones field reads back as all ones.+    assert_eq!(extract_bits(&[0xFFu8; 9], 5, 36), (1u64 << 36) - 1);+    assert_eq!(extract_bits(&[0x00u8; 9], 5, 36), 0);+}++#[test]+fn payload_field_layout_matches_record_codec() {+    // Hand-pack one kind-2 record: lat|lon|acc|alt at 35/36/16/16 bits.+    let lat_u: u64 = (37.77f64 * COORD_SCALE) as u64 + LAT_BIAS as u64;+    let lon_u: u64 = (-122.41f64 * COORD_SCALE) as u64 + LON_BIAS as u64;+    let fields = [+        (lat_u, LAT_BITS),+        (lon_u, LON_BITS),+        (250u64, ACC_BITS),+        ((8848i64 + ALT_BIAS) as u64, ALT_BITS),+    ];+    let total: u32 = fields.iter().map(|f| f.1).sum();+    assert_eq!(total, 103);+    let mut buf = vec![0u8; 13];+    let mut pos = 0u32;+    for &(v, n) in &fields {+        for k in 0..n {+            if (v >> k) & 1 == 1 {+                let p = (pos + k) as usize;+                buf[p >> 3] |= 1 << (p & 7);+            }+        }+        pos += n;+    }+    assert_eq!(extract_bits(&buf, 0, LAT_BITS), lat_u);+    assert_eq!(extract_bits(&buf, LAT_BITS, LON_BITS), lon_u);+    assert_eq!(extract_bits(&buf, LAT_BITS + LON_BITS, ACC_BITS), 250);+    assert_eq!(+        extract_bits(&buf, LAT_BITS + LON_BITS + ACC_BITS, ALT_BITS),+        (8848i64 + ALT_BIAS) as u64+    );+}