rust: apply rustfmt workspace-wide
- Commit
78cf39a4203b0da7d8199d9e0160481efa04e3f9- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-01 18:59 UTC (4 days ago)
- Parents
97d585b
Apply cargo fmt --all under the root rustfmt.toml (max_width 100) to every workspace crate, plus a direct rustfmt pass on library/map/src/main/rust/src/overlay_tests.rs, whose leading blank line cargo fmt --all reported but did not remove. This is formatting only: reflow, import ordering and trailing newlines. String-literal and macro bodies were audited; the only string-adjacent changes are line-continuation reflows and macro argument reflows with identical literal content, and no macro definition changed. Crates covered: all 61 workspace members (875 .rs files), including scripts/maps, scripts/networklocation, third_party/betocore, third_party/om-file-format-sys, library/tilecodec, library/jni-http and library/vision. No standalone non-workspace crate exists in this checkout (Cargo.toml enumeration outside target/build found only workspace members), so there was nothing extra to format in-dir. Verified with cargo fmt --all -- --check (clean), cargo check --offline --workspace --profile fast with WORKSPACE_DIR set (passes except kart_engine, voxels_engine and yuu_avatar, which fail only on missing Gradle-generated build/spirv/*.spv files, a pre-existing prerequisite), the same check excluding those three (clean), and cargo test --offline --profile fast for gtfs_ingest, tile_build and youpipe_extractor (391 passed, 0 failed). cargo check --locked fails before compiling on a pre-existing Cargo.lock drift that this change does not touch; it is reported, not fixed.
Diff
appstore/src/main/rust/src/jni_bridge.rs
diff --git a/appstore/src/main/rust/src/jni_bridge.rs b/appstore/src/main/rust/src/jni_bridge.rsindex f7f70abd92..d07f4c4c42 100644--- a/appstore/src/main/rust/src/jni_bridge.rs+++ b/appstore/src/main/rust/src/jni_bridge.rs@@ -7,14 +7,24 @@ use jni::objects::{JByteArray, JClass}; use jni::sys::jboolean; use jni::{Env, EnvUnowned}; -fn bytes_in(env: &Env, arr: &JByteArray) -> Option<Vec<u8>> { env.convert_byte_array(arr).ok() }+fn bytes_in(env: &Env, arr: &JByteArray) -> Option<Vec<u8>> {+ env.convert_byte_array(arr).ok()+} /// Returns `1` only for a valid signature; `0` for everything else, including /// a failed array read. Never throws — the Kotlin caller treats `false` as /// "not verified", so a thrown exception would only turn a clean rejection /// into a crash. #[no_mangle]-pub extern "system" fn Java_com_vayunmathur_appstore_data_accrescent_SignifyNative_nativeVerify<'l>(mut env: EnvUnowned<'l>, _class: JClass<'l>, pubkey: JByteArray<'l>, msg: JByteArray<'l>, sig: JByteArray<'l>) -> jboolean {+pub extern "system" fn Java_com_vayunmathur_appstore_data_accrescent_SignifyNative_nativeVerify<+ 'l,+>(+ mut env: EnvUnowned<'l>,+ _class: JClass<'l>,+ pubkey: JByteArray<'l>,+ msg: JByteArray<'l>,+ sig: JByteArray<'l>,+) -> jboolean { env.with_env(|env| -> jni::errors::Result<jboolean> { Ok(verify_inputs(bytes_in(env, &pubkey), bytes_in(env, &msg), bytes_in(env, &sig))) })
appstore/src/main/rust/src/lib.rs
diff --git a/appstore/src/main/rust/src/lib.rs b/appstore/src/main/rust/src/lib.rsindex b6d1468819..9d8bfd6149 100644--- a/appstore/src/main/rust/src/lib.rs+++ b/appstore/src/main/rust/src/lib.rs@@ -180,11 +180,7 @@ pub fn verify_signify(pubkey_b64: &str, signature: &str, msg: &[u8]) -> bool { /// The testable core of the JNI bridge: `false` unless all three inputs /// are present and [`verify`] accepts them.-pub fn verify_inputs(- pubkey: Option<Vec<u8>>,- msg: Option<Vec<u8>>,- sig: Option<Vec<u8>>,-) -> bool {+pub fn verify_inputs(pubkey: Option<Vec<u8>>, msg: Option<Vec<u8>>, sig: Option<Vec<u8>>) -> bool { match (pubkey, msg, sig) { (Some(pubkey), Some(msg), Some(sig)) => verify(&pubkey, &msg, &sig), _ => false,
appstore/src/main/rust/src/signify_tests.rs
diff --git a/appstore/src/main/rust/src/signify_tests.rs b/appstore/src/main/rust/src/signify_tests.rsindex 6b43d92f56..f4fdf5e768 100644--- a/appstore/src/main/rust/src/signify_tests.rs+++ b/appstore/src/main/rust/src/signify_tests.rs@@ -68,11 +68,7 @@ fn round_trip_fresh_key_verifies_through_every_api() { assert!(verify_signify(&pubkey_b64, &STANDARD.encode(&sig_blob), &msg)); assert!(verify_signify_blobs(&pubkey_blob, &sig_blob, &msg)); assert!(verify(&verifying, &msg, &signature));- assert!(verify_inputs(- Some(verifying.to_vec()),- Some(msg.clone()),- Some(signature.to_vec()),- ));+ assert!(verify_inputs(Some(verifying.to_vec()), Some(msg.clone()), Some(signature.to_vec()),)); assert_eq!(decode_pubkey(&pubkey_b64), Some(verifying)); assert_eq!(sig_file_signature(&sig_file), Some(signature)); assert_eq!(extract_pubkey_key(&pubkey_blob), Some(verifying));@@ -118,7 +114,10 @@ fn mismatched_algo_and_key_num_still_verify_like_kotlin() { for key_num in [KEY_NUM, other_num] { let key_blob = blob(algo, key_num, &verifying); let sig_blob = blob(algo, key_num, &signature);- assert!(verify_signify_blobs(&key_blob, &sig_blob, msg), "algo {algo:?} num {key_num:?}");+ assert!(+ verify_signify_blobs(&key_blob, &sig_blob, msg),+ "algo {algo:?} num {key_num:?}"+ ); } } // Key and signature framing need not agree with each other either.@@ -261,7 +260,8 @@ fn sig_file_takes_last_blob_line() { let (pubkey_b64, sig_file_a, msg_a) = fixture(17, b"first message"); let (_, sig_file_b, msg_b) = { let (signing, _) = fresh_key(17);- let sig_b64 = STANDARD.encode(blob(ALGO, KEY_NUM, &signing.sign(b"second message").to_bytes()));+ let sig_b64 =+ STANDARD.encode(blob(ALGO, KEY_NUM, &signing.sign(b"second message").to_bytes())); ((), format!("untrusted comment: x\n{sig_b64}\n"), b"second message".to_vec()) }; let two_blobs = format!("{}{}", sig_file_a, sig_file_b.lines().nth(1).unwrap());
camera/src/main/rust/src/avif.rs
diff --git a/camera/src/main/rust/src/avif.rs b/camera/src/main/rust/src/avif.rsindex 892111d9de..98bed5b49b 100644--- a/camera/src/main/rust/src/avif.rs+++ b/camera/src/main/rust/src/avif.rs@@ -41,7 +41,13 @@ const SPEED_MAX: u8 = 10; /// /// Never panics on untrusted sizes: dimensions are validated before any /// allocation sized by them.-pub fn encode_avif(rgba: &[u8], width: usize, height: usize, quality: f32, speed: u8) -> Option<Vec<u8>> {+pub fn encode_avif(+ rgba: &[u8],+ width: usize,+ height: usize,+ quality: f32,+ speed: u8,+) -> Option<Vec<u8>> { encode_avif_with_exif(rgba, width, height, quality, speed, None) } @@ -94,9 +100,7 @@ pub fn encode_avif_with_exif( // default (`None`) silently inherits whatever size the global rayon // pool happened to be created with. Pinning it to the device's // parallelism makes the tile/thread split deterministic on every call.- let threads = std::thread::available_parallelism()- .map(|n| n.get())- .unwrap_or(1);+ let threads = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1); let mut encoder = Encoder::new() .with_quality(quality.clamp(QUALITY_MIN, QUALITY_MAX)) .with_speed(speed.clamp(SPEED_MIN, SPEED_MAX))@@ -128,7 +132,9 @@ pub fn avif_dimensions(bytes: &[u8]) -> Option<(u32, u32)> { let mut out = Vec::new(); let mut off = 0usize; while off + 8 <= bytes.len() {- let size = u32::from_be_bytes([bytes[off], bytes[off + 1], bytes[off + 2], bytes[off + 3]]) as usize;+ let size =+ u32::from_be_bytes([bytes[off], bytes[off + 1], bytes[off + 2], bytes[off + 3]])+ as usize; if size < 8 || off + size > bytes.len() { break; }@@ -271,7 +277,14 @@ pub extern "system" fn Java_com_vayunmathur_camera_platform_StitchNative_encodeA }; let exif_ref = if exif_bytes.is_empty() { None } else { Some(exif_bytes.as_slice()) }; let encoded = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {- encode_avif_with_exif(&bytes, width as usize, height as usize, quality, speed.clamp(1, 10) as u8, exif_ref)+ encode_avif_with_exif(+ &bytes,+ width as usize,+ height as usize,+ quality,+ speed.clamp(1, 10) as u8,+ exif_ref,+ ) })) .unwrap_or(None); match encoded {
camera/src/main/rust/src/avif_mux.rs
diff --git a/camera/src/main/rust/src/avif_mux.rs b/camera/src/main/rust/src/avif_mux.rsindex 8b2b26a653..146a39ec47 100644--- a/camera/src/main/rust/src/avif_mux.rs+++ b/camera/src/main/rust/src/avif_mux.rs@@ -15,12 +15,10 @@ pub(crate) fn parse_boxes(bytes: &[u8], span: std::ops::Range<usize>) -> Vec<Box let mut out = Vec::new(); let mut off = span.start; while off + 8 <= span.end && off + 8 <= bytes.len() {- let size32 = u32::from_be_bytes([bytes[off], bytes[off + 1], bytes[off + 2], bytes[off + 3]]);+ let size32 =+ u32::from_be_bytes([bytes[off], bytes[off + 1], bytes[off + 2], bytes[off + 3]]); let (size, header) = if size32 == 1 && off + 16 <= bytes.len() {- (- u64::from_be_bytes(bytes[off + 8..off + 16].try_into().unwrap()) as usize,- 16usize,- )+ (u64::from_be_bytes(bytes[off + 8..off + 16].try_into().unwrap()) as usize, 16usize) } else if size32 == 0 { (span.end.saturating_sub(off), 8usize) } else {@@ -83,19 +81,31 @@ pub fn mux_avif_exif(avif: &[u8], exif: &[u8]) -> Option<Vec<u8>> { let pitm = children.iter().find(|b| &b.typ == b"pitm")?; let pitm_version = *avif.get(pitm.payload.start)?; let primary_id: u32 = if pitm_version == 1 {- u32::from_be_bytes(avif.get(pitm.payload.start + 4..pitm.payload.start + 8)?.try_into().ok()?)+ u32::from_be_bytes(+ avif.get(pitm.payload.start + 4..pitm.payload.start + 8)?.try_into().ok()?,+ ) } else {- u16::from_be_bytes(avif.get(pitm.payload.start + 4..pitm.payload.start + 6)?.try_into().ok()?) as u32+ u16::from_be_bytes(+ avif.get(pitm.payload.start + 4..pitm.payload.start + 6)?.try_into().ok()?,+ ) as u32 }; // `iinf`: bump the entry count and append an Exif `infe` (v2). let iinf = children.iter().find(|b| &b.typ == b"iinf")?; let iinf_version = *avif.get(iinf.payload.start)?;- let (count_len, entry_count) = if iinf_version == 1 { (4usize, {- u32::from_be_bytes(avif.get(iinf.payload.start + 4..iinf.payload.start + 8)?.try_into().ok()?) as usize- }) } else { (2usize, {- u16::from_be_bytes(avif.get(iinf.payload.start + 4..iinf.payload.start + 6)?.try_into().ok()?) as usize- }) };+ let (count_len, entry_count) = if iinf_version == 1 {+ (4usize, {+ u32::from_be_bytes(+ avif.get(iinf.payload.start + 4..iinf.payload.start + 8)?.try_into().ok()?,+ ) as usize+ })+ } else {+ (2usize, {+ u16::from_be_bytes(+ avif.get(iinf.payload.start + 4..iinf.payload.start + 6)?.try_into().ok()?,+ ) as usize+ })+ }; let infes = parse_boxes(avif, (iinf.payload.start + 4 + count_len)..iinf.payload.end); let mut max_id: u32 = primary_id; for infe in &infes {@@ -198,11 +208,8 @@ pub fn mux_avif_exif(avif: &[u8], exif: &[u8]) -> Option<Vec<u8>> { iloc_payload.push(0); // base_offset_size=0, index_size=0 iloc_payload.extend_from_slice(&((iloc_items.len() + 1) as u16).to_be_bytes()); let shift = |offset: u64| -> Option<u32> {- let adjusted = if offset as usize >= meta.payload.end {- offset as i64 + delta- } else {- offset as i64- };+ let adjusted =+ if offset as usize >= meta.payload.end { offset as i64 + delta } else { offset as i64 }; u32::try_from(adjusted).ok() }; for item in &iloc_items {@@ -284,11 +291,8 @@ fn parse_iloc(bytes: &[u8], iloc: &BoxSpan) -> Option<Vec<IlocItem>> { let mut items = Vec::with_capacity(item_count); for _ in 0..item_count { let item_id = read_uint(bytes, &mut pos, 2)? as u32;- let construction = if version == 1 || version == 2 {- read_uint(bytes, &mut pos, 2)? as u16- } else {- 0- };+ let construction =+ if version == 1 || version == 2 { read_uint(bytes, &mut pos, 2)? as u16 } else { 0 }; read_uint(bytes, &mut pos, 2)?; // data_reference_index let base_offset = read_uint(bytes, &mut pos, base_offset_size)?; let extent_count = read_uint(bytes, &mut pos, 2)? as usize;@@ -340,4 +344,3 @@ pub extern "system" fn Java_com_vayunmathur_camera_platform_StitchNative_muxAvif }) .resolve::<jni::errors::LogErrorAndDefault>() }-
camera/src/main/rust/src/avif_tests.rs
diff --git a/camera/src/main/rust/src/avif_tests.rs b/camera/src/main/rust/src/avif_tests.rsindex 0f4f9df710..c68a972162 100644--- a/camera/src/main/rust/src/avif_tests.rs+++ b/camera/src/main/rust/src/avif_tests.rs@@ -1,4 +1,7 @@-use super::{avif_dimensions, avif_exif_item, avif_exif_tiff, encode_avif, encode_avif_with_exif, has_avif_magic};+use super::{+ avif_dimensions, avif_exif_item, avif_exif_tiff, encode_avif, encode_avif_with_exif,+ has_avif_magic,+}; use crate::avif_mux::mux_avif_exif; /// Minimal little-endian TIFF: IFD0 with one Orientation(=1) entry,@@ -22,12 +25,7 @@ fn gradient(width: usize, height: usize) -> Vec<u8> { let mut px = Vec::with_capacity(width * height * 4); for y in 0..height { for x in 0..width {- px.extend_from_slice(&[- (x % 256) as u8,- (y % 256) as u8,- ((x + y) % 256) as u8,- 255,- ]);+ px.extend_from_slice(&[(x % 256) as u8, (y % 256) as u8, ((x + y) % 256) as u8, 255]); } } px@@ -157,10 +155,8 @@ fn bench_12mp_encode_time() { assert!(has_avif_magic(&bytes)); } // Thread scaling at the production-adjacent speeds, via ravif directly.- let pixels: Vec<ravif::RGBA8> = rgba- .chunks_exact(4)- .map(|p| ravif::RGBA8::new(p[0], p[1], p[2], p[3]))- .collect();+ let pixels: Vec<ravif::RGBA8> =+ rgba.chunks_exact(4).map(|p| ravif::RGBA8::new(p[0], p[1], p[2], p[3])).collect(); for speed in [8u8, 10] { for threads in [Some(1usize), Some(4), Some(8), Some(16)] { let img = ravif::Img::new(pixels.as_slice(), w, h);
camera/src/main/rust/src/blend.rs
diff --git a/camera/src/main/rust/src/blend.rs b/camera/src/main/rust/src/blend.rsindex d70da862b3..d3d9df5ecb 100644--- a/camera/src/main/rust/src/blend.rs+++ b/camera/src/main/rust/src/blend.rs@@ -293,7 +293,8 @@ fn pyr_up_3ch(src: &Img3, dst_w: usize, dst_h: usize) -> Img3 { let y1 = (y0 + 1).min(eh - 1); let ay = fy - y0 as f32; for x in 0..dst_w {- let fx = ((x as f32 + 0.5) * ew as f32 / dst_w as f32 - 0.5).clamp(0.0, (ew - 1) as f32);+ let fx =+ ((x as f32 + 0.5) * ew as f32 / dst_w as f32 - 0.5).clamp(0.0, (ew - 1) as f32); let x0 = fx.floor() as usize; let x1 = (x0 + 1).min(ew - 1); let ax = fx - x0 as f32;@@ -312,7 +313,15 @@ fn pyr_up_3ch(src: &Img3, dst_w: usize, dst_h: usize) -> Img3 { // Feather fallback (original) – kept and used if multiband fails // --------------------------------------------------------------------------- -fn feather_blend(tiles: &[WarpedTile], masks: &[Vec<u8>], gain_maps: &[Vec<f32>], gx0: i32, gy0: i32, cw: usize, ch: usize) -> Option<Rgba> {+fn feather_blend(+ tiles: &[WarpedTile],+ masks: &[Vec<u8>],+ gain_maps: &[Vec<f32>],+ gx0: i32,+ gy0: i32,+ cw: usize,+ ch: usize,+) -> Option<Rgba> { let num = tiles.len(); let mut acc = vec![0f32; cw * ch * 3]; let mut accw = vec![0f32; cw * ch];
camera/src/main/rust/src/blend_tests.rs
diff --git a/camera/src/main/rust/src/blend_tests.rs b/camera/src/main/rust/src/blend_tests.rsindex 0dc2230982..0e5822f3bf 100644--- a/camera/src/main/rust/src/blend_tests.rs+++ b/camera/src/main/rust/src/blend_tests.rs@@ -190,10 +190,8 @@ fn multiband_blend_single_tile_returns_its_colours() { #[test] fn multiband_blend_two_identical_overlapping_tiles_stays_uniform() {- let tiles = vec![- tile(16, 16, 0, 0, [120, 120, 120, 255]),- tile(16, 16, 8, 0, [120, 120, 120, 255]),- ];+ let tiles =+ vec![tile(16, 16, 0, 0, [120, 120, 120, 255]), tile(16, 16, 8, 0, [120, 120, 120, 255])]; let masks: Vec<Vec<u8>> = tiles.iter().map(|t| vec![1u8; t.img.w * t.img.h]).collect(); let gains: Vec<Vec<f32>> = tiles.iter().map(|t| vec![1.0f32; t.img.w * t.img.h]).collect(); let out = multiband_blend(&tiles, &masks, &gains).expect("blend");
camera/src/main/rust/src/bundle.rs
diff --git a/camera/src/main/rust/src/bundle.rs b/camera/src/main/rust/src/bundle.rsindex 0c1a730f7e..3dc0580854 100644--- a/camera/src/main/rust/src/bundle.rs+++ b/camera/src/main/rust/src/bundle.rs@@ -7,8 +7,8 @@ use crate::camera::{rodrigues_to_mat, CameraParams}; use crate::geometry::Pt;-use crate::matching::MatchInfo; use crate::linalg::{DMatrix, DVector, Matrix3, Vector3};+use crate::matching::MatchInfo; /// BundleAdjusterRay conf_thresh matches stitch.rs CONF_THRESH – must be 0.3 not 1.0, /// otherwise bundle drops all edges while biggest_component keeps them.@@ -25,11 +25,7 @@ struct Edge { } fn k_inv(focal: f64, ppx: f64, ppy: f64) -> Matrix3<f64> {- Matrix3::new(- 1.0 / focal, 0.0, -ppx / focal,- 0.0, 1.0 / focal, -ppy / focal,- 0.0, 0.0, 1.0,- )+ Matrix3::new(1.0 / focal, 0.0, -ppx / focal, 0.0, 1.0 / focal, -ppy / focal, 0.0, 0.0, 1.0) } /// A camera perturbed by a single tangent parameter (0 = focal, 1..3 = ω axis).@@ -123,11 +119,15 @@ pub fn bundle_adjust(cams: &mut Vec<CameraParams>, matches: &[MatchInfo]) { for c in 0..8 { let (pj, is_i) = (c % 4, c < 4); let (rp, rm) = if is_i {- (edge_res(&perturb(ca, pj, STEP), cb, &e.corr),- edge_res(&perturb(ca, pj, -STEP), cb, &e.corr))+ (+ edge_res(&perturb(ca, pj, STEP), cb, &e.corr),+ edge_res(&perturb(ca, pj, -STEP), cb, &e.corr),+ ) } else {- (edge_res(ca, &perturb(cb, pj, STEP), &e.corr),- edge_res(ca, &perturb(cb, pj, -STEP), &e.corr))+ (+ edge_res(ca, &perturb(cb, pj, STEP), &e.corr),+ edge_res(ca, &perturb(cb, pj, -STEP), &e.corr),+ ) }; let mut col = vec![0.0f64; m]; for t in 0..m {@@ -136,8 +136,14 @@ pub fn bundle_adjust(cams: &mut Vec<CameraParams>, matches: &[MatchInfo]) { jb.push(col); } let gcol = [- 4 * e.i, 4 * e.i + 1, 4 * e.i + 2, 4 * e.i + 3,- 4 * e.j, 4 * e.j + 1, 4 * e.j + 2, 4 * e.j + 3,+ 4 * e.i,+ 4 * e.i + 1,+ 4 * e.i + 2,+ 4 * e.i + 3,+ 4 * e.j,+ 4 * e.j + 1,+ 4 * e.j + 2,+ 4 * e.j + 3, ]; let mut jtj = DMatrix::<f64>::zeros(nparams, nparams); let mut jtr = DVector::<f64>::zeros(nparams);
camera/src/main/rust/src/bundle_tests.rs
diff --git a/camera/src/main/rust/src/bundle_tests.rs b/camera/src/main/rust/src/bundle_tests.rsindex 8094eda6e2..7b8f0e499c 100644--- a/camera/src/main/rust/src/bundle_tests.rs+++ b/camera/src/main/rust/src/bundle_tests.rs@@ -2,11 +2,15 @@ //! geodesic increments, and ray residuals; plus bundle_adjust no-op paths. fn mdiff(a: &Matrix3<f64>, b: &Matrix3<f64>) -> f64 { let mut s = 0.0f64;- for r in 0..3 { for c in 0..3 { let d = a[(r, c)] - b[(r, c)]; s += d * d; } }+ for r in 0..3 {+ for c in 0..3 {+ let d = a[(r, c)] - b[(r, c)];+ s += d * d;+ }+ } s.sqrt() } - use super::*; use crate::linalg::Matrix3; @@ -95,7 +99,13 @@ fn edge_res_grows_when_second_point_moves() { let n_same: f64 = same.iter().map(|v| v * v).sum(); let n_moved: f64 = moved.iter().map(|v| v * v).sum(); assert!(n_moved > n_same + 1.0, "moved point must raise residual ({n_moved} vs {n_same})");- assert_eq!(total_cost(&[c.clone(), c.clone()], &[Edge { i: 0, j: 1, corr: vec![((1.0f32, 1.0f32), (1.0, 1.0))] }]), 0.0);+ assert_eq!(+ total_cost(+ &[c.clone(), c.clone()],+ &[Edge { i: 0, j: 1, corr: vec![((1.0f32, 1.0f32), (1.0, 1.0))] }]+ ),+ 0.0+ ); } #[test]
camera/src/main/rust/src/estimator.rs
diff --git a/camera/src/main/rust/src/estimator.rs b/camera/src/main/rust/src/estimator.rsindex d7fc70d689..cd93a5ae26 100644--- a/camera/src/main/rust/src/estimator.rs+++ b/camera/src/main/rust/src/estimator.rs@@ -4,9 +4,9 @@ //! at the central image, matching OpenCV's findMaxSpanningTree + walkBreadthFirst. use crate::camera::CameraParams;+use crate::linalg::Matrix3; use crate::matching::MatchInfo; use crate::sphere::{estimate_focal_with_prior, k_matrix, orthonormalize};-use crate::linalg::Matrix3; /// `node -> [(neighbour, num_inliers, confidence, H_node->neighbour)]`. type Adjacency = Vec<Vec<(usize, usize, f64, Matrix3<f64>)>>;
camera/src/main/rust/src/estimator_tests.rs
diff --git a/camera/src/main/rust/src/estimator_tests.rs b/camera/src/main/rust/src/estimator_tests.rsindex 949d4f39d5..e619d8cf64 100644--- a/camera/src/main/rust/src/estimator_tests.rs+++ b/camera/src/main/rust/src/estimator_tests.rs@@ -2,11 +2,15 @@ //! matches, checking focal fallback and rotation validity. fn mdiff(a: &Matrix3<f64>, b: &Matrix3<f64>) -> f64 { let mut s = 0.0f64;- for r in 0..3 { for c in 0..3 { let d = a[(r, c)] - b[(r, c)]; s += d * d; } }+ for r in 0..3 {+ for c in 0..3 {+ let d = a[(r, c)] - b[(r, c)];+ s += d * d;+ }+ } s.sqrt() } - use super::*; use crate::linalg::Matrix3; @@ -53,11 +57,15 @@ fn estimate_cameras_disconnected_images_all_identity() { fn estimate_cameras_identity_homography_chain_keeps_identity() { // Identity homographies carry no focal, so the fallback focal applies // and CalcRotation yields identity relative rotations.- let matches = vec![mi(0, 1, Matrix3::identity(), 50, 0.9), mi(1, 2, Matrix3::identity(), 40, 0.9)];+ let matches =+ vec![mi(0, 1, Matrix3::identity(), 50, 0.9), mi(1, 2, Matrix3::identity(), 40, 0.9)]; let cams = estimate_cameras(3, 640, 480, &matches, None); assert_eq!(cams.len(), 3); for c in &cams {- assert!(approx(mdiff(&(c.r), &(Matrix3::identity())), 0.0, 1e-6), "identity chain must stay identity");+ assert!(+ approx(mdiff(&(c.r), &(Matrix3::identity())), 0.0, 1e-6),+ "identity chain must stay identity"+ ); assert_rotation(&c.r); } }
camera/src/main/rust/src/exposure.rs
diff --git a/camera/src/main/rust/src/exposure.rs b/camera/src/main/rust/src/exposure.rsindex 0c65a87e8a..fd1c81e6ae 100644--- a/camera/src/main/rust/src/exposure.rs+++ b/camera/src/main/rust/src/exposure.rs@@ -6,8 +6,8 @@ //! BlocksCompensator::feedWithStrategy tiles into bl_per_img ceil/size, //! getGainMap CV_32F, smoothing kernel [0.25 0.5 0.25] sepFilter2D iter=2 -use crate::sphere::WarpedTile; use crate::linalg::{DMatrix, DVector};+use crate::sphere::WarpedTile; const ALPHA: f64 = 0.01; const BETA: f64 = 100.0;@@ -182,7 +182,8 @@ pub fn compensate(tiles: &[WarpedTile]) -> Vec<Vec<f32>> { let ti = { let mut t = 0usize; for i in 0..num {- if p >= block_offset[i] && p < block_offset[i] + bl_infos[i].bl_w * bl_infos[i].bl_h {+ if p >= block_offset[i] && p < block_offset[i] + bl_infos[i].bl_w * bl_infos[i].bl_h+ { t = i; break; }
camera/src/main/rust/src/exposure_tests.rs
diff --git a/camera/src/main/rust/src/exposure_tests.rs b/camera/src/main/rust/src/exposure_tests.rsindex 488b4c9f4e..fd204b8055 100644--- a/camera/src/main/rust/src/exposure_tests.rs+++ b/camera/src/main/rust/src/exposure_tests.rs@@ -83,7 +83,12 @@ fn compensate_dark_tile_gets_gain_above_bright_tile() { let tiles = vec![tile(48, 48, 0, 0, 60), tile(48, 48, 24, 0, 180)]; let gains = compensate(&tiles); let mean = |g: &[f32]| g.iter().sum::<f32>() / g.len() as f32;- assert!(mean(&gains[0]) > mean(&gains[1]), "dark {} vs bright {}", mean(&gains[0]), mean(&gains[1]));+ assert!(+ mean(&gains[0]) > mean(&gains[1]),+ "dark {} vs bright {}",+ mean(&gains[0]),+ mean(&gains[1])+ ); } #[test]
camera/src/main/rust/src/lib.rs
diff --git a/camera/src/main/rust/src/lib.rs b/camera/src/main/rust/src/lib.rsindex 67b0709616..aa169b3651 100644--- a/camera/src/main/rust/src/lib.rs+++ b/camera/src/main/rust/src/lib.rs@@ -8,23 +8,23 @@ pub use vision_core::{camera, features, geometry, imgbuf, linalg}; -mod matching;-mod estimator;+mod avif;+mod avif_mux;+mod blend; mod bundle;-mod wave;-mod warp;-mod sphere;+mod estimator; mod exposure;-mod seam;-mod blend;-mod stitch;+mod luma;+mod matching; mod night;-mod raw_night; #[allow(dead_code)] mod raw_jni;-mod avif;-mod avif_mux;-mod luma;+mod raw_night;+mod seam;+mod sphere;+mod stitch;+mod warp;+mod wave; use imgbuf::Rgba; use std::collections::HashMap;@@ -73,7 +73,7 @@ fn encode_jpeg(img: &Rgba, quality: u8) -> Option<Vec<u8>> { // For minimal deps we vend a simple path using `jpeg_encoder` if available, otherwise // naive baseline that still produces loadable JPEG via `image` replacement path would fail. // We add `jpeg-encoder` as dependency in Cargo.toml (tiny).- use jpeg_encoder::{Encoder, ColorType};+ use jpeg_encoder::{ColorType, Encoder}; let mut rgb = vec![0u8; img.w * img.h * 3]; for i in 0..img.w * img.h { rgb[i * 3] = img.px[i * 4];@@ -205,11 +205,20 @@ mod tests { let peak = (0..out.w).max_by(|&a, &b| colmean[a].total_cmp(&colmean[b])).unwrap(); eprintln!( "streak: peak col {} mean {:.0} vs avg {:.0} (+{:.0})",- peak, colmean[peak], avg, colmean[peak] - avg+ peak,+ colmean[peak],+ avg,+ colmean[peak] - avg ); eprintln!( "inputs {aw}x{ah}; stitched {}x{} in {:?} -> {} KB; black={} ({:.3}%), border_black={}",- out.w, out.h, dt, jpeg.len() / 1024, black, black_pct, border_black+ out.w,+ out.h,+ dt,+ jpeg.len() / 1024,+ black,+ black_pct,+ border_black ); assert!(out.w > 800 && out.h > 800, "degenerate crop: {}x{}", out.w, out.h); assert_eq!(border_black, 0, "black pixels on the border");@@ -249,7 +258,6 @@ mod tests { assert!(gain.is_finite() && (0.5..=2.0).contains(&gain), "bad gain {gain}"); } }- } mod jni_bindings {@@ -349,8 +357,9 @@ mod jni_bindings { }, None => return Ok(null), };- let bytes = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| do_estimate(&session)))- .unwrap_or(None);+ let bytes =+ std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| do_estimate(&session)))+ .unwrap_or(None); if let Some(s) = registry().lock().unwrap().get_mut(&handle) { s.frames = session.frames; s.yaw = session.yaw;@@ -380,7 +389,9 @@ mod jni_bindings { } #[no_mangle]- pub extern "system" fn Java_com_vayunmathur_camera_platform_StitchNative_addNightRgbaFrame<'l>(+ pub extern "system" fn Java_com_vayunmathur_camera_platform_StitchNative_addNightRgbaFrame<+ 'l,+ >( mut env: EnvUnowned<'l>, _class: JClass<'l>, handle: jlong,@@ -453,7 +464,6 @@ mod jni_bindings { night_registry().lock().unwrap().remove(&handle); } - fn run_and_return(env: &mut Env, handle: jlong, panorama: bool) -> jbyteArray { let null = std::ptr::null_mut(); let mut session = match registry().lock().unwrap().get_mut(&handle) {
camera/src/main/rust/src/luma.rs
diff --git a/camera/src/main/rust/src/luma.rs b/camera/src/main/rust/src/luma.rsindex 28bf450254..7ed2743589 100644--- a/camera/src/main/rust/src/luma.rs+++ b/camera/src/main/rust/src/luma.rs@@ -21,10 +21,7 @@ fn readable(len: usize, row_stride: usize, pixel_stride: usize, w: usize, h: usi if w == 0 || h == 0 || row_stride == 0 || pixel_stride == 0 { return false; }- match (h - 1)- .checked_mul(row_stride)- .and_then(|v| v.checked_add((w - 1) * pixel_stride))- {+ match (h - 1).checked_mul(row_stride).and_then(|v| v.checked_add((w - 1) * pixel_stride)) { Some(last) => last < len, None => false, }
camera/src/main/rust/src/matching.rs
diff --git a/camera/src/main/rust/src/matching.rs b/camera/src/main/rust/src/matching.rsindex 95fb71ab4c..a76287b607 100644--- a/camera/src/main/rust/src/matching.rs+++ b/camera/src/main/rust/src/matching.rs@@ -101,7 +101,9 @@ fn match_pair(src: usize, dst: usize, fs: &Features, fd: &Features) -> Option<Ma if num_inliers >= 4 { let a_inl: Vec<Pt> = inl_idx.iter().map(|&k| a_centered[k]).collect(); let b_inl: Vec<Pt> = inl_idx.iter().map(|&k| b_centered[k]).collect();- if let Some((h_refined, _)) = find_homography_ransac(&a_inl, &b_inl, RANSAC_ITERS, RANSAC_THRESH) {+ if let Some((h_refined, _)) =+ find_homography_ransac(&a_inl, &b_inl, RANSAC_ITERS, RANSAC_THRESH)+ { if h_refined.determinant().abs() >= f64::EPSILON { h = h_refined; }@@ -113,14 +115,7 @@ fn match_pair(src: usize, dst: usize, fs: &Features, fd: &Features) -> Option<Ma // Inliers in original coords for downstream bundle adjuster (which centers via K) let inliers: Vec<(Pt, Pt)> = inl_idx.iter().map(|&k| (a_orig[k], b_orig[k])).collect(); - Some(MatchInfo {- src,- dst,- h,- inliers,- confidence,- num_inliers,- })+ Some(MatchInfo { src, dst, h, inliers, confidence, num_inliers }) } /// Angular separation (deg) between two frames' gyro orientations: the true@@ -160,10 +155,7 @@ pub fn match_all(feats: &[Features], yaw: &[f32], pitch: &[f32], max_angle: f32) } } }- pairs- .iter()- .filter_map(|&(i, j)| match_pair(i, j, &feats[i], &feats[j]))- .collect()+ pairs.iter().filter_map(|&(i, j)| match_pair(i, j, &feats[i], &feats[j])).collect() } /// leaveBiggestComponent: keep the largest set of images connected by matches
camera/src/main/rust/src/matching_tests.rs
diff --git a/camera/src/main/rust/src/matching_tests.rs b/camera/src/main/rust/src/matching_tests.rsindex 110f8f31d7..9a85ecfeaf 100644--- a/camera/src/main/rust/src/matching_tests.rs+++ b/camera/src/main/rust/src/matching_tests.rs@@ -109,7 +109,12 @@ fn match_all_gyro_gate_excludes_distant_pairs() { let desc = vec![[7u8; 32]; 8]; let mk = |desc: Vec<[u8; 32]>| Features { kps: (0..8)- .map(|i| KeyPoint { x: 10.0 + (i % 4) as f32 * 20.0, y: 10.0 + (i / 4) as f32 * 20.0, angle: 0.0, score: 1.0 })+ .map(|i| KeyPoint {+ x: 10.0 + (i % 4) as f32 * 20.0,+ y: 10.0 + (i / 4) as f32 * 20.0,+ angle: 0.0,+ score: 1.0,+ }) .collect(), desc, w: 100,
camera/src/main/rust/src/night.rs
diff --git a/camera/src/main/rust/src/night.rs b/camera/src/main/rust/src/night.rsindex 656d6581bf..a90ddfe991 100644--- a/camera/src/main/rust/src/night.rs+++ b/camera/src/main/rust/src/night.rs@@ -186,9 +186,8 @@ fn merge_with_homographies( } let mut px = [0u8; 4]; for ch in 0..3 {- px[ch] = trimmed_mean(sum[ch], min[ch], max[ch], count)- .round()- .clamp(0.0, 255.0) as u8;+ px[ch] =+ trimmed_mean(sum[ch], min[ch], max[ch], count).round().clamp(0.0, 255.0) as u8; } px[3] = 255; out.set(x, y, px);@@ -252,7 +251,8 @@ pub fn align_and_merge(frames: &[Rgba]) -> Option<Rgba> { continue; } let a: Vec<Pt> = matches.iter().map(|&(ia, _)| (feat.kps[ia].x, feat.kps[ia].y)).collect();- let b: Vec<Pt> = matches.iter().map(|&(_, ib)| (ref_feat.kps[ib].x, ref_feat.kps[ib].y)).collect();+ let b: Vec<Pt> =+ matches.iter().map(|&(_, ib)| (ref_feat.kps[ib].x, ref_feat.kps[ib].y)).collect(); let h_small = match find_homography_ransac(&a, &b, RANSAC_ITERS, RANSAC_THRESH) { Some((hm, inl)) if inl >= MIN_INLIERS => hm, _ => continue,
camera/src/main/rust/src/raw_jni.rs
diff --git a/camera/src/main/rust/src/raw_jni.rs b/camera/src/main/rust/src/raw_jni.rsindex 62d67ee9ec..296b215caf 100644--- a/camera/src/main/rust/src/raw_jni.rs+++ b/camera/src/main/rust/src/raw_jni.rs@@ -83,8 +83,7 @@ pub extern "system" fn Java_com_vayunmathur_camera_platform_StitchNative_mergeRa let null = std::ptr::null_mut(); let bytes = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { let frames = raw_night_registry().lock().unwrap().remove(&handle)?;- raw_night::merge_raw_burst(&frames, exposure_gain)- .and_then(|img| encode_jpeg(&img, 95))+ raw_night::merge_raw_burst(&frames, exposure_gain).and_then(|img| encode_jpeg(&img, 95)) })) .unwrap_or(None); match bytes {
camera/src/main/rust/src/raw_night.rs
diff --git a/camera/src/main/rust/src/raw_night.rs b/camera/src/main/rust/src/raw_night.rsindex 15dcad9146..1f0417982b 100644--- a/camera/src/main/rust/src/raw_night.rs+++ b/camera/src/main/rust/src/raw_night.rs@@ -92,7 +92,13 @@ impl RawMeta { /// Uniform-black convenience constructor (tests and scalar-black sensors). #[allow(dead_code)] pub fn scalar(black: f32, white: f32, cfa: Cfa) -> Self {- RawMeta { black_levels: [black; 4], white_level: white, cfa, gains: [1.0, 1.0, 1.0], exposure_scale: 1.0 }+ RawMeta {+ black_levels: [black; 4],+ white_level: white,+ cfa,+ gains: [1.0, 1.0, 1.0],+ exposure_scale: 1.0,+ } } } @@ -184,7 +190,11 @@ pub fn demosaic(frame: &RawFrame) -> LinearRgb { } else { rgb[1] = (at(x - 1, y).0 + at(x + 1, y).0 + at(x, y - 1).0 + at(x, y + 1).0) * 0.25; let other = 2 - ch;- rgb[other] = (at(x - 1, y - 1).0 + at(x + 1, y - 1).0 + at(x - 1, y + 1).0 + at(x + 1, y + 1).0) * 0.25;+ rgb[other] = (at(x - 1, y - 1).0+ + at(x + 1, y - 1).0+ + at(x - 1, y + 1).0+ + at(x + 1, y + 1).0)+ * 0.25; } for c in 0..3 { rgb[c] *= frame.meta.gains[c];@@ -220,7 +230,17 @@ fn scale_homography(h: &Matrix3<f64>, s: f64) -> Matrix3<f64> { if (s - 1.0).abs() < 1e-6 { return *h; }- Matrix3::new(h[(0, 0)], h[(0, 1)], h[(0, 2)] / s, h[(1, 0)], h[(1, 1)], h[(1, 2)] / s, h[(2, 0)] * s, h[(2, 1)] * s, h[(2, 2)])+ Matrix3::new(+ h[(0, 0)],+ h[(0, 1)],+ h[(0, 2)] / s,+ h[(1, 0)],+ h[(1, 1)],+ h[(1, 2)] / s,+ h[(2, 0)] * s,+ h[(2, 1)] * s,+ h[(2, 2)],+ ) } /// Estimates, per frame, the warp from reference coordinates into that@@ -244,7 +264,8 @@ fn estimate_warps(frames: &[LinearRgb]) -> Vec<Option<Matrix3<f64>>> { continue; } let a: Vec<Pt> = matches.iter().map(|&(ia, _)| (feat.kps[ia].x, feat.kps[ia].y)).collect();- let b: Vec<Pt> = matches.iter().map(|&(_, ib)| (ref_feat.kps[ib].x, ref_feat.kps[ib].y)).collect();+ let b: Vec<Pt> =+ matches.iter().map(|&(_, ib)| (ref_feat.kps[ib].x, ref_feat.kps[ib].y)).collect(); if let Some((h_small, inl)) = find_homography_ransac(&a, &b, RANSAC_ITERS, RANSAC_THRESH) { if inl < MIN_INLIERS { continue;@@ -261,7 +282,11 @@ fn estimate_warps(frames: &[LinearRgb]) -> Vec<Option<Matrix3<f64>>> { #[inline] fn apply_h(h: &Matrix3<f64>, x: f64, y: f64) -> (f64, f64) { let v = h * crate::linalg::Vector3::new(x, y, 1.0);- if v.z.abs() < 1e-12 { (v.x, v.y) } else { (v.x / v.z, v.y / v.z) }+ if v.z.abs() < 1e-12 {+ (v.x, v.y)+ } else {+ (v.x / v.z, v.y / v.z)+ } } #[inline]@@ -326,7 +351,9 @@ pub fn merge_raw_linear(frames: &[RawFrame]) -> Option<LinearRgb> { let (sx, sy) = apply_h(&warp, x as f64, y as f64); let Some(mut c) = sample_linear_rgb(f, sx as f32, sy as f32) else { continue }; let norm = ref_scale / frames[i].meta.exposure_scale.max(1e-6);- for ch in 0..3 { c[ch] *= norm; }+ for ch in 0..3 {+ c[ch] *= norm;+ } let diff = (c[0] - rp[0]).abs() + (c[1] - rp[1]).abs() + (c[2] - rp[2]).abs(); if diff > LINEAR_GHOST_THRESH { continue;
camera/src/main/rust/src/raw_night_tests.rs
diff --git a/camera/src/main/rust/src/raw_night_tests.rs b/camera/src/main/rust/src/raw_night_tests.rsindex 2275666f18..c6d896ab11 100644--- a/camera/src/main/rust/src/raw_night_tests.rs+++ b/camera/src/main/rust/src/raw_night_tests.rs@@ -117,7 +117,8 @@ fn merge_reduces_noise_variance_measurably() { // Large enough for the ORB pyramid's 31px edge threshold to leave an // interior (registration needs >~72px per side to see any keypoints). let (w, h) = (160, 120);- let frames: Vec<RawFrame> = (0..6).map(|i| synthetic(w, h, 100 + i * 17, 28, 64, 1023)).collect();+ let frames: Vec<RawFrame> =+ (0..6).map(|i| synthetic(w, h, 100 + i * 17, 28, 64, 1023)).collect(); let single = demosaic(&frames[0]); let clean = demosaic(&synthetic(w, h, 999, 0, 64, 1023)); let merged = merge_raw_linear(&frames).expect("merge");
camera/src/main/rust/src/seam.rs
diff --git a/camera/src/main/rust/src/seam.rs b/camera/src/main/rust/src/seam.rsindex 2a188621cd..75878e4564 100644--- a/camera/src/main/rust/src/seam.rs+++ b/camera/src/main/rust/src/seam.rs@@ -29,7 +29,9 @@ pub fn voronoi_masks(tiles: &[WarpedTile]) -> Vec<Vec<u8>> { let (gx0, gy0, gx1, gy1) = global_bounds(tiles); let centers: Vec<(f64, f64)> = tiles .iter()- .map(|t| (t.corner_x as f64 + t.img.w as f64 / 2.0, t.corner_y as f64 + t.img.h as f64 / 2.0))+ .map(|t| {+ (t.corner_x as f64 + t.img.w as f64 / 2.0, t.corner_y as f64 + t.img.h as f64 / 2.0)+ }) .collect(); for gy in gy0..gy1 { for gx in gx0..gx1 {@@ -196,7 +198,7 @@ fn graph_cut_masks(tiles: &[WarpedTile]) -> Option<Vec<Vec<u8>>> { mf.max_flow(src, snk); let cut = mf.min_cut_side(src); // true = source side (A keeps), false = sink (B=ti)- // Assign overlap pixels.+ // Assign overlap pixels. for (k, &gi) in overlap.iter().enumerate() { if !cut[k] { owner[gi] = ti as i32;@@ -307,9 +309,14 @@ fn gradient_map(img: &Rgba) -> Vec<i64> { let yp_row = yp; // 3x3 luma matrix let get_l = |xx: usize, yy: usize| -> i32 { luma_i(img.get(xx, yy)) as i32 };- let l00 = get_l(xm, ym_row); let l01 = get_l(x, ym_row); let l02 = get_l(xp, ym_row);- let l10 = get_l(xm, y); let l12 = get_l(xp, y);- let l20 = get_l(xm, yp_row); let l21 = get_l(x, yp_row); let l22 = get_l(xp, yp_row);+ let l00 = get_l(xm, ym_row);+ let l01 = get_l(x, ym_row);+ let l02 = get_l(xp, ym_row);+ let l10 = get_l(xm, y);+ let l12 = get_l(xp, y);+ let l20 = get_l(xm, yp_row);+ let l21 = get_l(x, yp_row);+ let l22 = get_l(xp, yp_row); let dx = -l00 + l02 - 2 * l10 + 2 * l12 - l20 + l22; let dy = -l00 - 2 * l01 - l02 + l20 + 2 * l21 + l22; let mag = dx.abs() + dy.abs(); // Manhattan approx of Sobel magnitude, scaled
camera/src/main/rust/src/seam_tests.rs
diff --git a/camera/src/main/rust/src/seam_tests.rs b/camera/src/main/rust/src/seam_tests.rsindex f8c53fc57b..f15c9464a7 100644--- a/camera/src/main/rust/src/seam_tests.rs+++ b/camera/src/main/rust/src/seam_tests.rs@@ -123,10 +123,7 @@ fn voronoi_masks_empty_and_single_tile() { #[test] fn voronoi_masks_partition_overlap_between_nearest_centres() {- let tiles = vec![- tile(10, 6, 0, 0, [255, 0, 0, 255]),- tile(10, 6, 6, 0, [0, 0, 255, 255]),- ];+ let tiles = vec![tile(10, 6, 0, 0, [255, 0, 0, 255]), tile(10, 6, 6, 0, [0, 0, 255, 255])]; let masks = voronoi_masks(&tiles); let total: usize = masks.iter().map(|m| m.iter().filter(|&&v| v != 0).count()).sum(); assert_eq!(total, 16 * 6, "union covered exactly once");@@ -137,10 +134,7 @@ fn voronoi_masks_partition_overlap_between_nearest_centres() { #[test] fn seam_masks_agree_with_voronoi_on_disjoint_tiles() {- let tiles = vec![- tile(5, 5, 0, 0, [255, 0, 0, 255]),- tile(5, 5, 30, 0, [0, 255, 0, 255]),- ];+ let tiles = vec![tile(5, 5, 0, 0, [255, 0, 0, 255]), tile(5, 5, 30, 0, [0, 255, 0, 255])]; let masks = seam_masks(&tiles); assert_eq!(masks.len(), 2); assert!(masks.iter().all(|m| m.iter().all(|&v| v == 1)));@@ -149,10 +143,7 @@ fn seam_masks_agree_with_voronoi_on_disjoint_tiles() { #[test] fn seam_masks_partition_overlapping_coverage_exactly_once() {- let tiles = vec![- tile(12, 8, 0, 0, [200, 30, 30, 255]),- tile(12, 8, 6, 2, [30, 30, 200, 255]),- ];+ let tiles = vec![tile(12, 8, 0, 0, [200, 30, 30, 255]), tile(12, 8, 6, 2, [30, 30, 200, 255])]; let masks = seam_masks(&tiles); // Union is the bounding box minus the two uncovered corners: compute // coverage from alpha and compare counts.
camera/src/main/rust/src/sphere.rs
diff --git a/camera/src/main/rust/src/sphere.rs b/camera/src/main/rust/src/sphere.rsindex 9c6ead5cbe..5e34d20c66 100644--- a/camera/src/main/rust/src/sphere.rs+++ b/camera/src/main/rust/src/sphere.rs@@ -15,9 +15,15 @@ use crate::linalg::{Matrix3, Vector3}; pub fn focals_from_homography(h: &Matrix3<f64>) -> (Option<f64>, Option<f64>) { // Row-major access matching OpenCV's h[0..8]. let hh = [- h[(0, 0)], h[(0, 1)], h[(0, 2)],- h[(1, 0)], h[(1, 1)], h[(1, 2)],- h[(2, 0)], h[(2, 1)], h[(2, 2)],+ h[(0, 0)],+ h[(0, 1)],+ h[(0, 2)],+ h[(1, 0)],+ h[(1, 1)],+ h[(1, 2)],+ h[(2, 0)],+ h[(2, 1)],+ h[(2, 2)], ]; // f1 (from the "to" image)@@ -97,11 +103,7 @@ pub fn estimate_focal_with_prior( } all.sort_by(|a, b| a.total_cmp(b)); let m = all.len() / 2;- let median = if all.len() % 2 == 1 {- all[m]- } else {- (all[m - 1] + all[m]) / 2.0- };+ let median = if all.len() % 2 == 1 { all[m] } else { (all[m - 1] + all[m]) / 2.0 }; match prior { Some(p) => median.clamp(0.5 * p, 2.0 * p), None => median,@@ -135,13 +137,7 @@ impl Proj { pub fn new(k: &Matrix3<f64>, r: &Matrix3<f64>, scale: f64) -> Option<Proj> { let k_inv = k.try_inverse()?; let rinv = r.transpose();- Some(Proj {- r_kinv: r * k_inv,- k_rinv: k * rinv,- rinv,- k: *k,- scale,- })+ Some(Proj { r_kinv: r * k_inv, k_rinv: k * rinv, rinv, k: *k, scale }) } /// source (x,y) -> sphere (u,v). Spherical handles large vertical FOV (tall@@ -258,7 +254,13 @@ fn tile_bounds(proj: &Proj, w: usize, h: usize) -> (f64, f64, f64, f64) { /// Cheap (u,v) bounds of a warped image (border walk only, no pixels), for /// sizing the output canvas before committing to a full warp.-pub fn warped_bounds(fw: usize, fh: usize, k: &Matrix3<f64>, r: &Matrix3<f64>, scale: f64) -> Option<(f64, f64, f64, f64)> {+pub fn warped_bounds(+ fw: usize,+ fh: usize,+ k: &Matrix3<f64>,+ r: &Matrix3<f64>,+ scale: f64,+) -> Option<(f64, f64, f64, f64)> { let p = Proj::new(k, r, scale)?; let b = tile_bounds(&p, fw, fh); if b.0.is_finite() && b.1.is_finite() && b.2.is_finite() && b.3.is_finite() {@@ -291,10 +293,16 @@ fn sample_reflect_101(frame: &Rgba, fx: f32, fy: f32) -> Option<[f32; 4]> { fn refl(i: isize, n: usize) -> usize { let m = n as isize;- if m <= 1 { return 0; }+ if m <= 1 {+ return 0;+ } let mut v = i; while v < 0 || v >= m {- if v < 0 { v = -v; } else { v = 2 * m - v - 2; }+ if v < 0 {+ v = -v;+ } else {+ v = 2 * m - v - 2;+ } } v as usize }@@ -323,7 +331,12 @@ fn sample_reflect_101(frame: &Rgba, fx: f32, fy: f32) -> Option<[f32; 4]> { /// Warp one image onto the sphere with camera intrinsics `k`/rotation `r` and /// warp `scale`. Mirrors SphericalWarper::warp (buildMaps + remap) with /// BORDER_REFLECT_101 sampling (not clamp) and pole ROI already handled in tile_bounds.-pub fn warp_one(frame: &Rgba, k: &Matrix3<f64>, r: &Matrix3<f64>, scale: f64) -> Option<WarpedTile> {+pub fn warp_one(+ frame: &Rgba,+ k: &Matrix3<f64>,+ r: &Matrix3<f64>,+ scale: f64,+) -> Option<WarpedTile> { let p = Proj::new(k, r, scale)?; let (u0, v0, u1, v1) = tile_bounds(&p, frame.w, frame.h); if !u0.is_finite() || !u1.is_finite() {@@ -345,12 +358,16 @@ pub fn warp_one(frame: &Rgba, k: &Matrix3<f64>, r: &Matrix3<f64>, scale: f64) -> // Use reflect_101 sampling for spherical quality like OpenCV INTER_LINEAR BORDER_REFLECT if let Some(c) = sample_reflect_101(frame, sx as f32, sy as f32) { if c[3] >= 8.0 {- img.set(tx, ty, [- c[0].round().clamp(0.0, 255.0) as u8,- c[1].round().clamp(0.0, 255.0) as u8,- c[2].round().clamp(0.0, 255.0) as u8,- 255,- ]);+ img.set(+ tx,+ ty,+ [+ c[0].round().clamp(0.0, 255.0) as u8,+ c[1].round().clamp(0.0, 255.0) as u8,+ c[2].round().clamp(0.0, 255.0) as u8,+ 255,+ ],+ ); } } }
camera/src/main/rust/src/sphere_tests.rs
diff --git a/camera/src/main/rust/src/sphere_tests.rs b/camera/src/main/rust/src/sphere_tests.rsindex 71a0ad86bd..c6f1cc31b9 100644--- a/camera/src/main/rust/src/sphere_tests.rs+++ b/camera/src/main/rust/src/sphere_tests.rs@@ -2,11 +2,15 @@ //! projector round trip, orthonormalisation, and single-image warping. fn mdiff(a: &Matrix3<f64>, b: &Matrix3<f64>) -> f64 { let mut s = 0.0f64;- for r in 0..3 { for c in 0..3 { let d = a[(r, c)] - b[(r, c)]; s += d * d; } }+ for r in 0..3 {+ for c in 0..3 {+ let d = a[(r, c)] - b[(r, c)];+ s += d * d;+ }+ } s.sqrt() } - use super::*; use crate::camera::rodrigues_to_mat; use crate::linalg::Vector3;@@ -71,7 +75,17 @@ fn estimate_focal_median_odd_and_even_counts() { #[test] fn orthonormalize_snaps_scaled_rotation_back_to_rotation() { let r = rodrigues_to_mat(Vector3::new(0.1, -0.2, 0.05));- let scaled = Matrix3::new(r[(0,0)]*1.7, r[(0,1)]*1.7, r[(0,2)]*1.7, r[(1,0)]*1.7, r[(1,1)]*1.7, r[(1,2)]*1.7, r[(2,0)]*1.7, r[(2,1)]*1.7, r[(2,2)]*1.7); // scalar multiple: SVD projection drops the scale+ let scaled = Matrix3::new(+ r[(0, 0)] * 1.7,+ r[(0, 1)] * 1.7,+ r[(0, 2)] * 1.7,+ r[(1, 0)] * 1.7,+ r[(1, 1)] * 1.7,+ r[(1, 2)] * 1.7,+ r[(2, 0)] * 1.7,+ r[(2, 1)] * 1.7,+ r[(2, 2)] * 1.7,+ ); // scalar multiple: SVD projection drops the scale let o = orthonormalize(&scaled); assert!(approx(o.determinant(), 1.0, 1e-9) || approx(o.determinant(), -1.0, 1e-9)); let prod = o * o.transpose();
camera/src/main/rust/src/stitch.rs
diff --git a/camera/src/main/rust/src/stitch.rs b/camera/src/main/rust/src/stitch.rsindex 1f0ef90a3c..b2bac21a57 100644--- a/camera/src/main/rust/src/stitch.rs+++ b/camera/src/main/rust/src/stitch.rs@@ -5,7 +5,6 @@ //! stages are parallelised with rayon. use crate::blend::{build_compose_masks, multiband_blend, multiband_blend_with_rect, resize_gain};-use crate::sphere::{focal_prior_reg, sphere_canvas}; use crate::bundle::bundle_adjust; use crate::camera::CameraParams; use crate::estimator::estimate_cameras;@@ -14,15 +13,16 @@ use crate::features::{detect_and_describe, Features}; use crate::imgbuf::{to_gray, Rgba}; use crate::matching::{biggest_component, match_all, MatchInfo}; use crate::seam::seam_masks;+use crate::sphere::{focal_prior_reg, sphere_canvas}; use crate::sphere::{warp_one, warped_bounds, WarpedTile}; use crate::warp::mean_luma; use crate::wave::wave_correct_horizontal; const MAX_FEATURES: usize = 3000; // keep upper bound but distributed via pyramid, ORB default 500 but we keep 3000 for quality const FAST_THRESHOLD: i32 = 20; // ORB default 20, was 12 – matches OpenCV-// OpenCV default BEST_OF_2_NEAREST_MATCHER_CONFIDENCE=0.3; 1.0 was too strict for-// sparse 3-4 frame sweeps at 30° — kept largest component dropped to 1 image,-// causing "estimate returned null" and no save.+ // OpenCV default BEST_OF_2_NEAREST_MATCHER_CONFIDENCE=0.3; 1.0 was too strict for+ // sparse 3-4 frame sweeps at 30° — kept largest component dropped to 1 image,+ // causing "estimate returned null" and no save. pub const CONF_THRESH: f64 = 0.3; const MATCH_MAX_ANGLE: f32 = 55.0; // match frames within this gyro separation (deg) – custom optimization for mobile sphere grid const REG_MEGAPIXELS: f64 = 0.6; // registration resolution (like OpenCV's registr_resol_)@@ -53,7 +53,8 @@ fn remap_matches(matches: Vec<MatchInfo>, kept: &[usize]) -> Vec<MatchInfo> { } fn median_focal(cams: &[CameraParams]) -> f64 {- let mut f: Vec<f64> = cams.iter().map(|c| c.focal).filter(|v| v.is_finite() && *v > 1.0).collect();+ let mut f: Vec<f64> =+ cams.iter().map(|c| c.focal).filter(|v| v.is_finite() && *v > 1.0).collect(); if f.is_empty() { return 1.0; }@@ -105,7 +106,6 @@ fn median_f32(vals: &[f32]) -> f32 { } } - /// Registration-only path for the GPU compositor: runs the same low-res /// features → matching → estimate → bundle-adjust → wave-correct stages as /// [`stitch_panorama`], computes the compose canvas geometry, and returns@@ -226,12 +226,7 @@ pub fn estimate_pano( if !gx0.is_finite() || !gy0.is_finite() || !gx1.is_finite() || !gy1.is_finite() { return None; }- (- ((gx1 - gx0).ceil() as i64 + 1).max(1),- ((gy1 - gy0).ceil() as i64 + 1).max(1),- gx0,- gy0,- )+ (((gx1 - gx0).ceil() as i64 + 1).max(1), ((gy1 - gy0).ceil() as i64 + 1).max(1), gx0, gy0) }; // Cheap per-frame exposure gain: pull each kept frame toward the median luma.@@ -242,7 +237,8 @@ pub fn estimate_pano( .zip(cams.iter()) .map(|(&i, c)| { let luma = lumas[i];- let gain = if ref_luma > 1.0 && luma > 1.0 { (ref_luma / luma).clamp(0.5, 2.0) } else { 1.0 };+ let gain =+ if ref_luma > 1.0 && luma > 1.0 { (ref_luma / luma).clamp(0.5, 2.0) } else { 1.0 }; let r = c.r; FrameCam { original_index: i,@@ -250,9 +246,15 @@ pub fn estimate_pano( ppx: c.ppx, ppy: c.ppy, r: [- r[(0, 0)], r[(0, 1)], r[(0, 2)],- r[(1, 0)], r[(1, 1)], r[(1, 2)],- r[(2, 0)], r[(2, 1)], r[(2, 2)],+ r[(0, 0)],+ r[(0, 1)],+ r[(0, 2)],+ r[(1, 0)],+ r[(1, 1)],+ r[(1, 2)],+ r[(2, 0)],+ r[(2, 1)],+ r[(2, 2)], ], gain, }@@ -394,7 +396,15 @@ pub fn stitch_panorama( // Compose-resolution seam masks as a true partition of the coverage. let masks = build_compose_masks(&tiles, &seam_tiles, &low_masks); let gain_maps: Vec<Vec<f32>> = (0..tiles.len())- .map(|i| resize_gain(&seam_gains[i], seam_tiles[i].img.w, seam_tiles[i].img.h, tiles[i].img.w, tiles[i].img.h))+ .map(|i| {+ resize_gain(+ &seam_gains[i],+ seam_tiles[i].img.w,+ seam_tiles[i].img.h,+ tiles[i].img.w,+ tiles[i].img.h,+ )+ }) .collect(); if !sphere {@@ -435,7 +445,6 @@ pub fn stitch_panorama( Some(canvas) } - #[cfg(test)] #[path = "stitch_tests.rs"] mod stitch_tests;
camera/src/main/rust/src/stitch_tests.rs
diff --git a/camera/src/main/rust/src/stitch_tests.rs b/camera/src/main/rust/src/stitch_tests.rsindex 62f0ebe05b..d5199aa596 100644--- a/camera/src/main/rust/src/stitch_tests.rs+++ b/camera/src/main/rust/src/stitch_tests.rs@@ -124,7 +124,10 @@ fn build_compose_masks_empty_input_gives_empty_masks() { fn stitch_panorama_degenerate_inputs_return_none_or_single_frame() { assert!(stitch_panorama(&[], &[], &[], false, 0.0).is_none()); assert!(stitch_panorama(&[vec![1, 2, 3]], &[0.0], &[0.0], false, 0.0).is_none(), "bad JPEG");- assert!(estimate_pano(&[vec![1, 2, 3]], &[0.0], &[0.0], false, 0.0).is_none(), "needs >= 2 frames");+ assert!(+ estimate_pano(&[vec![1, 2, 3]], &[0.0], &[0.0], false, 0.0).is_none(),+ "needs >= 2 frames"+ ); assert!(estimate_pano(&[], &[], &[], false, 0.0).is_none()); }
camera/src/main/rust/src/warp.rs
diff --git a/camera/src/main/rust/src/warp.rs b/camera/src/main/rust/src/warp.rsindex 2e5b8760f8..3f9fa4c12e 100644--- a/camera/src/main/rust/src/warp.rs+++ b/camera/src/main/rust/src/warp.rs@@ -16,7 +16,11 @@ pub fn mean_luma(f: &Rgba) -> f32 { sum += 0.299 * r + 0.587 * g + 0.114 * b; n += 1.0; }- if n > 0.0 { (sum / n) as f32 } else { 0.0 }+ if n > 0.0 {+ (sum / n) as f32+ } else {+ 0.0+ } } #[cfg(test)]
camera/src/main/rust/src/wave_tests.rs
diff --git a/camera/src/main/rust/src/wave_tests.rs b/camera/src/main/rust/src/wave_tests.rsindex 85855c6c00..2b0ec58937 100644--- a/camera/src/main/rust/src/wave_tests.rs+++ b/camera/src/main/rust/src/wave_tests.rs@@ -2,11 +2,15 @@ //! already-level camera sets (nearly) unchanged. fn mdiff(a: &Matrix3<f64>, b: &Matrix3<f64>) -> f64 { let mut s = 0.0f64;- for r in 0..3 { for c in 0..3 { let d = a[(r, c)] - b[(r, c)]; s += d * d; } }+ for r in 0..3 {+ for c in 0..3 {+ let d = a[(r, c)] - b[(r, c)];+ s += d * d;+ }+ } s.sqrt() } - use super::*; use crate::camera::rodrigues_to_mat; use crate::linalg::Vector3;@@ -43,7 +47,8 @@ fn wave_correct_empty_and_single_are_noops() { #[test] fn wave_correct_identity_cameras_stay_rotations() {- let mut cams = vec![cam(Matrix3::identity()), cam(Matrix3::identity()), cam(Matrix3::identity())];+ let mut cams =+ vec![cam(Matrix3::identity()), cam(Matrix3::identity()), cam(Matrix3::identity())]; wave_correct_horizontal(&mut cams); for c in &cams { assert_rotation(&c.r);
camera/src/main/rust/tests/math_edges.rs
diff --git a/camera/src/main/rust/tests/math_edges.rs b/camera/src/main/rust/tests/math_edges.rsindex d016ce39c9..533197ae93 100644--- a/camera/src/main/rust/tests/math_edges.rs+++ b/camera/src/main/rust/tests/math_edges.rs@@ -39,13 +39,8 @@ fn rodrigues_identity_stays_identity() { #[test] fn camera_k_matrix_has_expected_shape() {- let params = CameraParams {- focal: 800.0,- aspect: 1.0,- ppx: 320.0,- ppy: 240.0,- r: Matrix3::identity(),- };+ let params =+ CameraParams { focal: 800.0, aspect: 1.0, ppx: 320.0, ppy: 240.0, r: Matrix3::identity() }; let k = params.k(); assert!(approx(k[(0, 0)], 800.0, 1e-9)); assert!(approx(k[(1, 1)], 800.0, 1e-9));
camera/src/main/rust/tests/pure_logic.rs
diff --git a/camera/src/main/rust/tests/pure_logic.rs b/camera/src/main/rust/tests/pure_logic.rsindex 776e94f81c..49fef751fe 100644--- a/camera/src/main/rust/tests/pure_logic.rs+++ b/camera/src/main/rust/tests/pure_logic.rs@@ -32,13 +32,8 @@ fn solid(w: usize, h: usize, c: [u8; 4]) -> Rgba { #[test] fn camera_k_uses_focal_times_aspect_for_y() {- let p = CameraParams {- focal: 600.0,- aspect: 0.5,- ppx: 10.0,- ppy: 20.0,- r: Matrix3::identity(),- };+ let p =+ CameraParams { focal: 600.0, aspect: 0.5, ppx: 10.0, ppy: 20.0, r: Matrix3::identity() }; let k = p.k(); assert!(approx(k[(0, 0)], 600.0, 1e-12)); assert!(approx(k[(1, 1)], 300.0, 1e-12), "fy = focal*aspect");@@ -241,7 +236,9 @@ fn transfer_inliers_with_identity_maps_points_to_themselves() { assert_eq!(inl, vec![0, 1, 2]); // A destination 100px away is not an inlier of the identity. let far: Vec<(f32, f32)> = pts.iter().map(|(x, y)| (x + 100.0, *y)).collect();- assert!(camera_stitch::geometry::transfer_inliers(&Matrix3::identity(), &pts, &far, 1.0).is_empty());+ assert!(+ camera_stitch::geometry::transfer_inliers(&Matrix3::identity(), &pts, &far, 1.0).is_empty()+ ); } #[test]@@ -253,9 +250,8 @@ fn homography_needs_at_least_four_points() { #[test] fn homography_recovers_pure_scale_about_origin() {- let a: Vec<(f32, f32)> = vec![- (1.0, 1.0), (4.0, 1.0), (4.0, 4.0), (1.0, 4.0), (2.0, 3.0), (7.0, 2.0), (3.0, 8.0),- ];+ let a: Vec<(f32, f32)> =+ vec![(1.0, 1.0), (4.0, 1.0), (4.0, 4.0), (1.0, 4.0), (2.0, 3.0), (7.0, 2.0), (3.0, 8.0)]; let b: Vec<(f32, f32)> = a.iter().map(|(x, y)| (2.0 * x, 2.0 * y)).collect(); let (h, inl) = camera_stitch::geometry::find_homography_ransac(&a, &b, 200, 1.0).expect("h"); assert!(inl >= 4, "inliers {inl}");
code/src/main/rust/src/highlight_tests.rs
diff --git a/code/src/main/rust/src/highlight_tests.rs b/code/src/main/rust/src/highlight_tests.rsindex ec8f829a33..a9c86bbdaa 100644--- a/code/src/main/rust/src/highlight_tests.rs+++ b/code/src/main/rust/src/highlight_tests.rs@@ -136,7 +136,9 @@ fn kind_for_unmapped_names_return_minus_one() { #[test] fn grammar_resolves_all_ten_language_ids() {- for id in ["kotlin", "java", "javascript", "typescript", "python", "rust", "go", "json", "c", "cpp"] {+ for id in+ ["kotlin", "java", "javascript", "typescript", "python", "rust", "go", "json", "c", "cpp"]+ { let (_, query) = grammar(id).unwrap_or_else(|| panic!("grammar({id:?})")); assert!(!query.is_empty(), "empty highlights query for {id}"); }@@ -145,8 +147,8 @@ fn grammar_resolves_all_ten_language_ids() { #[test] fn grammar_rejects_unknown_empty_and_case_variants() { for id in [- "", "unknown", "Kotlin", "KOTLIN", "RUST", "Rust", "Java", "CPP", "C", "kotlin ", " kotlin",- "rs", "kt", "js", "ts", "py", "golang", "c++", "C++", "python3", "java ",+ "", "unknown", "Kotlin", "KOTLIN", "RUST", "Rust", "Java", "CPP", "C", "kotlin ",+ " kotlin", "rs", "kt", "js", "ts", "py", "golang", "c++", "C++", "python3", "java ", ] { assert!(grammar(id).is_none(), "grammar({id:?}) should be None"); }@@ -164,7 +166,9 @@ fn highlight_unknown_language_returns_none() { #[test] fn highlight_empty_source_is_some_empty_for_all_languages() {- for id in ["kotlin", "java", "javascript", "typescript", "python", "rust", "go", "json", "c", "cpp"] {+ for id in+ ["kotlin", "java", "javascript", "typescript", "python", "rust", "go", "json", "c", "cpp"]+ { assert_eq!(highlight_source(id, ""), Some(Vec::new()), "empty {id}"); } // Whitespace-only source parses too, with no captures expected.@@ -454,7 +458,9 @@ fn highlight_longer_snippet_is_well_formed_and_ordered() { #[test] fn highlight_every_language_returns_some_on_plain_identifier() {- for id in ["kotlin", "java", "javascript", "typescript", "python", "rust", "go", "json", "c", "cpp"] {+ for id in+ ["kotlin", "java", "javascript", "typescript", "python", "rust", "go", "json", "c", "cpp"]+ { let v = highlight_source(id, "x"); assert!(v.is_some(), "expected Some for {id}"); assert_well_formed("x", &v.unwrap());@@ -465,14 +471,11 @@ fn highlight_every_language_returns_some_on_plain_identifier() { fn highlight_malformed_source_still_returns_some() { // Tree-sitter is error-tolerant: broken syntax parses to an (error) // tree rather than failing, so the result is `Some`, well-formed.- for (id, src) in [- ("rust", "fn { (("),- ("python", "def :\n (("),- ("json", "{\"a\": }"),- ("java", "class {"),- ] {- let v = highlight_source(id, src)- .unwrap_or_else(|| panic!("expected Some for {id} {src:?}"));+ for (id, src) in+ [("rust", "fn { (("), ("python", "def :\n (("), ("json", "{\"a\": }"), ("java", "class {")]+ {+ let v =+ highlight_source(id, src).unwrap_or_else(|| panic!("expected Some for {id} {src:?}")); assert_well_formed(src, &v); } }
code/src/main/rust/src/lib.rs
diff --git a/code/src/main/rust/src/lib.rs b/code/src/main/rust/src/lib.rsindex a904b54890..47b44d35b9 100644--- a/code/src/main/rust/src/lib.rs+++ b/code/src/main/rust/src/lib.rs@@ -12,52 +12,27 @@ use jni::objects::{JClass, JString}; use jni::sys::jintArray;-use jni::{EnvUnowned};+use jni::EnvUnowned; use tree_sitter::{Language, Parser, Query, QueryCursor}; /// Resolves a language id (see `TreeSitterNative.languageIdFor`) to its grammar + highlights query. fn grammar(id: &str) -> Option<(Language, &'static str)> { let entry: (Language, &'static str) = match id {- "kotlin" => (- tree_sitter_kotlin::language(),- tree_sitter_kotlin::HIGHLIGHTS_QUERY,- ),- "java" => (- tree_sitter_java::language(),- tree_sitter_java::HIGHLIGHTS_QUERY,- ),- "javascript" => (- tree_sitter_javascript::language(),- tree_sitter_javascript::HIGHLIGHT_QUERY,- ),+ "kotlin" => (tree_sitter_kotlin::language(), tree_sitter_kotlin::HIGHLIGHTS_QUERY),+ "java" => (tree_sitter_java::language(), tree_sitter_java::HIGHLIGHTS_QUERY),+ "javascript" => {+ (tree_sitter_javascript::language(), tree_sitter_javascript::HIGHLIGHT_QUERY)+ } "typescript" => ( tree_sitter_typescript::language_typescript(), tree_sitter_typescript::HIGHLIGHTS_QUERY, ),- "python" => (- tree_sitter_python::language(),- tree_sitter_python::HIGHLIGHTS_QUERY,- ),- "rust" => (- tree_sitter_rust::language(),- tree_sitter_rust::HIGHLIGHTS_QUERY,- ),- "go" => (- tree_sitter_go::language(),- tree_sitter_go::HIGHLIGHTS_QUERY,- ),- "json" => (- tree_sitter_json::language(),- tree_sitter_json::HIGHLIGHTS_QUERY,- ),- "c" => (- tree_sitter_c::language(),- tree_sitter_c::HIGHLIGHT_QUERY,- ),- "cpp" => (- tree_sitter_cpp::language(),- tree_sitter_cpp::HIGHLIGHT_QUERY,- ),+ "python" => (tree_sitter_python::language(), tree_sitter_python::HIGHLIGHTS_QUERY),+ "rust" => (tree_sitter_rust::language(), tree_sitter_rust::HIGHLIGHTS_QUERY),+ "go" => (tree_sitter_go::language(), tree_sitter_go::HIGHLIGHTS_QUERY),+ "json" => (tree_sitter_json::language(), tree_sitter_json::HIGHLIGHTS_QUERY),+ "c" => (tree_sitter_c::language(), tree_sitter_c::HIGHLIGHT_QUERY),+ "cpp" => (tree_sitter_cpp::language(), tree_sitter_cpp::HIGHLIGHT_QUERY), _ => return None, }; Some(entry)@@ -123,14 +98,21 @@ mod highlight_tests; /// Called by the JVM with valid `env`/argument references. #[no_mangle] pub extern "system" fn Java_com_vayunmathur_code_util_TreeSitterNative_highlight<'local>(- mut env: EnvUnowned<'local>, _class: JClass<'local>, language_id: JString<'local>, source: JString<'local>) -> jintArray {+ mut env: EnvUnowned<'local>,+ _class: JClass<'local>,+ language_id: JString<'local>,+ source: JString<'local>,+) -> jintArray { env.with_env(|env| -> jni::errors::Result<jintArray> { let null = std::ptr::null_mut(); let Ok(id) = language_id.try_to_string(env) else { return Ok(null) }; let Ok(src) = source.try_to_string(env) else { return Ok(null) }; let Some(out) = highlight_source(&id, &src) else { return Ok(null) }; let Ok(arr) = env.new_int_array(out.len()) else { return Ok(null) };- if arr.set_region(env, 0, &out).is_err() { return Ok(null); }+ if arr.set_region(env, 0, &out).is_err() {+ return Ok(null);+ } Ok(arr.into_raw())- }).resolve::<jni::errors::LogErrorAndDefault>()+ })+ .resolve::<jni::errors::LogErrorAndDefault>() }
communicate-dev/src/main/rust-mls/src/group.rs
diff --git a/communicate-dev/src/main/rust-mls/src/group.rs b/communicate-dev/src/main/rust-mls/src/group.rsindex 994ef4264f..5909501751 100644--- a/communicate-dev/src/main/rust-mls/src/group.rs+++ b/communicate-dev/src/main/rust-mls/src/group.rs@@ -104,12 +104,7 @@ pub fn build_key_package( let (credential_with_key, signer) = keys::credential_and_signer(&identity).map_err(|_| GroupError::BadIdentity)?; let bundle: KeyPackageBundle = KeyPackage::builder()- .build(- keys::ciphersuite(),- &provider,- &signer,- credential_with_key,- )+ .build(keys::ciphersuite(), &provider, &signer, credential_with_key) .map_err(|e| GroupError::Mls(format!("{e:?}")))?; let tls = bundle .key_package()@@ -127,16 +122,9 @@ pub fn create_group( let identity = keys::parse_identity(identity_bytes).map_err(|_| GroupError::BadIdentity)?; let (credential_with_key, signer) = keys::credential_and_signer(&identity).map_err(|_| GroupError::BadIdentity)?;- let config = MlsGroupCreateConfig::builder()- .ciphersuite(keys::ciphersuite())- .build();- let group = MlsGroup::new(- &provider,- &signer,- &config,- credential_with_key,- )- .map_err(|e| GroupError::Mls(format!("{e:?}")))?;+ let config = MlsGroupCreateConfig::builder().ciphersuite(keys::ciphersuite()).build();+ let group = MlsGroup::new(&provider, &signer, &config, credential_with_key)+ .map_err(|e| GroupError::Mls(format!("{e:?}")))?; Ok(GroupCreated { storage: provider.snapshot(), group_id: group.group_id().as_slice().to_vec(),@@ -172,15 +160,11 @@ pub fn add_members( let (commit_out, welcome_out, group_info) = group .add_members(&provider, &signer, &key_packages) .map_err(|e| GroupError::Mls(format!("{e:?}")))?;- group- .merge_pending_commit(&provider)- .map_err(|e| GroupError::Mls(format!("{e:?}")))?;- let commit = commit_out- .tls_serialize_detached()- .map_err(|e| GroupError::Mls(format!("{e:?}")))?;- let welcome_msg = welcome_out- .tls_serialize_detached()- .map_err(|e| GroupError::Mls(format!("{e:?}")))?;+ group.merge_pending_commit(&provider).map_err(|e| GroupError::Mls(format!("{e:?}")))?;+ let commit =+ commit_out.tls_serialize_detached().map_err(|e| GroupError::Mls(format!("{e:?}")))?;+ let welcome_msg =+ welcome_out.tls_serialize_detached().map_err(|e| GroupError::Mls(format!("{e:?}")))?; let tree_tls = group .export_ratchet_tree() .tls_serialize_detached()@@ -192,11 +176,7 @@ pub fn add_members( welcome.extend_from_slice(&welcome_msg); push_u32(&mut welcome, tree_tls.len()); welcome.extend_from_slice(&tree_tls);- Ok(MembersAdded {- storage: provider.snapshot(),- commit,- welcome,- })+ Ok(MembersAdded { storage: provider.snapshot(), commit, welcome }) } /// Join a group from a [`WELCOME_MAGIC`]-framed envelope. Returns the updated@@ -218,9 +198,7 @@ pub fn join_group( let config = MlsGroupJoinConfig::builder().build(); let staged = StagedWelcome::new_from_welcome(&provider, &config, welcome, Some(tree)) .map_err(|e| GroupError::Mls(format!("{e:?}")))?;- let group = staged- .into_group(&provider)- .map_err(|e| GroupError::Mls(format!("{e:?}")))?;+ let group = staged.into_group(&provider).map_err(|e| GroupError::Mls(format!("{e:?}")))?; let group_id = group.group_id().as_slice().to_vec(); Ok((provider.snapshot(), group_id)) }@@ -241,19 +219,14 @@ pub fn remove_members( let (_, signer) = keys::credential_and_signer(&identity).map_err(|_| GroupError::BadIdentity)?; let mut group = load_group(&provider, group_id)?;- let indices: Vec<openmls::prelude::LeafNodeIndex> = removed_indices- .iter()- .map(|i| openmls::prelude::LeafNodeIndex::new(*i))- .collect();+ let indices: Vec<openmls::prelude::LeafNodeIndex> =+ removed_indices.iter().map(|i| openmls::prelude::LeafNodeIndex::new(*i)).collect(); let (commit_out, _, _) = group .remove_members(&provider, &signer, &indices) .map_err(|e| GroupError::Mls(format!("{e:?}")))?;- group- .merge_pending_commit(&provider)- .map_err(|e| GroupError::Mls(format!("{e:?}")))?;- let commit = commit_out- .tls_serialize_detached()- .map_err(|e| GroupError::Mls(format!("{e:?}")))?;+ group.merge_pending_commit(&provider).map_err(|e| GroupError::Mls(format!("{e:?}")))?;+ let commit =+ commit_out.tls_serialize_detached().map_err(|e| GroupError::Mls(format!("{e:?}")))?; Ok((provider.snapshot(), commit)) } @@ -272,16 +245,11 @@ pub fn encrypt( let out: MlsMessageOut = group .create_message(&provider, &signer, plaintext) .map_err(|e| GroupError::Mls(format!("{e:?}")))?;- let tls = out- .tls_serialize_detached()- .map_err(|e| GroupError::Mls(format!("{e:?}")))?;+ let tls = out.tls_serialize_detached().map_err(|e| GroupError::Mls(format!("{e:?}")))?; let mut payload = Vec::with_capacity(8 + tls.len()); payload.extend_from_slice(MESSAGE_MAGIC); payload.extend_from_slice(&tls);- Ok(Encrypted {- storage: provider.snapshot(),- payload,- })+ Ok(Encrypted { storage: provider.snapshot(), payload }) } /// Decrypt a [`MESSAGE_MAGIC`]-framed payload for [`group_id`].@@ -298,9 +266,8 @@ pub fn decrypt( let mut group = load_group(&provider, group_id)?; let inbound = MlsMessageIn::tls_deserialize(&mut tls.as_slice()) .map_err(|e| GroupError::Mls(format!("{e:?}")))?;- let protocol: ProtocolMessage = inbound- .try_into()- .map_err(|e| GroupError::Mls(format!("{e:?}")))?;+ let protocol: ProtocolMessage =+ inbound.try_into().map_err(|e| GroupError::Mls(format!("{e:?}")))?; let processed = group .process_message(&provider, protocol) .map_err(|e| GroupError::Mls(format!("{e:?}")))?;@@ -319,17 +286,10 @@ pub fn decrypt( } _ => (Vec::new(), false), };- Ok(Decrypted {- storage: provider.snapshot(),- plaintext,- is_application,- })+ Ok(Decrypted { storage: provider.snapshot(), plaintext, is_application }) } -fn load_group(- provider: &SnapshotProvider,- group_id: &[u8],-) -> Result<MlsGroup, GroupError> {+fn load_group(provider: &SnapshotProvider, group_id: &[u8]) -> Result<MlsGroup, GroupError> { if group_id.is_empty() { return Err(GroupError::InvalidInput("empty group id")); }@@ -359,10 +319,7 @@ fn strip_message(framed: &[u8]) -> Result<Vec<u8>, GroupError> { if framed.get(..8) != Some(MESSAGE_MAGIC.as_slice()) { return Err(GroupError::InvalidInput("bad message magic")); }- framed- .get(8..)- .map(<[u8]>::to_vec)- .ok_or(GroupError::InvalidInput("bad message magic"))+ framed.get(8..).map(<[u8]>::to_vec).ok_or(GroupError::InvalidInput("bad message magic")) } fn push_u32(out: &mut Vec<u8>, v: usize) {
communicate-dev/src/main/rust-mls/src/jni_bridge.rs
diff --git a/communicate-dev/src/main/rust-mls/src/jni_bridge.rs b/communicate-dev/src/main/rust-mls/src/jni_bridge.rsindex 38689fa5e0..c8cfca124d 100644--- a/communicate-dev/src/main/rust-mls/src/jni_bridge.rs+++ b/communicate-dev/src/main/rust-mls/src/jni_bridge.rs@@ -11,7 +11,7 @@ use crate::message::payload_kind; use jni::objects::{JByteArray, JClass, JObjectArray}; use jni::strings::JNIString; use jni::sys::{jbyteArray, jint, jobjectArray};-use jni::{Env, EnvUnowned, jni_str};+use jni::{jni_str, Env, EnvUnowned}; // PACKAGE STRUCTURE EXCEPTION (JNI)
communicate-dev/src/main/rust-mls/src/keys.rs
diff --git a/communicate-dev/src/main/rust-mls/src/keys.rs b/communicate-dev/src/main/rust-mls/src/keys.rsindex 45baaa939b..2f984f6f05 100644--- a/communicate-dev/src/main/rust-mls/src/keys.rs+++ b/communicate-dev/src/main/rust-mls/src/keys.rs@@ -59,8 +59,7 @@ pub fn generate_identity(identity: &str) -> Result<IdentityState, KeysError> { let mut rng = SysRng; let mut secret = [0u8; 32]; use rand_core::TryRng;- rng.try_fill_bytes(&mut secret)- .map_err(|e| KeysError::Provider(e.to_string()))?;+ rng.try_fill_bytes(&mut secret).map_err(|e| KeysError::Provider(e.to_string()))?; let signing = SigningKey::from_bytes(&secret); let verifying = signing.verifying_key(); Ok(IdentityState {@@ -109,11 +108,7 @@ pub fn parse_identity(bytes: &[u8]) -> Result<IdentityState, KeysError> { if sign_private.len() != 32 || sign_public.len() != 32 || identity.trim().is_empty() { return Err(KeysError::InvalidInput("bad key lengths")); }- Ok(IdentityState {- identity,- sign_private,- sign_public,- })+ Ok(IdentityState { identity, sign_private, sign_public }) } /// Rebuild the credential + signer pair from persisted [state].
communicate-dev/src/main/rust-mls/src/store.rs
diff --git a/communicate-dev/src/main/rust-mls/src/store.rs b/communicate-dev/src/main/rust-mls/src/store.rsindex e9eea4a255..744ae482c7 100644--- a/communicate-dev/src/main/rust-mls/src/store.rs+++ b/communicate-dev/src/main/rust-mls/src/store.rs@@ -39,10 +39,7 @@ pub struct SnapshotProvider { impl SnapshotProvider { /// Fresh provider with empty storage. pub fn fresh() -> Self {- Self {- crypto: RustCrypto::default(),- store: MemoryStorage::default(),- }+ Self { crypto: RustCrypto::default(), store: MemoryStorage::default() } } /// Restore storage from a Kotlin-persisted [snapshot]; empty = fresh.@@ -50,9 +47,7 @@ impl SnapshotProvider { let map = decode_snapshot(snapshot)?; Ok(Self { crypto: RustCrypto::default(),- store: MemoryStorage {- values: RwLock::new(map),- },+ store: MemoryStorage { values: RwLock::new(map) }, }) } @@ -91,8 +86,10 @@ fn encode_snapshot(map: &HashMap<Vec<u8>, Vec<u8>>) -> Vec<u8> { let count = map.len().min(MAX_ENTRIES) as u32; out.extend_from_slice(&count.to_be_bytes()); for (k, v) in map.iter().take(MAX_ENTRIES) {- let k = k.split_at_checked(k.len().min(MAX_ENTRY_BYTES)).map_or(k.as_slice(), |(head, _)| head);- let v = v.split_at_checked(v.len().min(MAX_ENTRY_BYTES)).map_or(v.as_slice(), |(head, _)| head);+ let k =+ k.split_at_checked(k.len().min(MAX_ENTRY_BYTES)).map_or(k.as_slice(), |(head, _)| head);+ let v =+ v.split_at_checked(v.len().min(MAX_ENTRY_BYTES)).map_or(v.as_slice(), |(head, _)| head); out.extend_from_slice(&(k.len() as u32).to_be_bytes()); out.extend_from_slice(k); out.extend_from_slice(&(v.len() as u32).to_be_bytes());@@ -116,14 +113,12 @@ fn decode_snapshot(bytes: &[u8]) -> Result<HashMap<Vec<u8>, Vec<u8>>, StoreError } let mut map = HashMap::with_capacity(count.min(64)); for _ in 0..count {- let k_len =- take_u32(&mut cur).ok_or(StoreError::InvalidSnapshot("short key"))? as usize;+ let k_len = take_u32(&mut cur).ok_or(StoreError::InvalidSnapshot("short key"))? as usize; if k_len > MAX_ENTRY_BYTES { return Err(StoreError::InvalidSnapshot("key too long")); } let k = take_bytes(&mut cur, k_len).ok_or(StoreError::InvalidSnapshot("short key"))?;- let v_len =- take_u32(&mut cur).ok_or(StoreError::InvalidSnapshot("short value"))? as usize;+ let v_len = take_u32(&mut cur).ok_or(StoreError::InvalidSnapshot("short value"))? as usize; if v_len > MAX_ENTRY_BYTES { return Err(StoreError::InvalidSnapshot("value too long")); }
communicate-dev/src/main/rust-mls/src/tests.rs
diff --git a/communicate-dev/src/main/rust-mls/src/tests.rs b/communicate-dev/src/main/rust-mls/src/tests.rsindex 0e9546e50d..734464b6c5 100644--- a/communicate-dev/src/main/rust-mls/src/tests.rs+++ b/communicate-dev/src/main/rust-mls/src/tests.rs@@ -49,8 +49,7 @@ fn closed_loop_text() -> Result<(), String> { let bob_id = keys::serialize_identity(&bob); // Bob publishes a key package (storage evolves; Kotlin would persist it).- let (store_bob, bob_kp) =- group::build_key_package(&[], &bob_id).map_err(|e| e.to_string())?;+ let (store_bob, bob_kp) = group::build_key_package(&[], &bob_id).map_err(|e| e.to_string())?; // Alice creates a group and adds Bob. let created = group::create_group(&[], &alice_id).map_err(|e| e.to_string())?;@@ -68,8 +67,7 @@ fn closed_loop_text() -> Result<(), String> { let enc = group::encrypt(&added.storage, &alice_id, &created.group_id, b"hello mls") .map_err(|e| e.to_string())?; assert_eq!(payload_kind(&enc.payload), PayloadKind::Message);- let dec =- group::decrypt(&store_bob2, &bob_gid, &enc.payload).map_err(|e| e.to_string())?;+ let dec = group::decrypt(&store_bob2, &bob_gid, &enc.payload).map_err(|e| e.to_string())?; assert!(dec.is_application); assert_eq!(dec.plaintext, b"hello mls");
communicate-dev/src/main/rust-mls/tests/mls_edges.rs
diff --git a/communicate-dev/src/main/rust-mls/tests/mls_edges.rs b/communicate-dev/src/main/rust-mls/tests/mls_edges.rsindex a1480eced4..fe6c161f79 100644--- a/communicate-dev/src/main/rust-mls/tests/mls_edges.rs+++ b/communicate-dev/src/main/rust-mls/tests/mls_edges.rs@@ -10,7 +10,9 @@ use communicate_mls::message::{payload_kind, PayloadKind}; use communicate_mls::store::SnapshotProvider; fn alice_id() -> Result<Vec<u8>, String> {- Ok(keys::serialize_identity(&keys::generate_identity("+15550001111").map_err(|e| e.to_string())?))+ Ok(keys::serialize_identity(+ &keys::generate_identity("+15550001111").map_err(|e| e.to_string())?,+ )) } fn bob_parts() -> Result<(Vec<u8>, Vec<u8>), String> {@@ -47,10 +49,11 @@ fn create_group_rejects_empty_identity_and_bad_storage() -> Result<(), String> { fn welcome_envelope_boundaries_are_rejected() -> Result<(), String> { let (store_bob, bob_id) = bob_parts()?; let alice = alice_id()?;- let (store_bob_after, bob_kp) = group::build_key_package(&store_bob, &bob_id).map_err(|e| e.to_string())?;+ let (store_bob_after, bob_kp) =+ group::build_key_package(&store_bob, &bob_id).map_err(|e| e.to_string())?; let created = group::create_group(&[], &alice).map_err(|e| e.to_string())?;- let added =- group::add_members(&created.storage, &alice, &created.group_id, &[bob_kp]).map_err(|e| e.to_string())?;+ let added = group::add_members(&created.storage, &alice, &created.group_id, &[bob_kp])+ .map_err(|e| e.to_string())?; assert_eq!(payload_kind(&added.welcome), PayloadKind::Welcome); let mut truncated = added.welcome.clone(); truncated.truncate(added.welcome.len() / 2);@@ -71,12 +74,15 @@ fn welcome_envelope_boundaries_are_rejected() -> Result<(), String> { fn message_envelope_boundaries_are_rejected() -> Result<(), String> { let (store_bob, bob_id) = bob_parts()?; let alice = alice_id()?;- let (store_bob_after, bob_kp) = group::build_key_package(&store_bob, &bob_id).map_err(|e| e.to_string())?;+ let (store_bob_after, bob_kp) =+ group::build_key_package(&store_bob, &bob_id).map_err(|e| e.to_string())?; let created = group::create_group(&[], &alice).map_err(|e| e.to_string())?;- let added =- group::add_members(&created.storage, &alice, &created.group_id, &[bob_kp]).map_err(|e| e.to_string())?;- let (_, bob_gid) = group::join_group(&store_bob_after, &added.welcome).map_err(|e| e.to_string())?;- let enc = group::encrypt(&added.storage, &alice, &created.group_id, b"ping").map_err(|e| e.to_string())?;+ let added = group::add_members(&created.storage, &alice, &created.group_id, &[bob_kp])+ .map_err(|e| e.to_string())?;+ let (_, bob_gid) =+ group::join_group(&store_bob_after, &added.welcome).map_err(|e| e.to_string())?;+ let enc = group::encrypt(&added.storage, &alice, &created.group_id, b"ping")+ .map_err(|e| e.to_string())?; assert_eq!(payload_kind(&enc.payload), PayloadKind::Message); let mut tampered = enc.payload.clone(); if let Some(last) = tampered.last_mut() {@@ -97,14 +103,16 @@ fn message_envelope_boundaries_are_rejected() -> Result<(), String> { fn removed_member_can_no_longer_decrypt() -> Result<(), String> { let (store_bob, bob_id) = bob_parts()?; let alice = alice_id()?;- let (store_bob_after, bob_kp) = group::build_key_package(&store_bob, &bob_id).map_err(|e| e.to_string())?;+ let (store_bob_after, bob_kp) =+ group::build_key_package(&store_bob, &bob_id).map_err(|e| e.to_string())?; let created = group::create_group(&[], &alice).map_err(|e| e.to_string())?;- let added =- group::add_members(&created.storage, &alice, &created.group_id, &[bob_kp]).map_err(|e| e.to_string())?;+ let added = group::add_members(&created.storage, &alice, &created.group_id, &[bob_kp])+ .map_err(|e| e.to_string())?; let (store_bob_joined, bob_gid) = group::join_group(&store_bob_after, &added.welcome).map_err(|e| e.to_string())?; let (storage_after_remove, _commit) =- group::remove_members(&added.storage, &alice, &created.group_id, &[1]).map_err(|e| e.to_string())?;+ group::remove_members(&added.storage, &alice, &created.group_id, &[1])+ .map_err(|e| e.to_string())?; assert!(group::remove_members(&added.storage, &alice, &created.group_id, &[]).is_err()); let enc = group::encrypt(&storage_after_remove, &alice, &created.group_id, b"after removal") .map_err(|e| e.to_string())?;
communicate-dev/src/main/rust/src/crypto.rs
diff --git a/communicate-dev/src/main/rust/src/crypto.rs b/communicate-dev/src/main/rust/src/crypto.rsindex 2a8e20876e..b814e01cc2 100644--- a/communicate-dev/src/main/rust/src/crypto.rs+++ b/communicate-dev/src/main/rust/src/crypto.rs@@ -68,8 +68,8 @@ pub fn hkdf(ikm: &[u8], salt: &[u8], info: &[u8], out_len: usize) -> Vec<u8> { let mut t: Vec<u8> = Vec::new(); let mut counter: u8 = 1; while out.len() < out_len {- let mut mac =- <Hmac<Sha256> as hmac::KeyInit>::new_from_slice(&prk).expect("hmac accepts any key length");+ let mut mac = <Hmac<Sha256> as hmac::KeyInit>::new_from_slice(&prk)+ .expect("hmac accepts any key length"); mac.update(&t); mac.update(info); mac.update(&[counter]);
communicate-dev/src/main/rust/src/group.rs
diff --git a/communicate-dev/src/main/rust/src/group.rs b/communicate-dev/src/main/rust/src/group.rsindex 94e4e4e5f4..6451d86b36 100644--- a/communicate-dev/src/main/rust/src/group.rs+++ b/communicate-dev/src/main/rust/src/group.rs@@ -204,22 +204,16 @@ pub fn encrypt<R: rand_core::Rng + rand_core::CryptoRng>( state: &mut SenderKeyState, plaintext: &[u8], ) -> Result<Vec<u8>> {- let signing_private = state- .signing_private- .ok_or(CryptoError("no signing key for this sender key"))?;+ let signing_private =+ state.signing_private.ok_or(CryptoError("no signing key for this sender key"))?; let mk = state.chain.message_key(); state.chain = state.chain.next(); let ciphertext = crypto::aes_cbc_encrypt(&mk.cipher_key, &mk.iv, plaintext); let mut random = [0u8; 64]; rng.fill_bytes(&mut random);- let msg = SenderKeyMessage::new(- state.key_id,- mk.iteration,- &ciphertext,- &signing_private,- &random,- );+ let msg =+ SenderKeyMessage::new(state.key_id, mk.iteration, &ciphertext, &signing_private, &random); Ok(msg.serialized) }
communicate-dev/src/main/rust/src/jni_bridge.rs
diff --git a/communicate-dev/src/main/rust/src/jni_bridge.rs b/communicate-dev/src/main/rust/src/jni_bridge.rsindex 80d6345af5..aafd8f2a31 100644--- a/communicate-dev/src/main/rust/src/jni_bridge.rs+++ b/communicate-dev/src/main/rust/src/jni_bridge.rs@@ -10,7 +10,7 @@ use crate::OsRng; use jni::objects::{JByteArray, JClass}; use jni::strings::JNIString; use jni::sys::{jboolean, jbyteArray, jint, jobjectArray};-use jni::{Env, EnvUnowned, jni_str};+use jni::{jni_str, Env, EnvUnowned}; use rand_core::Rng; use std::panic::{catch_unwind, AssertUnwindSafe}; @@ -112,10 +112,7 @@ fn generate_keypair_inner(env: &mut Env) -> jbyteArray { bytes_out(&mut *env, &out) } -fn public_from_private_inner<'a>(- env: &mut Env,- private: JByteArray<'a>,-) -> jbyteArray {+fn public_from_private_inner<'a>(env: &mut Env, private: JByteArray<'a>) -> jbyteArray { let priv_bytes = match bytes_in(&mut *env, &private) { Some(b) => b, None => {@@ -139,13 +136,14 @@ fn x25519_agreement_inner<'a>( private: JByteArray<'a>, public: JByteArray<'a>, ) -> jbyteArray {- let (priv_bytes, pub_bytes) = match (bytes_in(&mut *env, &private), bytes_in(&mut *env, &public)) {- (Some(a), Some(b)) => (a, b),- _ => {- throw_runtime(&mut *env, "private or public null");- return std::ptr::null_mut();- }- };+ let (priv_bytes, pub_bytes) =+ match (bytes_in(&mut *env, &private), bytes_in(&mut *env, &public)) {+ (Some(a), Some(b)) => (a, b),+ _ => {+ throw_runtime(&mut *env, "private or public null");+ return std::ptr::null_mut();+ }+ }; let p32 = match parse_32("private", &priv_bytes) { Ok(v) => v, Err(e) => {@@ -164,18 +162,15 @@ fn x25519_agreement_inner<'a>( bytes_out(&mut *env, &shared) } -fn sign_inner<'a>(- env: &mut Env,- private: JByteArray<'a>,- message: JByteArray<'a>,-) -> jbyteArray {- let (priv_bytes, msg_bytes) = match (bytes_in(&mut *env, &private), bytes_in(&mut *env, &message)) {- (Some(a), Some(b)) => (a, b),- _ => {- throw_runtime(&mut *env, "private or message null");- return std::ptr::null_mut();- }- };+fn sign_inner<'a>(env: &mut Env, private: JByteArray<'a>, message: JByteArray<'a>) -> jbyteArray {+ let (priv_bytes, msg_bytes) =+ match (bytes_in(&mut *env, &private), bytes_in(&mut *env, &message)) {+ (Some(a), Some(b)) => (a, b),+ _ => {+ throw_runtime(&mut *env, "private or message null");+ return std::ptr::null_mut();+ }+ }; let p32 = match parse_32("private", &priv_bytes) { Ok(v) => v, Err(e) => {
communicate-dev/src/main/rust/src/jni_bridge_tests.rs
diff --git a/communicate-dev/src/main/rust/src/jni_bridge_tests.rs b/communicate-dev/src/main/rust/src/jni_bridge_tests.rsindex 50269e2b09..220503ab1a 100644--- a/communicate-dev/src/main/rust/src/jni_bridge_tests.rs+++ b/communicate-dev/src/main/rust/src/jni_bridge_tests.rs@@ -103,9 +103,11 @@ fn keypair_agreement_sign_verify_via_bridge() { assert!(verify_inner(&mut *env, p1, m2, s1a)); let (p2, m3, s2) = (ba(&mut *env, &pub_a), ba(&mut *env, b"HELLO"), ba(&mut *env, &sig)); assert!(!verify_inner(&mut *env, p2, m3, s2));- let (p3, m4, s3) = (ba(&mut *env, &pub_a), ba(&mut *env, b"hello"), ba(&mut *env, &sig[..63]));+ let (p3, m4, s3) =+ (ba(&mut *env, &pub_a), ba(&mut *env, b"hello"), ba(&mut *env, &sig[..63])); assert!(!verify_inner(&mut *env, p3, m4, s3));- let (p4, m5, s4) = (ba(&mut *env, &pub_a[..31]), ba(&mut *env, b"hello"), ba(&mut *env, &sig));+ let (p4, m5, s4) =+ (ba(&mut *env, &pub_a[..31]), ba(&mut *env, b"hello"), ba(&mut *env, &sig)); assert!(!verify_inner(&mut *env, p4, m5, s4)); }); }@@ -219,7 +221,8 @@ fn bundle_without_one_time_prekey_via_bridge() { let bundle = |env: &mut Env, sig: &[u8], local_priv_null: bool| { let a1 = if local_priv_null { JByteArray::null() } else { ba(env, &alice_priv) };- let (a2, a4, a5, a6) = (ba(env, &alice_pub), ba(env, &spk_pub), ba(env, sig), ba(env, &bob_pub));+ let (a2, a4, a5, a6) =+ (ba(env, &alice_pub), ba(env, &spk_pub), ba(env, sig), ba(env, &bob_pub)); process_prekey_bundle_inner(env, a1, a2, 9, 7, -1, JByteArray::null(), 3, a4, a5, a6) }; let raw = bundle(&mut *env, &sig, false);@@ -282,7 +285,11 @@ fn extern_wrappers_via_jni() { } with_env(|env| { let cls = JClass::null();- let raw = Java_com_vayunmathur_communicate_data_whatsapp_e2e_RustWhatsAppCrypto_generateKeyPair(un(&*env), cls);+ let raw =+ Java_com_vayunmathur_communicate_data_whatsapp_e2e_RustWhatsAppCrypto_generateKeyPair(+ un(&*env),+ cls,+ ); let pair = read(&mut *env, raw); let (alice_priv, alice_pub) = (pair[..32].to_vec(), pair[32..].to_vec()); let (bob_priv, bob_pub) = kp();@@ -291,57 +298,131 @@ fn extern_wrappers_via_jni() { let sig = crypto::sign(&bob_priv, &crypto::serialize_public(&spk_pub), &[0x66u8; 64]); let a = ba(&mut *env, &alice_priv);- let raw = Java_com_vayunmathur_communicate_data_whatsapp_e2e_RustWhatsAppCrypto_publicFromPrivate(un(&*env), JClass::null(), a);+ let raw =+ Java_com_vayunmathur_communicate_data_whatsapp_e2e_RustWhatsAppCrypto_publicFromPrivate(+ un(&*env),+ JClass::null(),+ a,+ ); assert_eq!(read(&mut *env, raw), alice_pub); let (a1, b1) = (ba(&mut *env, &alice_priv), ba(&mut *env, &bob_pub));- let raw = Java_com_vayunmathur_communicate_data_whatsapp_e2e_RustWhatsAppCrypto_x25519Agreement(un(&*env), JClass::null(), a1, b1);+ let raw =+ Java_com_vayunmathur_communicate_data_whatsapp_e2e_RustWhatsAppCrypto_x25519Agreement(+ un(&*env),+ JClass::null(),+ a1,+ b1,+ ); assert_eq!(read(&mut *env, raw).len(), 32); let (s1, m1) = (ba(&mut *env, &alice_priv), ba(&mut *env, b"hi"));- let raw = Java_com_vayunmathur_communicate_data_whatsapp_e2e_RustWhatsAppCrypto_sign(un(&*env), JClass::null(), s1, m1);+ let raw = Java_com_vayunmathur_communicate_data_whatsapp_e2e_RustWhatsAppCrypto_sign(+ un(&*env),+ JClass::null(),+ s1,+ m1,+ ); let sig_bytes = read(&mut *env, raw);- let (p1, m2, sg) = (ba(&mut *env, &alice_pub), ba(&mut *env, b"hi"), ba(&mut *env, &sig_bytes));- assert!(Java_com_vayunmathur_communicate_data_whatsapp_e2e_RustWhatsAppCrypto_verify(un(&*env), JClass::null(), p1, m2, sg));- let (p2, m3, sg2) = (ba(&mut *env, &alice_pub), ba(&mut *env, b"bye"), ba(&mut *env, &sig_bytes));- assert!(!Java_com_vayunmathur_communicate_data_whatsapp_e2e_RustWhatsAppCrypto_verify(un(&*env), JClass::null(), p2, m3, sg2));+ let (p1, m2, sg) =+ (ba(&mut *env, &alice_pub), ba(&mut *env, b"hi"), ba(&mut *env, &sig_bytes));+ assert!(Java_com_vayunmathur_communicate_data_whatsapp_e2e_RustWhatsAppCrypto_verify(+ un(&*env),+ JClass::null(),+ p1,+ m2,+ sg+ ));+ let (p2, m3, sg2) =+ (ba(&mut *env, &alice_pub), ba(&mut *env, b"bye"), ba(&mut *env, &sig_bytes));+ assert!(!Java_com_vayunmathur_communicate_data_whatsapp_e2e_RustWhatsAppCrypto_verify(+ un(&*env),+ JClass::null(),+ p2,+ m3,+ sg2+ )); // Session establishment + conversation via the WhatsApp symbols. let (w1, w2, w3, w4, w5, w6) = (- ba(&mut *env, &alice_priv), ba(&mut *env, &alice_pub), ba(&mut *env, &opk_pub),- ba(&mut *env, &spk_pub), ba(&mut *env, &sig), ba(&mut *env, &bob_pub),+ ba(&mut *env, &alice_priv),+ ba(&mut *env, &alice_pub),+ ba(&mut *env, &opk_pub),+ ba(&mut *env, &spk_pub),+ ba(&mut *env, &sig),+ ba(&mut *env, &bob_pub), ); let raw = Java_com_vayunmathur_communicate_data_whatsapp_e2e_RustWhatsAppCrypto_processPreKeyBundle( un(&*env), JClass::null(), w1, w2, 9, 7, 11, w3, 3, w4, w5, w6, ); let alice_sess = read(&mut *env, raw); let (e1, e2) = (ba(&mut *env, &alice_sess), ba(&mut *env, b"via wrappers"));- let raw = Java_com_vayunmathur_communicate_data_whatsapp_e2e_RustWhatsAppCrypto_encrypt(un(&*env), JClass::null(), e1, e2);+ let raw = Java_com_vayunmathur_communicate_data_whatsapp_e2e_RustWhatsAppCrypto_encrypt(+ un(&*env),+ JClass::null(),+ e1,+ e2,+ ); let parts = read_elems(&mut *env, raw, 3); let alice_sess2 = parts[2].clone(); let (d1, d2, d3, d4, d5) = (- ba(&mut *env, &bob_priv), ba(&mut *env, &bob_pub), ba(&mut *env, &spk_priv),- ba(&mut *env, &opk_priv), ba(&mut *env, &parts[1]),+ ba(&mut *env, &bob_priv),+ ba(&mut *env, &bob_pub),+ ba(&mut *env, &spk_priv),+ ba(&mut *env, &opk_priv),+ ba(&mut *env, &parts[1]), ); let raw = Java_com_vayunmathur_communicate_data_whatsapp_e2e_RustWhatsAppCrypto_decryptPreKeyMessage(un(&*env), JClass::null(), d1, d2, d3, d4, d5); let bob_parts = read_elems(&mut *env, raw, 2); assert_eq!(bob_parts[0], b"via wrappers"); let (e3, e4) = (ba(&mut *env, &bob_parts[1]), ba(&mut *env, b"reply"));- let raw = Java_com_vayunmathur_communicate_data_whatsapp_e2e_RustWhatsAppCrypto_encrypt(un(&*env), JClass::null(), e3, e4);+ let raw = Java_com_vayunmathur_communicate_data_whatsapp_e2e_RustWhatsAppCrypto_encrypt(+ un(&*env),+ JClass::null(),+ e3,+ e4,+ ); let parts = read_elems(&mut *env, raw, 3); let (d6, d7) = (ba(&mut *env, &alice_sess2), ba(&mut *env, &parts[1]));- let raw = Java_com_vayunmathur_communicate_data_whatsapp_e2e_RustWhatsAppCrypto_decryptMessage(un(&*env), JClass::null(), d6, d7);+ let raw =+ Java_com_vayunmathur_communicate_data_whatsapp_e2e_RustWhatsAppCrypto_decryptMessage(+ un(&*env),+ JClass::null(),+ d6,+ d7,+ ); assert_eq!(read_elems(&mut *env, raw, 2)[0], b"reply"); // Group symbols.- let raw = Java_com_vayunmathur_communicate_data_whatsapp_e2e_RustWhatsAppCrypto_createSenderKey(un(&*env), JClass::null());+ let raw =+ Java_com_vayunmathur_communicate_data_whatsapp_e2e_RustWhatsAppCrypto_createSenderKey(+ un(&*env),+ JClass::null(),+ ); let gp = read_elems(&mut *env, raw, 2); let k1 = ba(&mut *env, &gp[1]);- let raw = Java_com_vayunmathur_communicate_data_whatsapp_e2e_RustWhatsAppCrypto_processSenderKey(un(&*env), JClass::null(), k1);+ let raw =+ Java_com_vayunmathur_communicate_data_whatsapp_e2e_RustWhatsAppCrypto_processSenderKey(+ un(&*env),+ JClass::null(),+ k1,+ ); let state_b = read(&mut *env, raw); let (g1, g2) = (ba(&mut *env, &gp[0]), ba(&mut *env, b"grp"));- let raw = Java_com_vayunmathur_communicate_data_whatsapp_e2e_RustWhatsAppCrypto_encryptGroup(un(&*env), JClass::null(), g1, g2);+ let raw =+ Java_com_vayunmathur_communicate_data_whatsapp_e2e_RustWhatsAppCrypto_encryptGroup(+ un(&*env),+ JClass::null(),+ g1,+ g2,+ ); let ct = read_elems(&mut *env, raw, 2); let (g3, g4) = (ba(&mut *env, &state_b), ba(&mut *env, &ct[0]));- let raw = Java_com_vayunmathur_communicate_data_whatsapp_e2e_RustWhatsAppCrypto_decryptGroup(un(&*env), JClass::null(), g3, g4);+ let raw =+ Java_com_vayunmathur_communicate_data_whatsapp_e2e_RustWhatsAppCrypto_decryptGroup(+ un(&*env),+ JClass::null(),+ g3,+ g4,+ ); assert_eq!(read_elems(&mut *env, raw, 2)[0], b"grp"); // Sealed sender under both class names (empty ACI round-trips).@@ -365,18 +446,54 @@ fn extern_wrappers_via_jni() { // Signal bundle entry (Kyber args ignored by the stub) + replay guard. let (q1, q2, q3, q4, q5, q6) = (- ba(&mut *env, &alice_priv), ba(&mut *env, &alice_pub), ba(&mut *env, &opk_pub),- ba(&mut *env, &spk_pub), ba(&mut *env, &sig), ba(&mut *env, &bob_pub),+ ba(&mut *env, &alice_priv),+ ba(&mut *env, &alice_pub),+ ba(&mut *env, &opk_pub),+ ba(&mut *env, &spk_pub),+ ba(&mut *env, &sig),+ ba(&mut *env, &bob_pub), ); let (q7, q8, q9) = (ba(&mut *env, &[]), ba(&mut *env, &[]), ba(&mut *env, &[]));- let raw = Java_com_vayunmathur_communicate_data_signal_e2e_RustSignalCrypto_processPreKeyBundle(- un(&*env), JClass::null(), q1, q2, 9, 7, 11, q3, 3, q4, q5, q6, 5, q7, q8, q9,- );+ let raw =+ Java_com_vayunmathur_communicate_data_signal_e2e_RustSignalCrypto_processPreKeyBundle(+ un(&*env),+ JClass::null(),+ q1,+ q2,+ 9,+ 7,+ 11,+ q3,+ 3,+ q4,+ q5,+ q6,+ 5,+ q7,+ q8,+ q9,+ ); assert!(!raw.is_null()); let bk = ba(&mut *env, b"base-key-wrapper-test");- assert!(Java_com_vayunmathur_communicate_data_signal_e2e_RustSignalCrypto_markKyberPreKeyUsed(un(&*env), JClass::null(), 4242, 777, bk));+ assert!(+ Java_com_vayunmathur_communicate_data_signal_e2e_RustSignalCrypto_markKyberPreKeyUsed(+ un(&*env),+ JClass::null(),+ 4242,+ 777,+ bk+ )+ ); let bk2 = ba(&mut *env, b"base-key-wrapper-test");- assert!(!Java_com_vayunmathur_communicate_data_signal_e2e_RustSignalCrypto_markKyberPreKeyUsed(un(&*env), JClass::null(), 4242, 777, bk2));+ assert!(+ !Java_com_vayunmathur_communicate_data_signal_e2e_RustSignalCrypto_markKyberPreKeyUsed(+ un(&*env),+ JClass::null(),+ 4242,+ 777,+ bk2+ )+ ); env.exception_clear(); }); }
communicate-dev/src/main/rust/src/lib.rs
diff --git a/communicate-dev/src/main/rust/src/lib.rs b/communicate-dev/src/main/rust/src/lib.rsindex b1e5ac005c..af5cba5d6d 100644--- a/communicate-dev/src/main/rust/src/lib.rs+++ b/communicate-dev/src/main/rust/src/lib.rs@@ -14,13 +14,13 @@ //! bytecode — see `wire.rs`). The *persisted record* format is our own, which is safe //! because the migration accepts a one-time WhatsApp re-link. -pub mod wa_binary;-pub mod wa_tokens; pub mod crypto; pub mod group; pub mod session;-pub mod wire; pub mod signal;+pub mod wa_binary;+pub mod wa_tokens;+pub mod wire; // JNI bridge must also build for the host: JVM unit tests load the host // cdylib (build/rustHostLibs) and call the same Java_* entry points. Gating
communicate-dev/src/main/rust/src/session.rs
diff --git a/communicate-dev/src/main/rust/src/session.rs b/communicate-dev/src/main/rust/src/session.rsindex 515ee2803a..97fa87ca28 100644--- a/communicate-dev/src/main/rust/src/session.rs+++ b/communicate-dev/src/main/rust/src/session.rs@@ -31,10 +31,7 @@ impl ChainKey { } pub fn next(&self) -> ChainKey {- ChainKey {- key: self.base_material(crypto::CHAIN_KEY_SEED),- index: self.index + 1,- }+ ChainKey { key: self.base_material(crypto::CHAIN_KEY_SEED), index: self.index + 1 } } pub fn message_keys(&self) -> MessageKeys {@@ -430,4 +427,4 @@ pub struct Encrypted { pub body: Vec<u8>, } -include!("session_part1.rs");\ No newline at end of file+include!("session_part1.rs");
communicate-dev/src/main/rust/src/signal.rs
diff --git a/communicate-dev/src/main/rust/src/signal.rs b/communicate-dev/src/main/rust/src/signal.rsindex 7bd4b9bfe0..e877cc78a9 100644--- a/communicate-dev/src/main/rust/src/signal.rs+++ b/communicate-dev/src/main/rust/src/signal.rs@@ -42,7 +42,9 @@ fn aes_gcm_encrypt(key: &[u8; 32], plaintext: &[u8], aad: &[u8]) -> Vec<u8> { cipher.encrypt_block(&mut enc); keystream.copy_from_slice(&enc); let take = std::cmp::min(16, plaintext.len() - pos);- for i in 0..take { out.push(plaintext[pos + i] ^ keystream[i]); }+ for i in 0..take {+ out.push(plaintext[pos + i] ^ keystream[i]);+ } pos += take; counter = counter.wrapping_add(1); }@@ -64,8 +66,12 @@ fn aes_gcm_decrypt(key: &[u8; 32], sealed: &[u8], aad: &[u8]) -> Result<Vec<u8>> use aes::cipher::Array; use aes::cipher::{BlockCipherEncrypt, KeyInit}; use aes::Aes256;- if sealed.is_empty() || sealed[0] != SEALED_VERSION { return Err(CryptoError("bad sealed version")); }- if sealed.len() < 1 + 12 + 16 { return Err(CryptoError("sealed too short")); }+ if sealed.is_empty() || sealed[0] != SEALED_VERSION {+ return Err(CryptoError("bad sealed version"));+ }+ if sealed.len() < 1 + 12 + 16 {+ return Err(CryptoError("sealed too short"));+ } let iv = &sealed[1..13]; let tag = &sealed[sealed.len() - 16..]; let ct = &sealed[13..sealed.len() - 16];@@ -74,7 +80,9 @@ fn aes_gcm_decrypt(key: &[u8; 32], sealed: &[u8], aad: &[u8]) -> Result<Vec<u8>> mac_input.extend_from_slice(aad); mac_input.extend_from_slice(ct); let expected = &crypto::hmac_sha256(key, &mac_input)[..16];- if !crypto::ct_eq(tag, expected) { return Err(CryptoError("sealed tag mismatch")); }+ if !crypto::ct_eq(tag, expected) {+ return Err(CryptoError("sealed tag mismatch"));+ } let cipher = Aes256::new(&Array::from(*key)); let mut out = Vec::with_capacity(ct.len()); let mut counter: u32 = 0;@@ -86,7 +94,9 @@ fn aes_gcm_decrypt(key: &[u8; 32], sealed: &[u8], aad: &[u8]) -> Result<Vec<u8>> let mut enc = Array::from(block); cipher.encrypt_block(&mut enc); let take = std::cmp::min(16, ct.len() - pos);- for i in 0..take { out.push(ct[pos + i] ^ enc[i]); }+ for i in 0..take {+ out.push(ct[pos + i] ^ enc[i]);+ } pos += take; counter = counter.wrapping_add(1); }@@ -122,20 +132,26 @@ static KYBER_REPLAY: Mutex<Option<KyberReplayState>> = Mutex::new(None); struct KyberReplayState { base_keys_seen: HashMap<(i32, i32), HashSet<Vec<u8>>>, }-fn replay() -> std::sync::MutexGuard<'static, Option<KyberReplayState>> { KYBER_REPLAY.lock().unwrap() }+fn replay() -> std::sync::MutexGuard<'static, Option<KyberReplayState>> {+ KYBER_REPLAY.lock().unwrap()+} /// Returns true on success, false if replay detected. Mirrors /// storage/traits.rs:129 mark_kyber_pre_key_used(kyberId, ecId, baseKey). pub fn mark_kyber_pre_key_used(kyber_id: i32, signed_ec_id: i32, base_key: &[u8]) -> bool { let mut g = replay();- if g.is_none() { *g = Some(KyberReplayState { base_keys_seen: HashMap::new() }); }+ if g.is_none() {+ *g = Some(KyberReplayState { base_keys_seen: HashMap::new() });+ } let s = g.as_mut().unwrap(); // Last-resort vs one-time is not tracked in this stub — we treat negative kyber_id as one-time for demo // Real logic needs KyberPreKeyStore to know isLastResort; caller passes appropriate id. // Stub: if kyber_id already used and base key seen, reject. let key = (kyber_id, signed_ec_id); let entry = s.base_keys_seen.entry(key).or_default();- if entry.contains(base_key) { return false; }+ if entry.contains(base_key) {+ return false;+ } entry.insert(base_key.to_vec()); true }
communicate-dev/src/main/rust/src/tests.rs
diff --git a/communicate-dev/src/main/rust/src/tests.rs b/communicate-dev/src/main/rust/src/tests.rsindex e6f6ccf303..4845afcc92 100644--- a/communicate-dev/src/main/rust/src/tests.rs+++ b/communicate-dev/src/main/rust/src/tests.rs@@ -221,8 +221,9 @@ fn crypto_hkdf_and_sign_verify_edges() { assert!(!crypto::verify(&public, b"msg", &non_canonical)); let digest = crypto::sha256(b"abc"); let expected: [u8; 32] = [- 0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea, 0x41, 0x41, 0x40, 0xde, 0x5d, 0xae, 0x22, 0x23,- 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c, 0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad,+ 0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea, 0x41, 0x41, 0x40, 0xde, 0x5d, 0xae, 0x22,+ 0x23, 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c, 0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00,+ 0x15, 0xad, ]; assert_eq!(digest, expected); let serialized = crypto::serialize_public(&public);
communicate-dev/src/main/rust/src/wa_binary.rs
diff --git a/communicate-dev/src/main/rust/src/wa_binary.rs b/communicate-dev/src/main/rust/src/wa_binary.rsindex e133062ec0..7be82548e9 100644--- a/communicate-dev/src/main/rust/src/wa_binary.rs+++ b/communicate-dev/src/main/rust/src/wa_binary.rs@@ -189,11 +189,7 @@ impl Encoder { // as `a.b.c`, and using AD_JID for agent-only or device-only forms // would synthesise the missing `:0`/`.0` on decode. Everything else // keeps the full user part in a JID_PAIR so it round-trips losslessly.- let ad_form = if server == "s.whatsapp.net" {- parse_ad_jid(user_part)- } else {- None- };+ let ad_form = if server == "s.whatsapp.net" { parse_ad_jid(user_part) } else { None }; if let Some((user, agent, device)) = ad_form { self.push(AD_JID); self.push(agent);@@ -352,4 +348,4 @@ struct Decoder<'a> { index: usize, } -include!("wa_binary_part1.rs");\ No newline at end of file+include!("wa_binary_part1.rs");
communicate-dev/src/main/rust/src/wire.rs
diff --git a/communicate-dev/src/main/rust/src/wire.rs b/communicate-dev/src/main/rust/src/wire.rsindex 2e2e48b177..372eda0095 100644--- a/communicate-dev/src/main/rust/src/wire.rs+++ b/communicate-dev/src/main/rust/src/wire.rs@@ -261,7 +261,8 @@ impl SignalMessage { return false; } let split = self.serialized.len() - MAC_LENGTH;- let expected = Self::mac(mac_key, sender_identity, receiver_identity, &self.serialized[..split]);+ let expected =+ Self::mac(mac_key, sender_identity, receiver_identity, &self.serialized[..split]); crypto::ct_eq(&self.serialized[split..], &expected) } }@@ -366,12 +367,7 @@ impl SenderKeyMessage { let sig = crypto::sign(signing_private, &out, random); out.extend_from_slice(&sig); - SenderKeyMessage {- key_id,- iteration,- ciphertext: ciphertext.to_vec(),- serialized: out,- }+ SenderKeyMessage { key_id, iteration, ciphertext: ciphertext.to_vec(), serialized: out } } pub fn parse(data: &[u8]) -> Result<SenderKeyMessage> {
communicate-dev/src/main/rust/tests/coverage_crypto_wire.rs
diff --git a/communicate-dev/src/main/rust/tests/coverage_crypto_wire.rs b/communicate-dev/src/main/rust/tests/coverage_crypto_wire.rsindex c0243425b0..a87ef77328 100644--- a/communicate-dev/src/main/rust/tests/coverage_crypto_wire.rs+++ b/communicate-dev/src/main/rust/tests/coverage_crypto_wire.rs@@ -39,19 +39,13 @@ fn hkdf_lengths_and_multiblock() { assert_eq!(&long[..32], &crypto::hkdf(b"k", &[], b"i", 32)[..]); assert_ne!(crypto::hkdf(b"k", &[], b"a", 32), crypto::hkdf(b"k", &[], b"b", 32)); assert_ne!(crypto::hkdf(b"k1", &[], b"i", 32), crypto::hkdf(b"k2", &[], b"i", 32));- assert_ne!(- crypto::hkdf(b"k", &[1u8; 32], b"i", 32),- crypto::hkdf(b"k", &[2u8; 32], b"i", 32)- );+ assert_ne!(crypto::hkdf(b"k", &[1u8; 32], b"i", 32), crypto::hkdf(b"k", &[2u8; 32], b"i", 32)); } #[test] fn hmac_matches_rfc4231_and_key_lengths() { let mac = crypto::hmac_sha256(&[0x0bu8; 20], b"Hi There");- assert_eq!(- hex(&mac),- "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7"- );+ assert_eq!(hex(&mac), "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7"); // Any key length is accepted (empty, block-size, over block-size). assert_eq!(crypto::hmac_sha256(&[], b"d").len(), 32); assert_eq!(crypto::hmac_sha256(&[7u8; 64], b"d").len(), 32);@@ -88,8 +82,14 @@ fn aes_cbc_boundaries() { } // Block-aligned input gains a full padding block; changing key/iv changes ct. let p = [5u8; 16];- assert_ne!(crypto::aes_cbc_encrypt(&key, &iv, &p), crypto::aes_cbc_encrypt(&[1u8; 32], &iv, &p));- assert_ne!(crypto::aes_cbc_encrypt(&key, &iv, &p), crypto::aes_cbc_encrypt(&key, &[2u8; 16], &p));+ assert_ne!(+ crypto::aes_cbc_encrypt(&key, &iv, &p),+ crypto::aes_cbc_encrypt(&[1u8; 32], &iv, &p)+ );+ assert_ne!(+ crypto::aes_cbc_encrypt(&key, &iv, &p),+ crypto::aes_cbc_encrypt(&key, &[2u8; 16], &p)+ ); } #[test]@@ -193,7 +193,10 @@ fn protobuf_rejects_malformed() { assert!(PbReader::new(&[0x80]).next_field().is_err(), "truncated varint"); assert!(PbReader::new(&[0x80, 0x80]).next_field().is_err()); for key in [0x0bu8, 0x0c, 0x0e, 0x0f] {- assert!(PbReader::new(&[key, 0, 0, 0, 0, 0, 0, 0, 0]).next_field().is_err(), "key {key:#x}");+ assert!(+ PbReader::new(&[key, 0, 0, 0, 0, 0, 0, 0, 0]).next_field().is_err(),+ "key {key:#x}"+ ); } assert!(PbReader::new(&[0x12, 0x7f, 1, 2]).next_field().is_err()); let mut r = PbReader::new(&[0x09, 1, 2, 3, 4, 5, 6, 7, 8]);
communicate-dev/src/main/rust/tests/coverage_session_group.rs
diff --git a/communicate-dev/src/main/rust/tests/coverage_session_group.rs b/communicate-dev/src/main/rust/tests/coverage_session_group.rsindex 7ffcaf49e5..c446fc4fdd 100644--- a/communicate-dev/src/main/rust/tests/coverage_session_group.rs+++ b/communicate-dev/src/main/rust/tests/coverage_session_group.rs@@ -115,13 +115,48 @@ fn bundle_signature_validation() { signed_pre_key_signature: sig, identity_key: bob_ik_pub, };- assert!(session::process_pre_key_bundle(&mut r, &mk_bundle(good.to_vec()), &alice_ik_priv, &alice_ik_pub, 1).is_ok());+ assert!(session::process_pre_key_bundle(+ &mut r,+ &mk_bundle(good.to_vec()),+ &alice_ik_priv,+ &alice_ik_pub,+ 1+ )+ .is_ok()); // Wrong length, garbage, and a signature over the wrong key all fail.- assert!(session::process_pre_key_bundle(&mut r, &mk_bundle(vec![0u8; 63]), &alice_ik_priv, &alice_ik_pub, 1).is_err());- assert!(session::process_pre_key_bundle(&mut r, &mk_bundle(vec![0u8; 65]), &alice_ik_priv, &alice_ik_pub, 1).is_err());- assert!(session::process_pre_key_bundle(&mut r, &mk_bundle([0u8; 64].to_vec()), &alice_ik_priv, &alice_ik_pub, 1).is_err());+ assert!(session::process_pre_key_bundle(+ &mut r,+ &mk_bundle(vec![0u8; 63]),+ &alice_ik_priv,+ &alice_ik_pub,+ 1+ )+ .is_err());+ assert!(session::process_pre_key_bundle(+ &mut r,+ &mk_bundle(vec![0u8; 65]),+ &alice_ik_priv,+ &alice_ik_pub,+ 1+ )+ .is_err());+ assert!(session::process_pre_key_bundle(+ &mut r,+ &mk_bundle([0u8; 64].to_vec()),+ &alice_ik_priv,+ &alice_ik_pub,+ 1+ )+ .is_err()); let wrong_msg = crypto::sign(&bob_ik_priv, b"not the spk", &[1u8; 64]);- assert!(session::process_pre_key_bundle(&mut r, &mk_bundle(wrong_msg.to_vec()), &alice_ik_priv, &alice_ik_pub, 1).is_err());+ assert!(session::process_pre_key_bundle(+ &mut r,+ &mk_bundle(wrong_msg.to_vec()),+ &alice_ik_priv,+ &alice_ik_pub,+ 1+ )+ .is_err()); } #[test]
communicate-dev/src/main/rust/tests/coverage_signal_binary.rs
diff --git a/communicate-dev/src/main/rust/tests/coverage_signal_binary.rs b/communicate-dev/src/main/rust/tests/coverage_signal_binary.rsindex b11e009481..e6c18dc940 100644--- a/communicate-dev/src/main/rust/tests/coverage_signal_binary.rs+++ b/communicate-dev/src/main/rust/tests/coverage_signal_binary.rs@@ -201,9 +201,8 @@ fn node_decoder_rejects_garbage_robustly() { assert!(decode_node(&[248, 1]).is_err(), "LIST_8 size without tag"); assert!(decode_node(&[249, 0]).is_err(), "truncated LIST_16"); // Every prefix of a valid encoding: Ok or Err, never panic/hang.- let node = Node::new("message")- .attr("to", "15551234567.1:[email protected]")- .attr("id", "ABC123");+ let node =+ Node::new("message").attr("to", "15551234567.1:[email protected]").attr("id", "ABC123"); let mut with_child = node.clone(); let mut child = Node::new("enc"); child.data = Some(vec![1, 2, 3, 4, 5]);
communicate-dev/src/main/rust/tests/signal_edges.rs
diff --git a/communicate-dev/src/main/rust/tests/signal_edges.rs b/communicate-dev/src/main/rust/tests/signal_edges.rsindex de631c5348..12c1726f1a 100644--- a/communicate-dev/src/main/rust/tests/signal_edges.rs+++ b/communicate-dev/src/main/rust/tests/signal_edges.rs@@ -11,8 +11,8 @@ use communicate_signal::signal::{mark_kyber_pre_key_used, sealed_sender_encrypt} use communicate_signal::signal::{sealed_sender_decrypt, sealed_sender_decrypt_any}; use communicate_signal::wa_binary::{decode_node, encode_node, Node}; use communicate_signal::wire::{- PbReader, PbValue, PbWriter, PreKeySignalMessage, SenderKeyDistributionMessage, SenderKeyMessage,- SignalMessage,+ PbReader, PbValue, PbWriter, PreKeySignalMessage, SenderKeyDistributionMessage,+ SenderKeyMessage, SignalMessage, }; fn key_pair() -> ([u8; 32], [u8; 32]) {
euicc/src/main/rust/src/activation_code.rs
diff --git a/euicc/src/main/rust/src/activation_code.rs b/euicc/src/main/rust/src/activation_code.rsindex 7f8d5ad913..e6fc4636fe 100644--- a/euicc/src/main/rust/src/activation_code.rs+++ b/euicc/src/main/rust/src/activation_code.rs@@ -41,14 +41,9 @@ pub fn parse_activation_code(code: &str) -> Result<ActivationCode, String> { if matching_id.is_empty() { return Err("Activation code is missing the matching ID".to_string()); }- if !matching_id- .bytes()- .all(|b| b.is_ascii_alphanumeric() || b == b'-')- {- return Err(- "Matching ID has an invalid format (only letters, digits and '-' are allowed)"- .to_string(),- );+ if !matching_id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') {+ return Err("Matching ID has an invalid format (only letters, digits and '-' are allowed)"+ .to_string()); } if !is_plausible_smdp(smdp) { return Err(format!("SM-DP+ address '{smdp}' does not look like a hostname"));@@ -74,9 +69,7 @@ fn is_plausible_smdp(smdp: &str) -> bool { .unwrap_or(""); !host.is_empty() && host.contains('.')- && host- .bytes()- .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'.')+ && host.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'.') && !host.starts_with('.') && !host.starts_with('-') && !host.ends_with('.')@@ -166,14 +159,8 @@ mod tests { let expected: [u8; 32] = outer.finalize().into(); assert_eq!(hash_confirmation_code("1234", &tx), expected); // Different codes / transactions differ.- assert_ne!(- hash_confirmation_code("1234", &tx),- hash_confirmation_code("4321", &tx)- );- assert_ne!(- hash_confirmation_code("1234", &tx),- hash_confirmation_code("1234", &[0x09])- );+ assert_ne!(hash_confirmation_code("1234", &tx), hash_confirmation_code("4321", &tx));+ assert_ne!(hash_confirmation_code("1234", &tx), hash_confirmation_code("1234", &[0x09])); } #[test]
euicc/src/main/rust/src/base64.rs
diff --git a/euicc/src/main/rust/src/base64.rs b/euicc/src/main/rust/src/base64.rsindex 94f86a87bd..fde550fc2a 100644--- a/euicc/src/main/rust/src/base64.rs+++ b/euicc/src/main/rust/src/base64.rs@@ -16,16 +16,8 @@ pub fn encode(data: &[u8]) -> String { let n = (b0 << 16) | (b1 << 8) | b2; out.push(ALPHABET[((n >> 18) & 0x3F) as usize] as char); out.push(ALPHABET[((n >> 12) & 0x3F) as usize] as char);- out.push(if chunk.len() > 1 {- ALPHABET[((n >> 6) & 0x3F) as usize] as char- } else {- '='- });- out.push(if chunk.len() > 2 {- ALPHABET[(n & 0x3F) as usize] as char- } else {- '='- });+ out.push(if chunk.len() > 1 { ALPHABET[((n >> 6) & 0x3F) as usize] as char } else { '=' });+ out.push(if chunk.len() > 2 { ALPHABET[(n & 0x3F) as usize] as char } else { '=' }); } out }
euicc/src/main/rust/src/download.rs
diff --git a/euicc/src/main/rust/src/download.rs b/euicc/src/main/rust/src/download.rsindex 31539714ee..39879a2509 100644--- a/euicc/src/main/rust/src/download.rs+++ b/euicc/src/main/rust/src/download.rs@@ -13,17 +13,15 @@ use jni::Env; -use crate::activation_code::{ActivationCode, hash_confirmation_code, parse_activation_code}; pub use crate::activation_code::DownloadOptions;+use crate::activation_code::{hash_confirmation_code, parse_activation_code, ActivationCode}; use crate::jni::store_data; use crate::{asn1, es10, es10b, es9p}; /// The key bytes of a CI public-key identifier field, unwrapping one DER TLV /// layer when the server sends the full TLV rather than the bare value. fn pkid_value(field: &[u8]) -> &[u8] {- asn1::parse(field)- .map(|(tlv, _)| tlv.value)- .unwrap_or(field)+ asn1::parse(field).map(|(tlv, _)| tlv.value).unwrap_or(field) } /// Whether the server's chosen CI key appears in the eUICC's verification list@@ -102,7 +100,9 @@ where } if i + 1 < total { if let Ok(probe) = es10b::parse_install_result(&last) {- if !probe.success && (probe.bpp_command_id.is_some() || probe.error_reason.is_some()) {+ if !probe.success+ && (probe.bpp_command_id.is_some() || probe.error_reason.is_some())+ { return Err(probe.message); } }@@ -129,7 +129,10 @@ fn authenticate_server_request( } /// PrepareDownload request, carrying `hashCc` when a code was supplied.-fn prepare_download_request(session: &DownloadSession, code: Option<&str>) -> Result<Vec<u8>, String> {+fn prepare_download_request(+ session: &DownloadSession,+ code: Option<&str>,+) -> Result<Vec<u8>, String> { let tx_bin = es10b::extract_transaction_id(&session.server_signed2)?; let hash = code.map(|c| hash_confirmation_code(c, &tx_bin)); let hash_ref = hash.as_ref().map(|h| &h[..]);@@ -143,15 +146,17 @@ fn prepare_download_request(session: &DownloadSession, code: Option<&str>) -> Re /// Delivery target for a notification: its own address, else the SM-DP+. fn notification_target<'a>(address: &'a str, smdp: &'a str) -> &'a str {- if address.is_empty() { smdp } else { address }+ if address.is_empty() {+ smdp+ } else {+ address+ } } fn ci_key_known(verification_list: &[String], field: &[u8]) -> bool { let raw_hex = es10::hex(field); let inner_hex = es10::hex(pkid_value(field));- verification_list- .iter()- .any(|k| *k == raw_hex || *k == inner_hex)+ verification_list.iter().any(|k| *k == raw_hex || *k == inner_hex) } /// Runs the full download for an activation code, driving the eUICC over the@@ -349,7 +354,14 @@ fn deliver_notification(env: &mut Env, smdp: &str, seq_number: i64, fallback: &[ .and_then(|resp| es10::parse_remove_result(&resp)); }; deliver_notification_with(- env, smdp, seq_number, fallback, &mut retrieve, &mut post_fallback, &mut post_at, &mut remove,+ env,+ smdp,+ seq_number,+ fallback,+ &mut retrieve,+ &mut post_fallback,+ &mut post_at,+ &mut remove, ); } @@ -440,10 +452,7 @@ mod tests { let mut seq = crate::asn1::tlv(0x80, &[0xDE, 0xAD, 0xBE, 0xEF]); seq.extend(crate::asn1::tlv(0x01, &[0x00])); let signed = crate::asn1::tlv(0x30, &seq);- assert_eq!(- es10b::extract_transaction_id(&signed).unwrap(),- vec![0xDE, 0xAD, 0xBE, 0xEF]- );+ assert_eq!(es10b::extract_transaction_id(&signed).unwrap(), vec![0xDE, 0xAD, 0xBE, 0xEF]); assert!(es10b::extract_transaction_id(&[0x30, 0x00]).is_err()); } }
euicc/src/main/rust/src/download_tests.rs
diff --git a/euicc/src/main/rust/src/download_tests.rs b/euicc/src/main/rust/src/download_tests.rsindex 335a0b3fd4..c6aaa2bbad 100644--- a/euicc/src/main/rust/src/download_tests.rs+++ b/euicc/src/main/rust/src/download_tests.rs@@ -32,11 +32,19 @@ fn notification_seq_bounds() { #[test] fn check_ci_key_rules() {- let info = crate::es10::EuiccInfo1 { svn: "2.2.0".into(), ci_pkid_verification: vec!["aabb".into()], ci_pkid_signing: vec![] };+ let info = crate::es10::EuiccInfo1 {+ svn: "2.2.0".into(),+ ci_pkid_verification: vec!["aabb".into()],+ ci_pkid_signing: vec![],+ }; assert!(check_ci_key(&info, &[0xAA, 0xBB]).is_ok()); let err = check_ci_key(&info, &[0xDD]).unwrap_err(); assert!(err.contains("unknown to this eUICC") && err.contains("aabb"), "{err}");- let empty = crate::es10::EuiccInfo1 { svn: String::new(), ci_pkid_verification: vec![], ci_pkid_signing: vec![] };+ let empty = crate::es10::EuiccInfo1 {+ svn: String::new(),+ ci_pkid_verification: vec![],+ ci_pkid_signing: vec![],+ }; assert!(check_ci_key(&empty, &[0xDD]).is_ok(), "no list never blocks"); } @@ -44,25 +52,42 @@ fn check_ci_key_rules() { fn resolve_confirmation_code_rules() { assert_eq!(resolve_confirmation_code(false, None, None).unwrap(), None); assert_eq!(resolve_confirmation_code(false, Some("1234"), Some("9999")).unwrap(), Some("1234"));- assert_eq!(resolve_confirmation_code(true, Some(""), Some("9999")).unwrap(), Some("9999"), "empty explicit falls back");+ assert_eq!(+ resolve_confirmation_code(true, Some(""), Some("9999")).unwrap(),+ Some("9999"),+ "empty explicit falls back"+ ); assert_eq!(resolve_confirmation_code(true, None, Some("9999")).unwrap(), Some("9999"));- assert!(resolve_confirmation_code(true, Some(""), None).unwrap_err().contains("confirmation code"));+ assert!(resolve_confirmation_code(true, Some(""), None)+ .unwrap_err()+ .contains("confirmation code")); assert!(resolve_confirmation_code(true, None, None).is_err()); } #[test] fn build_session_parses_metadata_and_cc() {- let ac = ActivationCode { smdp: "smdp.example.com".into(), matching_id: "M1".into(), confirmation_code_required: false };+ let ac = ActivationCode {+ smdp: "smdp.example.com".into(),+ matching_id: "M1".into(),+ confirmation_code_required: false,+ }; let mut meta_body = crate::asn1::tlv(0x91, b"Carrier"); meta_body.extend(crate::asn1::tlv(0x92, b"Plan"));- let r1 = crate::es9p::InitiateAuthResult { transaction_id: "tx-9".into(), server_signed1: vec![1], server_signature1: vec![2], euicc_ci_pkid: vec![3], server_certificate: vec![4] };+ let r1 = crate::es9p::InitiateAuthResult {+ transaction_id: "tx-9".into(),+ server_signed1: vec![1],+ server_signature1: vec![2],+ euicc_ci_pkid: vec![3],+ server_certificate: vec![4],+ }; // smdpSigned2: SEQUENCE { 80 tx, 01 FF } => cc required. let mut signed_inner = crate::asn1::tlv(0x80, &[0x01]); signed_inner.extend(crate::asn1::tlv(0x01, &[0xFF])); let r2 = crate::es9p::AuthenticateClientResult { profile_metadata: crate::asn1::tlv(0xBF25, &meta_body), smdp_signed2: crate::asn1::tlv(0x30, &signed_inner),- smdp_signature2: vec![5], smdp_certificate: vec![6],+ smdp_signature2: vec![5],+ smdp_certificate: vec![6], }; let s = build_session(ac, r1, r2, vec![0x01], &DownloadOptions::default()).unwrap(); assert_eq!(s.transaction_id, "tx-9");@@ -70,9 +95,24 @@ fn build_session_parses_metadata_and_cc() { assert_eq!(s.metadata.service_provider, "Carrier"); assert_eq!(s.metadata.profile_name, "Plan"); // Bad metadata propagates.- let r1b = crate::es9p::InitiateAuthResult { transaction_id: "t".into(), server_signed1: vec![], server_signature1: vec![], euicc_ci_pkid: vec![], server_certificate: vec![] };- let r2b = crate::es9p::AuthenticateClientResult { profile_metadata: vec![], smdp_signed2: vec![], smdp_signature2: vec![], smdp_certificate: vec![] };- let acb = ActivationCode { smdp: "s".into(), matching_id: "m".into(), confirmation_code_required: true };+ let r1b = crate::es9p::InitiateAuthResult {+ transaction_id: "t".into(),+ server_signed1: vec![],+ server_signature1: vec![],+ euicc_ci_pkid: vec![],+ server_certificate: vec![],+ };+ let r2b = crate::es9p::AuthenticateClientResult {+ profile_metadata: vec![],+ smdp_signed2: vec![],+ smdp_signature2: vec![],+ smdp_certificate: vec![],+ };+ let acb = ActivationCode {+ smdp: "s".into(),+ matching_id: "m".into(),+ confirmation_code_required: true,+ }; assert!(build_session(acb, r1b, r2b, vec![], &DownloadOptions::default()).is_err()); } @@ -82,7 +122,10 @@ fn install_segments_streaming_rules() { // Happy path: last response returned, progress sees each segment. let mut seen: Vec<usize> = Vec::new(); let mut tx = |_: &mut (), s: &[u8]| Ok::<Vec<u8>, String>(vec![s[0] + 10]);- let mut prog = |_: &mut (), d: usize, _t: usize| { seen.push(d); true };+ let mut prog = |_: &mut (), d: usize, _t: usize| {+ seen.push(d);+ true+ }; assert_eq!(install_segments(&mut (), &segs, &mut tx, &mut prog).unwrap(), vec![13]); assert_eq!(seen, vec![1, 2, 3]); // Empty segment list returns empty last response.@@ -91,17 +134,33 @@ fn install_segments_streaming_rules() { assert_eq!(install_segments(&mut (), &[], &mut tx2, &mut prog2).unwrap(), Vec::<u8>::new()); // Transmit failure names the segment. let mut tx3 = |_: &mut (), _s: &[u8]| Err::<Vec<u8>, String>("boom".into());- assert!(install_segments(&mut (), &segs, &mut tx3, &mut prog2).unwrap_err().contains("segment 1/3: boom"));+ assert!(install_segments(&mut (), &segs, &mut tx3, &mut prog2)+ .unwrap_err()+ .contains("segment 1/3: boom")); // Progress veto cancels after first segment. let mut tx4 = |_: &mut (), s: &[u8]| Ok::<Vec<u8>, String>(vec![s[0]]); let mut veto = |_: &mut (), _d: usize, _t: usize| false;- assert_eq!(install_segments(&mut (), &segs, &mut tx4, &mut veto).unwrap_err(), "Download cancelled");+ assert_eq!(+ install_segments(&mut (), &segs, &mut tx4, &mut veto).unwrap_err(),+ "Download cancelled"+ ); // Mid-stream typed BF37 error aborts; same blob as last segment does not.- let err_blob = crate::asn1::tlv(0xBF37, &crate::asn1::tlv(0xBF27, &crate::asn1::tlv(0xA2, &crate::asn1::tlv(0xA1, &crate::asn1::tlv(0x80, &[0x03])))));+ let err_blob = crate::asn1::tlv(+ 0xBF37,+ &crate::asn1::tlv(+ 0xBF27,+ &crate::asn1::tlv(0xA2, &crate::asn1::tlv(0xA1, &crate::asn1::tlv(0x80, &[0x03]))),+ ),+ ); let mut calls = 0usize;- let mut tx5 = |_: &mut (), _s: &[u8]| { calls += 1; Ok::<Vec<u8>, String>(err_blob.clone()) };+ let mut tx5 = |_: &mut (), _s: &[u8]| {+ calls += 1;+ Ok::<Vec<u8>, String>(err_blob.clone())+ }; let mut prog3 = |_: &mut (), _d: usize, _t: usize| true;- assert!(install_segments(&mut (), &segs, &mut tx5, &mut prog3).unwrap_err().contains("store_metadata2"));+ assert!(install_segments(&mut (), &segs, &mut tx5, &mut prog3)+ .unwrap_err()+ .contains("store_metadata2")); assert_eq!(calls, 1, "must abort on first segment"); let mut tx6 = |_: &mut (), _s: &[u8]| Ok::<Vec<u8>, String>(err_blob.clone()); assert_eq!(install_segments(&mut (), &segs[..1], &mut tx6, &mut prog3).unwrap(), err_blob);@@ -115,10 +174,20 @@ fn notification_target_prefers_own_address() { #[test] fn request_builders_embed_inputs() {- let r1 = crate::es9p::InitiateAuthResult { transaction_id: "tx".into(), server_signed1: vec![0x30, 0x00], server_signature1: vec![0x02], euicc_ci_pkid: vec![0x03], server_certificate: vec![0x04] };+ let r1 = crate::es9p::InitiateAuthResult {+ transaction_id: "tx".into(),+ server_signed1: vec![0x30, 0x00],+ server_signature1: vec![0x02],+ euicc_ci_pkid: vec![0x03],+ server_certificate: vec![0x04],+ }; let req = authenticate_server_request(&r1, "MATCH-1", &DownloadOptions::default()); assert!(!req.is_empty());- let with_imei = DownloadOptions { confirmation_code: None, tac: Some([1, 2, 3, 4]), imei: Some("490154203237518".into()) };+ let with_imei = DownloadOptions {+ confirmation_code: None,+ tac: Some([1, 2, 3, 4]),+ imei: Some("490154203237518".into()),+ }; assert!(!authenticate_server_request(&r1, "MATCH-1", &with_imei).is_empty()); // PrepareDownload: no code => request builds; bad signed2 => tx error. let mut s = DownloadSession::for_test("tx-prep");@@ -136,31 +205,94 @@ fn deliver_notification_with_branches() { use std::c
Diff truncated.