infra: Bump rust to match fuchsia's versions Add infra/env_setup.fish to setup env with fish (for users) Remove unused bitfield from Cargo.toml Rerun cargo fmt with new rustfmt Test: CQ Change-Id: I936b5f19542e11e1641a66238a2c611f6a6a6964 Reviewed-on: https://bluetooth-review.googlesource.com/c/bluetooth/+/4220
diff --git a/infra/cipd.ensure b/infra/cipd.ensure index 03d9b0c..47dec8a 100644 --- a/infra/cipd.ensure +++ b/infra/cipd.ensure
@@ -8,8 +8,8 @@ fuchsia/third_party/gcc/${os=mac}-amd64 git_revision:fbe5e908de76aa240bbcd2f144c156eccc863604,25558d2fc0e8b77d4c522c322012b048db4c1485 # Rust. -fuchsia/third_party/rust/host/${platform} git_revisions:afa859f8121bf2985362a2c8414dc71a825ccf2d,03b0f55d9c6319a851a60bb084faca0e32a38f2b -fuchsia/third_party/rust/target/x86_64-unknown-linux-gnu git_revisions:afa859f8121bf2985362a2c8414dc71a825ccf2d,03b0f55d9c6319a851a60bb084faca0e32a38f2b -fuchsia/third_party/rust/target/thumbv7m-none-eabi git_revisions:afa859f8121bf2985362a2c8414dc71a825ccf2d,03b0f55d9c6319a851a60bb084faca0e32a38f2b +fuchsia/third_party/rust/host/${platform} git_revisions:c26ce708de5d14682647895d2f3caf38f70b5aa6,3493720eca95cf844a8d7e58fdd12e0e5644e7d0 +fuchsia/third_party/rust/target/x86_64-unknown-linux-gnu git_revisions:c26ce708de5d14682647895d2f3caf38f70b5aa6,3493720eca95cf844a8d7e58fdd12e0e5644e7d0 +fuchsia/third_party/rust/target/thumbv7m-none-eabi git_revisions:c26ce708de5d14682647895d2f3caf38f70b5aa6,3493720eca95cf844a8d7e58fdd12e0e5644e7d0 @Subdir rust_bindgen -fuchsia/third_party/rust_bindgen/${platform} git_revision:f518815cc14a7f8c292964bb37179a1070d7e18a +fuchsia/third_party/rust_bindgen/${platform} git_revisions:6bbde80a916cd0591f452b1a061ed8f12281f277,5e63f2ce42db2c42f1d0012a3b5fa9c6113f750a-patch
diff --git a/infra/env_setup.fish b/infra/env_setup.fish new file mode 100644 index 0000000..449a049 --- /dev/null +++ b/infra/env_setup.fish
@@ -0,0 +1,15 @@ +# No "#!" line. This script should be sourced, not executed. + +set -gx INFRA (path resolve (status dirname)) + +cipd ensure -ensure-file "$INFRA/cipd.ensure" -root "$INFRA/packages" + +set -gx PATH $INFRA/packages/bin $INFRA/packages $PATH + +if test (uname -m) = "x86_64" + ln -sf $INFRA/packages/bin/x86_64-elf-gcc $INFRA/packages/bin/cc + ln -sf $INFRA/packages/bin/x86_64-elf-gcc $INFRA/packages/bin/gcc +else + ln -sf $INFRA/packages/bin/aarch64-elf-gcc $INFRA/packages/bin/cc + ln -sf $INFRA/packages/bin/aarch64-elf-gcc $INFRA/packages/bin/gcc +end
diff --git a/rust/Cargo.toml b/rust/Cargo.toml index 4fadabe..f570d40 100644 --- a/rust/Cargo.toml +++ b/rust/Cargo.toml
@@ -27,7 +27,6 @@ # Intended to match Fuchsia versions. aes = "=0.9.1" assert_matches = "1.5.0" -bitfield = "0.19.4" bitflags = "2.11.1" futures = "=0.3.34" futures-test = "=0.3.34"
diff --git a/rust/bt-ascs/src/client.rs b/rust/bt-ascs/src/client.rs index caff88c..58641d5 100644 --- a/rust/bt-ascs/src/client.rs +++ b/rust/bt-ascs/src/client.rs
@@ -522,9 +522,9 @@ qos_configurations.iter().map(|q| &q.ase_id), )?; - // TODO(b/431814103): Consider ATT MTU limits when configuring multiple ASEs. - // If the encoded request exceeds the current MTU, we may need to break it into - // multiple Control Point writes. + // TODO(b/431814103): Consider ATT MTU limits when configuring multiple + // ASEs. If the encoded request exceeds the current MTU, we may + // need to break it into multiple Control Point writes. let op = AseControlOperation::ConfigQos { qos_configurations, responses: vec![] }; self.perform_and_verify_operation(op).await @@ -949,8 +949,8 @@ ); // Let's mimic server side throwing a global invalid length error. - // (in reality this wouldn't happen because our configure codec operation was - // encoded correctly). + // (in reality this wouldn't happen because our configure codec + // operation was encoded correctly). #[rustfmt::skip] service.notify( &CONTROL_POINT_HANDLE, @@ -983,8 +983,8 @@ let client_fut = AudioStreamControlServiceClient::<FakeTypes>::create(service.clone()); let mut client = run_to_completion(client_fut).expect("client creation should succeed"); - // Pre-condition both Sink and Source endpoints to CodecConfigured with valid - // QoS constraints + // Pre-condition both Sink and Source endpoints to CodecConfigured with + // valid QoS constraints let sink_value = vec![ 0x01, // ASE ID: 1 0x01, // ASE State: Codec Configured @@ -1013,7 +1013,8 @@ ) .unwrap(); - // Request 1 (Preferred): Resolves constraints for AseId(1) from the cache + // Request 1 (Preferred): Resolves constraints for AseId(1) from the + // cache let req1 = QosConfigurationRequest::Preferred { ase_id: AseId(1), cig_id: CigId::try_from(1).unwrap(), @@ -1112,7 +1113,8 @@ let client_fut = AudioStreamControlServiceClient::<FakeTypes>::create(service.clone()); let mut client = run_to_completion(client_fut).expect("client creation should succeed"); - // Transition the sink ASE to Streaming state to test client-side validation. + // Transition the sink ASE to Streaming state to test client-side + // validation. let streaming_value = vec![ 0x01, // ASE ID: 1 0x04, // ASE State: Streaming @@ -1352,8 +1354,8 @@ }) )); - // Both endpoints in our local cache MUST be updated with the latest notified - // states! + // Both endpoints in our local cache MUST be updated with the latest + // notified states! assert_eq!( client.endpoints.sink[&SINK_ASE_HANDLE].endpoint.state, AseState::CodecConfigured @@ -1438,7 +1440,8 @@ let client_fut = AudioStreamControlServiceClient::<FakeTypes>::create(service.clone()); let mut client = run_to_completion(client_fut).expect("client creation should succeed"); - // Transition the sink ASE to Streaming state to test client-side validation. + // Transition the sink ASE to Streaming state to test client-side + // validation. let streaming_value = vec![ 0x01, // ASE ID: 1 0x04, // ASE State: Streaming @@ -1542,7 +1545,8 @@ let client_fut = AudioStreamControlServiceClient::<FakeTypes>::create(service.clone()); let mut client = run_to_completion(client_fut).expect("client creation should succeed"); - // ASE 2 (Source) is in Idle state, which is invalid for ReceiverStartReady + // ASE 2 (Source) is in Idle state, which is invalid for + // ReceiverStartReady let start_fut = client.receiver_start_ready(vec![AseId(2)]); let err = run_to_completion(start_fut).expect_err("should fail client-side validation"); @@ -1619,8 +1623,8 @@ ], ); - // Notify rejection from server due to Insufficient Resources (Response Code - // 0x0D) + // Notify rejection from server due to Insufficient Resources (Response + // Code 0x0D) #[rustfmt::skip] service.notify( &CONTROL_POINT_HANDLE, @@ -1752,7 +1756,8 @@ let client_fut = AudioStreamControlServiceClient::<FakeTypes>::create(service.clone()); let mut client = run_to_completion(client_fut).expect("client creation should succeed"); - // ASE 1 is in Idle state, which is an invalid starting state for Disable + // ASE 1 is in Idle state, which is an invalid starting state for + // Disable let disable_fut = client.disable(vec![AseId(1)]); let err = run_to_completion(disable_fut).expect_err("should fail client-side validation"); @@ -2138,7 +2143,8 @@ let client_fut = AudioStreamControlServiceClient::<FakeTypes>::create(service.clone()); let mut client = run_to_completion(client_fut).expect("client creation should succeed"); - // Source ASE is in Idle state, which is invalid starting state for Release + // Source ASE is in Idle state, which is invalid starting state for + // Release let release_fut = client.release(vec![AseId(2)]); let err = run_to_completion(release_fut).expect_err("should fail client-side validation");
diff --git a/rust/bt-ascs/src/server.rs b/rust/bt-ascs/src/server.rs index fa8b3f3..514aae8 100644 --- a/rust/bt-ascs/src/server.rs +++ b/rust/bt-ascs/src/server.rs
@@ -83,8 +83,8 @@ ) -> Poll<Option<Self::Item>> { // SAFETY: // - Wakers are Unpin - // - We re-pin the structurally pinned futures in Preparing and Published - // (service is untouched) + // - We re-pin the structurally pinned futures in Preparing and + // Published (service is untouched) // - Terminated is empty loop { match self.as_mut().project() { @@ -218,7 +218,8 @@ None => continue, Some(Err(Canceled)) => { log::warn!("Detected dropped responder!"); - // TODO: maybe figure out how to determine which AseId got canceled here + // TODO: maybe figure out how to determine which AseId got + // canceled here self.current_response_codes .push(ResponseCode::UnspecifiedError { ase_id: AseId(0x00) }); // Bail on the rest of them. @@ -844,7 +845,8 @@ unreachable!(); }; if endpoint.direction == AudioDirection::Source { - // Accept automatically, and wait for the ReceiverStopReady to send Disable + // Accept automatically, and wait for the + // ReceiverStopReady to send Disable // event. let mut endpoint = endpoint.clone(); endpoint.state = AseState::Disabling; @@ -905,8 +907,8 @@ .push(ResponseCode::InvalidAseStateMachineTransition { ase_id }); continue; } - // Automatically accept. We will automatically perform the Released operation - // on the next poll. + // Automatically accept. We will automatically perform the + // Released operation on the next poll. let mut endpoint = endpoint.clone(); endpoint.state = AseState::Releasing; endpoint.additional = AseAdditionalParameters::None; @@ -915,12 +917,13 @@ } } Self::Released { ase_id } => { - // Should only happen when we detect a link loss and are told so by the client. - // Therefore we can transition immediately. - // If there is no endpoint by that ase_id, we do nothing. + // Should only happen when we detect a link loss and are told so + // by the client. Therefore we can transition + // immediately. If there is no endpoint by that + // ase_id, we do nothing. if let Some(mut endpoint) = endpoint_map.get(&ase_id).cloned() { - // TODO(b/433287917): implement caching with either preferred or cached - // configurations + // TODO(b/433287917): implement caching with either + // preferred or cached configurations endpoint.state = AseState::Idle; endpoint.additional = AseAdditionalParameters::None; endpoints.push(endpoint);
diff --git a/rust/bt-ascs/src/tests.rs b/rust/bt-ascs/src/tests.rs index 36941fb..9242248 100644 --- a/rust/bt-ascs/src/tests.rs +++ b/rust/bt-ascs/src/tests.rs
@@ -156,8 +156,8 @@ x => panic!("Expected a CodecConfigure, got {x:?}"), }; - // Expect the write to be responded to / acknowledged and a notification from - // the CP handle and the Source ASE + // Expect the write to be responded to / acknowledged and a notification + // from the CP handle and the Source ASE match expect_service_event(&mut server_events) { FakeServerEvent::WriteResponded { value, .. } => assert!(value.is_ok()), x => panic!("Expected acknowledge of write, got {x:?}"), @@ -202,8 +202,8 @@ ascs_server: &mut Pin<Box<AudioStreamControlServiceServer<FakeTypes>>>, server_events: &mut UnboundedReceiver<FakeServerEvent>, ) -> Vec<u8> { - // Expect the write to be responded to / acknowledged and a notification from - // the CP handle and the Source ASE + // Expect the write to be responded to / acknowledged and a notification + // from the CP handle and the Source ASE match expect_service_event(server_events) { FakeServerEvent::WriteResponded { value, .. } => assert!(value.is_ok()), x => panic!("Expected acknowledge of write, got {x:?}"), @@ -386,8 +386,8 @@ // Adjust the number of ASEs codec_configure_two_ase_ids_one_bad[1] = 0x02; // This one has a bad ase_id in it - // TODO(b/518022833): adjust to find all ASE_IDs and randomly pick a non-used - // one) + // TODO(b/518022833): adjust to find all ASE_IDs and randomly pick a + // non-used one) let bad_ase_id_configure = build_codec_configure(ase_id | 0xF0); // Skip the opcode and num of ase_ids in this one codec_configure_two_ase_ids_one_bad.extend(&bad_ase_id_configure[2..]); @@ -509,7 +509,8 @@ let cp_value = expect_control_point_notified(&mut ascs_server, &mut server_events); // Opcode should match // Number_of_ASEs should be 1 - // ASE_ID is 0x00, and Reason should be 0x04 (invalid state machine transition) + // ASE_ID is 0x00, and Reason should be 0x04 (invalid state machine + // transition) assert_eq!(cp_value, &[0x02, 0x01, ase_id, 0x04, 0x00]); // And the ASE should still be in idle. @@ -803,7 +804,8 @@ let cp_value = expect_control_point_notified(&mut ascs_server, &mut server_events); // Opcode should match // Number_of_ASEs should be 1 - // ASE_ID is 0x00, and Reason should be 0x04 (invalid state machine transition) + // ASE_ID is 0x00, and Reason should be 0x04 (invalid state machine + // transition) assert_eq!(cp_value, &[0x02, 0x01, ase_id, 0x04, 0x00]); // And the ASE should still be in idle. @@ -957,8 +959,8 @@ // Number_of_ASEs should be 1 should match ASE_ID and success 0x00 assert_eq!(cp_value, &[0x04, 0x01, ase_id, 0x05, 0x00]); - // TODO: We don't do server-initiated ReceiverStart yet, so we can't proceed to - // streaming. + // TODO: We don't do server-initiated ReceiverStart yet, so we can't proceed + // to streaming. // Disable -> QosConfigured let disable = vec![0x05, 0x01, ase_id]; @@ -1007,8 +1009,8 @@ assert!(poll_server(&mut ascs_server).is_pending()); let cp_value = expect_control_point_notified(&mut ascs_server, &mut server_events); // Opcode should match - // Number_of_ASEs should be 1 should match ASE_ID and Failure for Invalid ASE - // State Transition (since we are already in QosCondfiguredj + // Number_of_ASEs should be 1 should match ASE_ID and Failure for Invalid + // ASE State Transition (since we are already in QosCondfiguredj assert_eq!(cp_value, &[0x06, 0x01, ase_id, 0x04, 0x00]); // Release -> Releasing
diff --git a/rust/bt-ascs/src/types.rs b/rust/bt-ascs/src/types.rs index ed8341f..8107a5e 100644 --- a/rust/bt-ascs/src/types.rs +++ b/rust/bt-ascs/src/types.rs
@@ -890,11 +890,12 @@ (Self::Release { ases }, consumed) } }; - // A client-initiated ASE Control operation shall also be defined as an invalid - // length operation if the total length of all parameters written by the - // client is not equal to the total length of all fixed parameters plus - // the length of any variable length parameters for that operation as - // defined in Section 5.1 through Section 5.8. + // A client-initiated ASE Control operation shall also be defined as an + // invalid length operation if the total length of all + // parameters written by the client is not equal to the total + // length of all fixed parameters plus the length of any + // variable length parameters for that operation as defined in + // Section 5.1 through Section 5.8. if (consumed + 2) != value.len() { return Err(ResponseCode::invalid_length_opcode(value[0])); } @@ -1086,7 +1087,8 @@ let try_decode_fn = |buf: &[u8]| { let ase_id = AseId::try_from(buf[0])?; let Ok(target_latency) = TargetLatency::try_from(buf[1]) else { - // TODO: unclear what to do if the target latency is out of range. + // TODO: unclear what to do if the target latency is out of + // range. return Err(ResponseCode::ConfigurationParameterValue { ase_id, issue: ResponseIssue::Invalid, @@ -2149,8 +2151,8 @@ let (res_malformed_ase, _) = ControlPointNotification::decode(malformed_bytes_ase); assert_eq!(res_malformed_ase, Err(bt_common::packet_encoding::Error::OutOfRange)); - // Case B: number_of_ases = 0xFF, but response_code is not 0x01 or 0x02 (e.g. - // Success 0x00) + // Case B: number_of_ases = 0xFF, but response_code is not 0x01 or 0x02 + // (e.g. Success 0x00) #[rustfmt::skip] let malformed_bytes_code = &[ 0x01, // Opcode
diff --git a/rust/bt-bap-unicast/src/mapping.rs b/rust/bt-bap-unicast/src/mapping.rs index 745ed63..72878ec 100644 --- a/rust/bt-bap-unicast/src/mapping.rs +++ b/rust/bt-bap-unicast/src/mapping.rs
@@ -15,8 +15,8 @@ let mut mapping = HashMap::new(); // TODO: Implement actual mapping logic based on PAC records. - // This is a skeleton implementation that returns hardcoded values if resources - // are available. + // This is a skeleton implementation that returns hardcoded values if + // resources are available. if pac_records.is_empty() { return mapping; @@ -54,7 +54,8 @@ fn test_map_capabilities_with_resources() { // Create a dummy PacRecord // We need to mock it or use a real one if easy. - // For now, we just need a non-empty slice to trigger the skeleton logic. + // For now, we just need a non-empty slice to trigger the skeleton + // logic. let pac_records = vec![PacRecord { codec_id: bt_common::core::CodecId::Assigned(bt_common::core::CodingFormat::Lc3), codec_specific_capabilities: vec![],
diff --git a/rust/bt-bap/src/types.rs b/rust/bt-bap/src/types.rs index 7f768e7..89fdf1d 100644 --- a/rust/bt-bap/src/types.rs +++ b/rust/bt-bap/src/types.rs
@@ -74,8 +74,8 @@ if buf.len() < self.encoded_len() { return Err(PacketError::BufferTooSmall); } - // Since 3-byte value is being fit into u32, we ignore the most significant - // byte. + // Since 3-byte value is being fit into u32, we ignore the most + // significant byte. buf[0..3].copy_from_slice(&self.0.to_le_bytes()[0..3]); Ok(()) } @@ -132,9 +132,10 @@ match BroadcastId::decode(&buf[0..3]) { (Ok(broadcast_id), _) => { - // According to the spec, broadcast audio announcement service data inlcudes - // broadcast id and any additional service data. We don't store any - // additional parameters, so for now we just "consume" all of data buffer + // According to the spec, broadcast audio announcement service + // data inlcudes broadcast id and any additional + // service data. We don't store any additional + // parameters, so for now we just "consume" all of data buffer // without doing anything. (Ok(Self { broadcast_id }), buf.len()) } @@ -209,8 +210,8 @@ } impl BroadcastIsochronousGroup { - // Should contain num BIS, codec id, codec specific config len, metadata len, - // and at least one BIS praram. + // Should contain num BIS, codec id, codec specific config len, metadata + // len, and at least one BIS praram. const MIN_PACKET_SIZE: usize = 1 + CodecId::BYTE_SIZE + 1 + 1 + BroadcastIsochronousStream::MIN_PACKET_SIZE; }
diff --git a/rust/bt-bass/src/client.rs b/rust/bt-bass/src/client.rs index aa29368..b74c268 100644 --- a/rust/bt-bass/src/client.rs +++ b/rust/bt-bass/src/client.rs
@@ -157,8 +157,8 @@ } let mut brs_map = HashMap::new(); for c in brs { - // Read the value of the Broadcast Recieve State at the time of discovery for - // record. + // Read the value of the Broadcast Recieve State at the time of + // discovery for record. let mut buf = vec![0; READ_CHARACTERISTIC_BUFFER_SIZE]; match c.read(&mut buf[..]).await { Ok(read_bytes) => match BroadcastReceiveState::decode(&buf[0..read_bytes]).0 { @@ -325,9 +325,9 @@ } } - // Left over metadata values are new subgroups that are to be added. New - // subgroups can only be added if the subgroup index is - // contiguous to existing subgroups. + // Left over metadata values are new subgroups that are to be added. + // New subgroups can only be added if the subgroup index + // is contiguous to existing subgroups. let mut new_big_indices: Vec<&u8> = m.keys().collect(); new_big_indices.sort(); for big_index in new_big_indices { @@ -422,8 +422,8 @@ fn setup_client() -> (BroadcastAudioScanServiceClient<FakeTypes>, FakePeerService) { let mut fake_peer_service = FakePeerService::new(); - // Add 3 Broadcast Receive State Characteristics, 1 Broadcast Audio Scan Control - // Point Characteristic, and 1 random one. + // Add 3 Broadcast Receive State Characteristics, 1 Broadcast Audio Scan + // Control Point Characteristic, and 1 random one. fake_peer_service.add_characteristic( Characteristic { handle: RECEIVE_STATE_1_HANDLE, @@ -598,8 +598,8 @@ let (mut client, mut fake_peer_service) = setup_client(); let mut event_stream = client.take_event_stream().expect("stream was created"); - // Send notification for updating BRS characteristic to indicate it's synced and - // requires broadcast code. + // Send notification for updating BRS characteristic to indicate it's + // synced and requires broadcast code. #[rustfmt::skip] fake_peer_service.add_characteristic( Characteristic { @@ -636,9 +636,9 @@ // Stream should be pending since no more notifications. assert!(event_stream.poll_next_unpin(&mut noop_cx).is_pending()); - // Send notification for updating BRS characteristic to indicate it requires - // sync info. Notification for updating the BRS characteristic value for - // characteristic with handle 3. + // Send notification for updating BRS characteristic to indicate it + // requires sync info. Notification for updating the BRS + // characteristic value for characteristic with handle 3. #[rustfmt::skip] fake_peer_service.add_characteristic( Characteristic { @@ -731,7 +731,8 @@ let (client, mut fake_peer_service) = setup_client(); // Manually update the broadcast source tracker for testing purposes. - // In practice, this would have been updated from BRS value change notification. + // In practice, this would have been updated from BRS value change + // notification. client.broadcast_sources.lock().update_state( RECEIVE_STATE_1_HANDLE, BroadcastReceiveState::NonEmpty(ReceiveState { @@ -773,7 +774,8 @@ let (client, mut fake_peer_service) = setup_client(); // Manually update the broadcast source tracker for testing purposes. - // In practice, this would have been updated from BRS value change notification. + // In practice, this would have been updated from BRS value change + // notification. client.broadcast_sources.lock().update_state( RECEIVE_STATE_1_HANDLE, BroadcastReceiveState::NonEmpty(ReceiveState { @@ -894,7 +896,8 @@ let bid = BroadcastId::try_from(0x11).expect("should not fail"); // Manually update the broadcast source tracker for testing purposes. - // In practice, this would have been updated from BRS value change notification. + // In practice, this would have been updated from BRS value change + // notification. client.broadcast_sources.lock().update_state( RECEIVE_STATE_1_HANDLE, BroadcastReceiveState::NonEmpty(ReceiveState { @@ -937,7 +940,8 @@ let (client, mut fake_peer_service) = setup_client(); // Manually update the broadcast source tracker for testing purposes. - // In practice, this would have been updated from BRS value change notification. + // In practice, this would have been updated from BRS value change + // notification. client.broadcast_sources.lock().update_state( RECEIVE_STATE_1_HANDLE, BroadcastReceiveState::NonEmpty(ReceiveState { @@ -979,8 +983,8 @@ pin_mut!(set_code_fut); let polled = set_code_fut.poll_unpin(&mut noop_cx); - // Should fail because we cannot get source id for the broadcast id since BRS - // Characteristic value wasn't updated. + // Should fail because we cannot get source id for the broadcast id + // since BRS Characteristic value wasn't updated. assert_matches!(polled, Poll::Ready(Err(_))); } }
diff --git a/rust/bt-bass/src/client/event.rs b/rust/bt-bass/src/client/event.rs index 6dd6e3f..3586568 100644 --- a/rust/bt-bass/src/client/event.rs +++ b/rust/bt-bass/src/client/event.rs
@@ -122,13 +122,14 @@ loop { if let Some(item) = self.event_queue.pop_front() { - // An error from a single stream will be reported, but the main EventStream - // will continue for other sources. + // An error from a single stream will be reported, but the main + // EventStream will continue for other sources. return Poll::Ready(Some(item)); } let Some(item) = futures::ready!(self.notification_streams.poll_next_unpin(cx)) else { - // All notification streams have been closed. Terminate the EventStream. + // All notification streams have been closed. Terminate the + // EventStream. self.terminated = true; let err = Error::EventStream(Box::new(Error::Service( ServiceError::NotificationChannelClosed(format!( @@ -138,8 +139,9 @@ return Poll::Ready(Some(Err(err))); }; - // One of the notification streams produced an error. Report it, but do not - // terminate. SelectAll will remove the faulty stream from its set. + // One of the notification streams produced an error. Report it, but + // do not terminate. SelectAll will remove the faulty + // stream from its set. let Ok(notification) = item else { let err = Error::EventStream(Box::new(Error::Gatt(item.unwrap_err()))); return Poll::Ready(Some(Err(err))); @@ -188,7 +190,8 @@ } } } - // Continue to the top of the loop to start draining the event_queue. + // Continue to the top of the loop to start draining the + // event_queue. continue; } } @@ -269,7 +272,8 @@ assert_eq!(event, Event::AddedBroadcastSource(BroadcastId::try_from(0x040302).unwrap(), PaSyncState::NoPast, EncryptionStatus::NotEncrypted)); }); - // Should be pending because no more events generated from notifications. + // Should be pending because no more events generated from + // notifications. assert!(event_streams.poll_next_unpin(&mut noop_cx).is_pending()); // Send notifications to underlying streams. @@ -293,7 +297,8 @@ let mut noop_cx = futures::task::Context::from_waker(futures::task::noop_waker_ref()); assert_matches!(event_streams.poll_next_unpin(&mut noop_cx), Poll::Ready(Some(Ok(event))) => { assert_eq!(event, Event::SyncedToPa(BroadcastId::try_from(0x040302).unwrap())) }); - // Should be pending because no more events generated from notifications. + // Should be pending because no more events generated from + // notifications. assert!(event_streams.poll_next_unpin(&mut noop_cx).is_pending()); } @@ -336,7 +341,8 @@ assert_eq!(event, Event::AddedBroadcastSource(BroadcastId::try_from(0x040302).unwrap(), PaSyncState::Synced, EncryptionStatus::NotEncrypted)); }); - // Should be pending because no more events generated from notifications. + // Should be pending because no more events generated from + // notifications. assert!(event_streams.poll_next_unpin(&mut noop_cx).is_pending()); // Send notifications to underlying streams. Ths time, send empty BRS @@ -353,7 +359,8 @@ let mut noop_cx = futures::task::Context::from_waker(futures::task::noop_waker_ref()); assert_matches!(event_streams.poll_next_unpin(&mut noop_cx), Poll::Ready(Some(Ok(event))) => { assert_eq!(event, Event::RemovedBroadcastSource(BroadcastId::try_from(0x040302).unwrap())) }); - // Should be pending because no more events generated from notifications. + // Should be pending because no more events generated from + // notifications. assert!(event_streams.poll_next_unpin(&mut noop_cx).is_pending()); }
diff --git a/rust/bt-bass/src/server.rs b/rust/bt-bass/src/server.rs index cbffdad..473921e 100644 --- a/rust/bt-bass/src/server.rs +++ b/rust/bt-bass/src/server.rs
@@ -210,8 +210,8 @@ /// Builds a [`Server`] instance after verifying required service /// characteristics. pub fn build<T: bt_gatt::ServerTypes>(self) -> Result<Server<T>, Error> { - // Per BASS v1.0 Section 3.2, there must be [1,255] Broadcast Receive State - // characteristics. + // Per BASS v1.0 Section 3.2, there must be [1,255] Broadcast Receive + // State characteristics. if self.receive_states.is_empty() { return Err(Error::MissingReceiveState); } @@ -227,8 +227,9 @@ let _ = service_def.add_characteristic(Self::build_control_point()); - // Broadcast Receive State characteristics (Read, Notify; Encryption Required). - // Handle(1) is allocated to the Control Point Characteristic. + // Broadcast Receive State characteristics (Read, Notify; Encryption + // Required). Handle(1) is allocated to the Control Point + // Characteristic. const FIRST_RECEIVE_STATE_HANDLE: Handle = Handle(2); let num_receive_states = self.receive_states.len(); let mut state = ServerState::new(num_receive_states); @@ -419,8 +420,8 @@ handle: Handle, value: &[u8], ) -> Result<ControlPointWriteResult, GattError> { - // Only the Broadcast Audio Scan Control Point characteristic can be written to - // by a client. See BASS v1.0 Section 3.3. + // Only the Broadcast Audio Scan Control Point characteristic can be + // written to by a client. See BASS v1.0 Section 3.3. if handle != CONTROL_POINT_HANDLE { return Err(GattError::WriteNotPermitted); } @@ -1055,7 +1056,8 @@ assert_eq!(source_id, 1); assert_eq!(operation, add_op); - // First notification: Initial minimal state created upon Control Point write + // First notification: Initial minimal state created upon Control Point + // write let Poll::Ready(Some(FakeServerEvent::Notified { handle, value, .. })) = event_stream.poll_unpin(&mut noop_cx) else { @@ -1080,8 +1082,8 @@ assert_eq!(handle, Handle(1)); assert!(value.is_ok()); - // 2. Upper layer client processes the event, establishes PA sync, and updates - // state + // 2. Upper layer client processes the event, establishes PA sync, and + // updates state let mut updated_state = initial_state; updated_state.pa_sync_state = PaSyncState::Synced; assert!(server.update_receive_state(updated_state).is_ok()); @@ -1377,7 +1379,8 @@ setup_test_server(vec![state]); let mut event_stream = event_receiver.next(); - // Verify slot's internal state and encoded read value have source_id = 1 + // Verify slot's internal state and encoded read value have source_id = + // 1 fake_gatt_server.incoming_read(PeerId(1), BASS_SERVICE_ID, Handle(2), 0); let _ = server.poll_next_unpin(&mut noop_cx); let Poll::Ready(Some(FakeServerEvent::ReadResponded { handle: _, value, .. })) = @@ -1505,8 +1508,8 @@ // Clear existing state in slot 1 assert!(server.clear_receive_state(1).is_ok()); - // Adding a new state should successfully reuse the cleared slot and allocate - // the next ID + // Adding a new state should successfully reuse the cleared slot and + // allocate the next ID let new_state = make_test_inner_receive_state(50); let result = server.add_receive_state(new_state); assert_eq!(result.expect("add ok"), 2); @@ -1564,18 +1567,19 @@ setup_test_server(vec![BroadcastReceiveState::NonEmpty(initial_inner.clone())]); let mut event_stream = event_receiver.next(); - // Create an invalid ReceiveState whose metadata total length exceeds 255 bytes - // (causing BigSubgroup encode to fail) + // Create an invalid ReceiveState whose metadata total length exceeds + // 255 bytes (causing BigSubgroup encode to fail) let vendor_metadata = vec![Metadata::AudioActiveState(true); 130]; let mut invalid_inner = initial_inner.clone(); invalid_inner.subgroups = vec![BigSubgroup::new(None).with_metadata(vendor_metadata)]; - // Attempting to update to invalid_inner should return a Packet encoding error + // Attempting to update to invalid_inner should return a Packet encoding + // error let result = server.update_receive_state(invalid_inner); assert_matches!(result, Err(Error::Packet(_))); - // Perform a GATT Read on Handle(2) to verify internal memory state was NOT - // mutated to invalid_state + // Perform a GATT Read on Handle(2) to verify internal memory state was + // NOT mutated to invalid_state fake_gatt_server.incoming_read(PeerId(10), BASS_SERVICE_ID, Handle(2), 0); let _ = server.poll_next_unpin(&mut noop_cx);
diff --git a/rust/bt-bass/src/types.rs b/rust/bt-bass/src/types.rs index a1c7ebe..2093c28 100644 --- a/rust/bt-bass/src/types.rs +++ b/rust/bt-bass/src/types.rs
@@ -320,7 +320,8 @@ impl Decodable for ModifySourceOperation { type Error = PacketError; - // Min size includes Source_ID, PA_Sync, PA_Interval, and Num_Subgroups params. + // Min size includes Source_ID, PA_Sync, PA_Interval, and Num_Subgroups + // params. fn decode(buf: &[u8]) -> (core::result::Result<Self, Self::Error>, usize) { if buf.len() < Self::MIN_PACKET_SIZE { return (Err(PacketError::UnexpectedDataLength), buf.len()); @@ -409,7 +410,8 @@ impl Decodable for SetBroadcastCodeOperation { type Error = PacketError; - // Min size includes Source_ID, PA_Sync, PA_Interval, and Num_Subgroups params. + // Min size includes Source_ID, PA_Sync, PA_Interval, and Num_Subgroups + // params. fn decode(buf: &[u8]) -> (core::result::Result<Self, Self::Error>, usize) { if buf.len() < Self::PACKET_SIZE { return (Err(PacketError::UnexpectedDataLength), buf.len()); @@ -470,7 +472,8 @@ impl Decodable for RemoveSourceOperation { type Error = PacketError; - // Min size includes Source_ID, PA_Sync, PA_Interval, and Num_Subgroups params. + // Min size includes Source_ID, PA_Sync, PA_Interval, and Num_Subgroups + // params. fn decode(buf: &[u8]) -> (core::result::Result<Self, Self::Error>, usize) { if buf.len() < Self::PACKET_SIZE { return (Err(PacketError::UnexpectedDataLength), buf.len()); @@ -557,9 +560,10 @@ let bit_mask = 0b1 << (bis_index - 1); if self.0 == Self::NO_PREFERENCE { - // No preference should be re-set to 0 so that all subsequent bit_mask - // operations correctly set the bits for the specified `bis_index`. - // See BASS v1.0.1 Section 3.1.1.4 Table 3.5. + // No preference should be re-set to 0 so that all subsequent + // bit_mask operations correctly set the bits for the + // specified `bis_index`. See BASS v1.0.1 Section + // 3.1.1.4 Table 3.5. self.0 = 0; } self.0 |= bit_mask; @@ -906,8 +910,8 @@ fn encoded_len(&self) -> core::primitive::usize { // Length including Source_ID, Source_Address_Type, Source_Address, - // Source_Adv_SID, Broadcast_ID, PA_Sync_State, BIG_Encryption, Bad_Code, - // Num_Subgroups and subgroup-related params. + // Source_Adv_SID, Broadcast_ID, PA_Sync_State, BIG_Encryption, + // Bad_Code, Num_Subgroups and subgroup-related params. SOURCE_ID_BYTE_SIZE + AddressType::BYTE_SIZE + Address::BYTE_SIZE @@ -952,7 +956,8 @@ } impl EncryptionStatus { - // Should at least include the BIG_Encryption enum value which is 1 byte long. + // Should at least include the BIG_Encryption enum value which is 1 byte + // long. const MIN_PACKET_SIZE: usize = 1; // Returns the u8 value that represents the status of encryption @@ -1133,8 +1138,8 @@ let mut bis_sync_default = BisSync::default(); assert_eq!(u32::from(bis_sync_default.clone()), 0xFFFFFFFF); - // An initial synchronization of no preference should correctly be set with the - // requested index. + // An initial synchronization of no preference should correctly be set + // with the requested index. bis_sync_default.synchronize_to_index(1).expect("should succeed"); assert_eq!(u32::from(bis_sync_default.clone()), 0x1); @@ -1236,7 +1241,8 @@ PeriodicAdvertisingInterval::unknown(), subgroups, ); - assert_eq!(op.encoded_len(), 31); // 16 for minimum params and params 15 for the subgroup. + assert_eq!(op.encoded_len(), 31); // 16 for minimum params and params 15 + // for the subgroup. let mut buf = vec![0u8; op.encoded_len()]; op.encode(&mut buf[..]).expect("shoud succeed"); @@ -1309,7 +1315,8 @@ PeriodicAdvertisingInterval::unknown(), subgroups, ); - assert_eq!(op.encoded_len(), 21); // 6 for minimum params and params 15 for two subgroups. + assert_eq!(op.encoded_len(), 21); // 6 for minimum params and params 15 + // for two subgroups. let mut buf = vec![0u8; op.encoded_len()]; op.encode(&mut buf[..]).expect("shoud succeed");
diff --git a/rust/bt-battery/src/monitor.rs b/rust/bt-battery/src/monitor.rs index cbe5a64..2ad33e2 100644 --- a/rust/bt-battery/src/monitor.rs +++ b/rust/bt-battery/src/monitor.rs
@@ -99,9 +99,10 @@ } let service = handle.connect().await.map_err(Error::GattLibrary)?; let monitor = BatteryMonitorClient::<T>::create(client, service).await?; - // TODO(b/335246946): This short circuits after the first valid service is - // found. Expand this to read all of the battery services to provide - // an aggregated view of the peer. + // TODO(b/335246946): This short circuits after the first valid + // service is found. Expand this to read all of the + // battery services to provide an aggregated view of the + // peer. return Ok(monitor); } Err(Error::ServiceNotFound)
diff --git a/rust/bt-battery/src/monitor/client.rs b/rust/bt-battery/src/monitor/client.rs index 29e20e4..ad3e342 100644 --- a/rust/bt-battery/src/monitor/client.rs +++ b/rust/bt-battery/src/monitor/client.rs
@@ -49,7 +49,8 @@ } impl Stream for BatteryMonitorEventStream { - // TODO(b/335259516): Update return type to accommodate other characteristics. + // TODO(b/335259516): Update return type to accommodate other + // characteristics. type Item = Result<BatteryLevel, Error>; fn poll_next( @@ -75,7 +76,8 @@ } Some(Err(e)) => { // GATT Errors are not fatal and will be relayed to the stream. - // All other errors are considered fatal and will result in stream termination. + // All other errors are considered fatal and will result in + // stream termination. if !matches!(e, GattLibraryError::Gatt(_)) { self.terminated = TerminatedState::Terminating; } @@ -129,24 +131,27 @@ where <T as bt_gatt::GattTypes>::NotificationStream: std::marker::Send, { - // All battery services must contain at least one battery level characteristic. + // All battery services must contain at least one battery level + // characteristic. let battery_level_characteristics = ServiceCharacteristic::<T>::find(&gatt_client, BATTERY_LEVEL_UUID).await?; if battery_level_characteristics.is_empty() { return Err(Error::Service(ServiceError::MissingCharacteristic)); } - // It is valid to have multiple Battery Level Characteristics. If multiple - // exist, the primary (main) characteristic has a Description field of - // "main". For now, we assume the first such characteristic is the - // primary. See BAS 1.1 Section 3.1.2.1. - // TODO(b/335246946): Check for Characteristic Presentation Format descriptor if - // multiple characteristics are present. Use this to infer the "primary". + // It is valid to have multiple Battery Level Characteristics. If + // multiple exist, the primary (main) characteristic has a + // Description field of "main". For now, we assume the first + // such characteristic is the primary. See BAS 1.1 Section + // 3.1.2.1. TODO(b/335246946): Check for Characteristic + // Presentation Format descriptor if multiple characteristics + // are present. Use this to infer the "primary". let primary_battery_level_characteristic = battery_level_characteristics.first().expect("nonempty"); let battery_level_handles: Vec<Handle> = battery_level_characteristics.iter().map(|c| *c.handle()).collect(); - // Get the current battery level of the primary Battery Level characteristic. + // Get the current battery level of the primary Battery Level + // characteristic. let (battery_level, _decoded_bytes) = { let mut buf = vec![0; READ_CHARACTERISTIC_BUFFER_SIZE]; let read_bytes = primary_battery_level_characteristic.read(&mut buf[..]).await?; @@ -166,8 +171,8 @@ .push(gatt_client.subscribe(primary_battery_level_characteristic.handle()).boxed()); notification_streams = Some(streams); } - // TODO(b/335259516): Subscribe to notifications from optional characteristics - // if they are present. + // TODO(b/335259516): Subscribe to notifications from optional + // characteristics if they are present. Ok(Self { _client, @@ -345,7 +350,8 @@ let mut notification_stream = monitor.take_event_stream().expect("contains notification stream"); - // Trying to grab it again should be handled gracefully and yield no stream. + // Trying to grab it again should be handled gracefully and yield no + // stream. assert!(monitor.take_event_stream().is_none()); let mut noop_cx = futures::task::Context::from_waker(futures::task::noop_waker_ref()); assert!(notification_stream.poll_next_unpin(&mut noop_cx).is_pending()); @@ -408,7 +414,8 @@ else { panic!("expected GATT library error"); }; - // The stream should be staged for shutdown since a fatal error was received. + // The stream should be staged for shutdown since a fatal error was + // received. let Poll::Ready(None) = notification_stream.poll_next_unpin(&mut noop_cx) else { panic!("expected notification stream termination"); }; @@ -430,8 +437,8 @@ else { panic!("expected service error"); }; - // The stream should be staged for shutdown since there are no more active - // notification streams. + // The stream should be staged for shutdown since there are no more + // active notification streams. let Poll::Ready(None) = notification_stream.poll_next_unpin(&mut noop_cx) else { panic!("expected notification stream termination"); };
diff --git a/rust/bt-battery/src/types.rs b/rust/bt-battery/src/types.rs index 9b51087..6aa7371 100644 --- a/rust/bt-battery/src/types.rs +++ b/rust/bt-battery/src/types.rs
@@ -55,7 +55,8 @@ fn decode_large_buf_success() { let large_buf = [19, 0]; // Only expect a single u8 for the level. let (parsed, parsed_size) = BatteryLevel::decode(&large_buf); - assert_eq!(parsed, Ok(BatteryLevel(19))); // Only the first byte should be read. + assert_eq!(parsed, Ok(BatteryLevel(19))); // Only the first byte should + // be read. assert_eq!(parsed_size, 1); }
diff --git a/rust/bt-broadcast-assistant/src/assistant.rs b/rust/bt-broadcast-assistant/src/assistant.rs index b75d5ef..98883db 100644 --- a/rust/bt-broadcast-assistant/src/assistant.rs +++ b/rust/bt-broadcast-assistant/src/assistant.rs
@@ -173,8 +173,8 @@ ))); } // Scan for service data with Broadcast Audio Scan Service UUID to look - // for Broadcast Sink collocated with the Scan Delegator (see BAP spec v1.0.1 - // Section 3.9.2 for details). + // for Broadcast Sink collocated with the Scan Delegator (see BAP spec + // v1.0.1 Section 3.9.2 for details). Ok(self.central.scan(&vec![Filter::HasServiceData(BROADCAST_AUDIO_SCAN_SERVICE).into()])) } @@ -350,8 +350,8 @@ ); assert!(!changed); - // 4. Merge a new broadcast source with a different SID (SID 2) for the same - // peer. + // 4. Merge a new broadcast source with a different SID (SID 2) for the + // same peer. let bid2 = BroadcastId::try_from(1002).unwrap(); let key2 = (PeerId(1001), AdvertisingSetId::try_from(2).unwrap()); let (bs, changed) = discovered.merge_broadcast_source_data(
diff --git a/rust/bt-broadcast-assistant/src/assistant/event.rs b/rust/bt-broadcast-assistant/src/assistant/event.rs index c679759..b7cf225 100644 --- a/rust/bt-broadcast-assistant/src/assistant/event.rs +++ b/rust/bt-broadcast-assistant/src/assistant/event.rs
@@ -246,10 +246,11 @@ }); } - // See if it's appropriate to establish PA sync for this broadcast source. + // See if it's appropriate to establish PA sync for this broadcast + // source. - // If we already have the endpoint data (BASE), we don't need to establish a - // sync. + // If we already have the endpoint data (BASE), we don't need to + // establish a sync. if broadcast_source.endpoint.is_some() { return None; } @@ -420,12 +421,13 @@ periodic_advertising_interval: Some(0x0100), })); - // Found broadcast source event shouldn't have been sent since braodcast source - // information isn't complete. + // Found broadcast source event shouldn't have been sent since braodcast + // source information isn't complete. let mut noop_cx = futures::task::Context::from_waker(futures::task::noop_waker_ref()); assert!(stream.poll_next_unpin(&mut noop_cx).is_pending()); - // Poll again to let the PA sync transition from Establishing to Established. + // Poll again to let the PA sync transition from Establishing to + // Established. assert!(stream.poll_next_unpin(&mut noop_cx).is_pending()); // Pretend somehow address, address type were filled out. @@ -453,8 +455,8 @@ let advertising_data = vec![AdvertisingDatum::ServiceData(BASIC_AUDIO_ANNOUNCEMENT_SERVICE, base_data)]; - // Get the fake periodic advertising sync sender that was registered when we - // polled the scan result + // Get the fake periodic advertising sync sender that was registered + // when we polled the scan result let periodic_advertising_sender = pa .get_sender(broadcast_source_pid) .expect("should have registered periodic advertising sync sender"); @@ -472,8 +474,8 @@ ))) .unwrap(); - // Expect the stream to send out broadcast source found event since information - // is complete. + // Expect the stream to send out broadcast source found event since + // information is complete. let Poll::Ready(Some(Ok(event))) = stream.poll_next_unpin(&mut noop_cx) else { panic!("should have received event"); }; @@ -485,8 +487,8 @@ assert_eq!(source.broadcast_name, Some("Test Broadcast".to_string())); }); - // Verify that the PA sync was stopped (removed from active_syncs) to conserve - // resources + // Verify that the PA sync was stopped (removed from active_syncs) to + // conserve resources assert!(stream.active_syncs.is_empty()); // Subsequent polls should be pending
diff --git a/rust/bt-common/src/core.rs b/rust/bt-common/src/core.rs index 91ec9dc..b06fb1d 100644 --- a/rust/bt-common/src/core.rs +++ b/rust/bt-common/src/core.rs
@@ -259,7 +259,8 @@ } let format = buf[0].into(); if format != CodingFormat::VendorSpecific { - // Maybe don't ignore the company and vendor id, and check if they are wrong. + // Maybe don't ignore the company and vendor id, and check if they + // are wrong. return (Ok(Self::Assigned(format)), 5); } let company_id = u16::from_le_bytes([buf[1], buf[2]]).into();
diff --git a/rust/bt-csis/src/client.rs b/rust/bt-csis/src/client.rs index 9c5adeb..80e0bc4 100644 --- a/rust/bt-csis/src/client.rs +++ b/rust/bt-csis/src/client.rs
@@ -165,8 +165,8 @@ let (lock_handle, lock_state) = lock.unzip(); if lock_handle.is_some() && rank_handle.is_none() { - // CSIS v1.1 Section 5, Table 5.1 Note C.1: Mandatory if Set Member Lock is - // supported + // CSIS v1.1 Section 5, Table 5.1 Note C.1: Mandatory if Set Member + // Lock is supported return Err(Error::MissingCharacteristic(SET_MEMBER_RANK_UUID)); } @@ -342,7 +342,10 @@ add_char(&mut service, SIRK_HANDLE, SET_IDENTITY_RESOLVING_KEY_UUID, sirk_val); add_char(&mut service, SIZE_HANDLE, COORDINATED_SET_SIZE_UUID, vec![0x02]); - add_lock_char(&mut service, LOCK_HANDLE, vec![0x01]); // 0x01 = Unlocked per CSIS v1.1 Section 5.3, Table 5.4 + add_lock_char(&mut service, LOCK_HANDLE, vec![0x01]); // 0x01 = Unlocked + // per CSIS v1.1 + // Section 5.3, + // Table 5.4 add_char(&mut service, RANK_HANDLE, SET_MEMBER_RANK_UUID, vec![0x01]); let create_fut = CoordinatedSetIdentificationServiceClient::<FakeTypes>::create(service);
diff --git a/rust/bt-gatt/src/test_utils.rs b/rust/bt-gatt/src/test_utils.rs index b767e2a..def7f62 100644 --- a/rust/bt-gatt/src/test_utils.rs +++ b/rust/bt-gatt/src/test_utils.rs
@@ -44,9 +44,10 @@ Self { inner: Arc::new(Mutex::new(Default::default())) } } - // Adds a characteristic so that it can be returned when discover/read method is - // called. - // Also triggers sending a characteristic value change notification to be sent. + // Adds a characteristic so that it can be returned when discover/read + // method is called. + // Also triggers sending a characteristic value change notification to be + // sent. pub fn add_characteristic(&mut self, char: Characteristic, value: Vec<u8>) { let mut lock = self.inner.lock(); let handle = char.handle; @@ -62,8 +63,8 @@ } } - // Sets expected characteristic value so that it can be used for validation when - // write method is called. + // Sets expected characteristic value so that it can be used for validation + // when write method is called. pub fn expect_characteristic_value(&mut self, handle: &Handle, value: Vec<u8>) { let mut lock = self.inner.lock(); let Some(char) = lock.characteristics.get_mut(handle) else {
diff --git a/rust/bt-gatt/src/tests.rs b/rust/bt-gatt/src/tests.rs index 78412ed..9f0bbd7 100644 --- a/rust/bt-gatt/src/tests.rs +++ b/rust/bt-gatt/src/tests.rs
@@ -158,8 +158,8 @@ assert!(!truncated); }); - // Read with offset equal to value length (offset = 4 == value.len()) returns 0 - // bytes read + // Read with offset equal to value length (offset = 4 == value.len()) + // returns 0 bytes read let mut read_result = fake_peer_service.read_characteristic(&Handle(0x1), 4, &mut buf[..]); let polled = read_result.poll_unpin(&mut noop_cx); assert_matches!(polled, Poll::Ready(Ok((len, truncated))) => { @@ -202,7 +202,8 @@ let fake_peer_service = setup_peer_service(); - // Write some random value without calling `expect_characteristic_value` first. + // Write some random value without calling `expect_characteristic_value` + // first. let mut write_result = fake_peer_service.write_characteristic( &Handle(0x1), WriteMode::WithoutResponse, @@ -397,7 +398,8 @@ let mut service_event_stream = local_service.publish(); - // Published shouldn't be emitted until the service is present on the server. + // Published shouldn't be emitted until the service is present on the + // server. let Poll::Ready(Some(FakeServerEvent::Published { id, definition })) = events.poll_next_unpin(&mut noop_cx) else {
diff --git a/rust/bt-mcs/src/server.rs b/rust/bt-mcs/src/server.rs index ca82faa..658631c 100644 --- a/rust/bt-mcs/src/server.rs +++ b/rust/bt-mcs/src/server.rs
@@ -165,10 +165,10 @@ /// characteristics per MCS v1.0.1 Section 3 and any configured optional /// characteristics. pub fn build_service_definition(&self) -> Result<ServiceDefinition, Error> { - // The local `ServiceId` is derived from the provided `CCID`. This is valid - // because the CCID must be unique across all MCS/GMCS instances on the - // host server. Adding a duplicate characteristic will result in an - // Error. + // The local `ServiceId` is derived from the provided `CCID`. This is + // valid because the CCID must be unique across all MCS/GMCS + // instances on the host server. Adding a duplicate + // characteristic will result in an Error. let mut service_def = ServiceDefinition::new( ServiceId::new(self.state.ccid.into()), self.service_uuid, @@ -312,8 +312,8 @@ value: &[u8], responder: W, ) -> Option<McsServerEvent> { - // Reject non-zero offsets as MCS writable characteristics do not support - // long writes. + // Reject non-zero offsets as MCS writable characteristics do not + // support long writes. if offset != 0 { responder.error(GattError::InvalidOffset); return None; @@ -365,7 +365,8 @@ return None; }; if !playing_orders.supported.contains(order.into()) { - // Unsupported playing order is ignored per MCS v1.0.1 Section 3.15.1. + // Unsupported playing order is ignored per MCS v1.0.1 + // Section 3.15.1. responder.acknowledge(); return None; } @@ -403,8 +404,8 @@ value: &[u8], responder: W, ) -> Option<McsServerEvent> { - // The Media Control Point characteristic is optional - reject all requests if - // it is not enabled on this server. + // The Media Control Point characteristic is optional - reject all + // requests if it is not enabled on this server. let Some(supported_opcodes) = self.state.supported_opcodes else { responder.error(GattError::InvalidHandle); return None; @@ -425,17 +426,17 @@ None }; - // Validate opcode decoding and server opcode support (see MCS v1.0.1 Section - // 3.18.2). + // Validate opcode decoding and server opcode support (see MCS v1.0.1 + // Section 3.18.2). let opcode = match MediaControlOpcode::decode(value) { (Ok(opcode), _) if supported_opcodes.contains((&opcode).into()) => opcode, _ => return notify_error(responder, ControlPointResultCode::OpcodeNotSupported), }; // Reject commands if the media player is inactive. - // TODO(b/540400364): The spec also technically allows the handling of the - // command if the media player supports it with no active track. Revisit - // this if needed. + // TODO(b/540400364): The spec also technically allows the handling of + // the command if the media player supports it with no active + // track. Revisit this if needed. if self.state.media_state == MediaState::Inactive { return notify_error(responder, ControlPointResultCode::MediaPlayerInactive); } @@ -457,7 +458,8 @@ match response { PendingWriteResponse::ControlPoint { peer_id, opcode, result_code } => { // Dispatches a Media Control Point GATT notification containing - // [opcode, result_code] to the peer per MCS v1.0.1 Section 3.18.2. + // [opcode, result_code] to the peer per MCS v1.0.1 Section + // 3.18.2. self.local_service.notify( &MEDIA_CONTROL_POINT_HANDLE, &[opcode.raw_opcode(), result_code.into()], @@ -493,8 +495,8 @@ ) -> Poll<Option<Self::Item>> { loop { let mut this = self.as_mut().project(); - // Drain any completed asynchronous write responses before processing new - // GATT events. + // Drain any completed asynchronous write responses before + // processing new GATT events. if let Poll::Ready(Some(response)) = this.pending_write_responses.as_mut().poll_next(cx) { if let Some(response) = response { @@ -505,8 +507,9 @@ let gatt_event = match futures::ready!(this.local_service.as_mut().poll_next(cx)) { None => { - // Continue polling until all in-flight responses have been drained before - // terminating the stream. + // Continue polling until all in-flight responses have been + // drained before terminating the + // stream. if this.pending_write_responses.is_empty() { this.local_service.as_mut().set(LocalServiceState::Terminated); return Poll::Ready(None); @@ -754,8 +757,8 @@ let _ = server1.next().poll_unpin(&mut noop_cx); assert!(server1.is_published()); - // The GATT server rejects the second server attempting to publish with the - // duplicate CCID / ServiceId. + // The GATT server rejects the second server attempting to publish with + // the duplicate CCID / ServiceId. fake_gatt_server.set_next_prepare_result(Err(bt_gatt::types::Error::AlreadyPublished( ServiceId::new(0x05), ))); @@ -950,7 +953,8 @@ // Upper layer confirms the set track position. responder.send(position); - // Server processes the confirmation, updates state, and sends notification. + // Server processes the confirmation, updates state, and sends + // notification. let _ = server.next().poll_unpin(&mut noop_cx); let FakeServerEvent::Notified { handle, value, peers, .. } = @@ -1206,8 +1210,8 @@ let peer = PeerId(1); let service_id = ServiceId::new(0x42); - // Writing ShuffleOnce when only InOrderOnce is supported is ignored per MCS - // v1.0.1 Section 3.15.1 + // Writing ShuffleOnce when only InOrderOnce is supported is ignored per + // MCS v1.0.1 Section 3.15.1 fake_gatt_server.incoming_write( peer, service_id, @@ -1304,8 +1308,8 @@ }; assert!(value.is_ok()); - // Immediate Media Control Point Notification sent with OPCODE_NOT_SUPPORTED - // (0x02) + // Immediate Media Control Point Notification sent with + // OPCODE_NOT_SUPPORTED (0x02) let FakeServerEvent::Notified { handle, value, peers, .. } = expect_service_event(&mut event_receiver) else { @@ -1343,8 +1347,8 @@ }; assert!(value.is_ok()); - // Immediate Media Control Point Notification sent with MEDIA_PLAYER_INACTIVE - // (0x03) + // Immediate Media Control Point Notification sent with + // MEDIA_PLAYER_INACTIVE (0x03) let FakeServerEvent::Notified { handle, value, peers, .. } = expect_service_event(&mut event_receiver) else { @@ -1535,7 +1539,8 @@ server.set_media_state(MediaState::Playing); server.set_supported_opcodes(SupportedOpcodes::PLAY); - // Pause is valid in spec, but not in supported_opcodes for this server instance + // Pause is valid in spec, but not in supported_opcodes for this server + // instance fake_gatt_server.incoming_write( peer, service_id, @@ -1695,8 +1700,9 @@ resp1.send(ControlPointResultCode::Success); resp2.send(ControlPointResultCode::CommandCannotBeCompleted); - // Polling the server stream drains both pending control point responses and - // issues two local service notifications in a single poll_next invocation. + // Polling the server stream drains both pending control point responses + // and issues two local service notifications in a single + // poll_next invocation. let poll_result = server.next().poll_unpin(&mut noop_cx); assert_matches!(poll_result, Poll::Pending); @@ -1761,7 +1767,8 @@ }; assert!(value.is_ok()); - // Replace local_service events stream with a custom channel and close it. + // Replace local_service events stream with a custom channel and close + // it. let (sender, receiver) = futures::channel::mpsc::unbounded(); let LocalServiceState::Published { service, .. } = std::mem::replace(&mut server.local_service, LocalServiceState::Terminated) @@ -1771,17 +1778,17 @@ server.local_service = LocalServiceState::Published { service, events: receiver }; drop(sender); - // Polling the server returns Pending because there is still an in-flight - // responder + // Polling the server returns Pending because there is still an + // in-flight responder let poll_result = server.next().poll_unpin(&mut noop_cx); assert_matches!(poll_result, Poll::Pending); // Upper layer executes command and responds with Success responder.send(ControlPointResultCode::Success); - // Polling the server dispatches the notification and drains the in-flight - // response, then terminates the stream as the GATT service event stream - // has closed. + // Polling the server dispatches the notification and drains the + // in-flight response, then terminates the stream as the GATT + // service event stream has closed. let poll_result = server.next().poll_unpin(&mut noop_cx); assert_matches!(poll_result, Poll::Ready(None)); @@ -1814,8 +1821,8 @@ let _ = server.next().poll_unpin(&mut noop_cx); expect_no_service_event(&mut event_receiver); - // Negative value represents offset from end of track per MCS v1.0.1 Section - // 3.7.1 + // Negative value represents offset from end of track per MCS v1.0.1 + // Section 3.7.1 fake_gatt_server.incoming_write( peer, service_id,
diff --git a/rust/bt-mcs/src/server/state.rs b/rust/bt-mcs/src/server/state.rs index aafa445..f802d19 100644 --- a/rust/bt-mcs/src/server/state.rs +++ b/rust/bt-mcs/src/server/state.rs
@@ -164,19 +164,20 @@ /// Calculates the instantaneous track position based on elapsed playback /// time (MCS v1.0.1 Section 3.7). pub(crate) fn current_track_position(&self) -> TrackPosition { - // Per MCS Section 3.17, an inactive player has no current track, so it is - // unavailable. + // Per MCS Section 3.17, an inactive player has no current track, so it + // is unavailable. if self.media_state == MediaState::Inactive { return TrackPosition::Unavailable; } - // Playback timing has not started since the track was initialized or loaded. + // Playback timing has not started since the track was initialized or + // loaded. let Some(updated_at) = self.position_updated_at else { return self.track_position; }; - // Playback is paused or seeking, so the position remains fixed at the current - // offset. + // Playback is paused or seeking, so the position remains fixed at the + // current offset. if self.media_state != MediaState::Playing { return self.track_position; }
diff --git a/rust/bt-pacs/src/server.rs b/rust/bt-pacs/src/server.rs index 8987e17..b2dea44 100644 --- a/rust/bt-pacs/src/server.rs +++ b/rust/bt-pacs/src/server.rs
@@ -93,8 +93,8 @@ ) -> Poll<Option<Self::Item>> { // SAFETY: // - Wakers are Unpin - // - We re-pin the structurally pinned futures in Preparing and Published - // (service is untouched) + // - We re-pin the structurally pinned futures in Preparing and + // Published (service is untouched) // - Terminated is empty loop { match self.as_mut().project() {
diff --git a/rust/bt-set-coordinator/src/types.rs b/rust/bt-set-coordinator/src/types.rs index ef479d9..329bf35 100644 --- a/rust/bt-set-coordinator/src/types.rs +++ b/rust/bt-set-coordinator/src/types.rs
@@ -99,10 +99,11 @@ use bt_gatt::central::PeerName; // Test vector from CSIS Spec v1.1 Appendix A.1 - // Given k (SIRK): 0xcd, 0xcc, 0x72, 0xdd, 0x86, 0x8c, 0xcd, 0xce, 0x22, 0xfd, - // 0xa1, 0x21, 0x09, 0x7d, 0x7d, 0x45 (LSO to MSO) Given r (prand): 0x63, - // 0xf5, 0x69 (LSO first; in MSB-first notation 0x69f563) Result hash: 0xda, - // 0x48, 0x19 (LSO first; in MSB-first notation 0x1948da) + // Given k (SIRK): 0xcd, 0xcc, 0x72, 0xdd, 0x86, 0x8c, 0xcd, 0xce, 0x22, + // 0xfd, 0xa1, 0x21, 0x09, 0x7d, 0x7d, 0x45 (LSO to MSO) Given r + // (prand): 0x63, 0xf5, 0x69 (LSO first; in MSB-first notation 0x69f563) + // Result hash: 0xda, 0x48, 0x19 (LSO first; in MSB-first notation + // 0x1948da) const SAMPLE_KEY: [u8; 16] = [ 0xcd, 0xcc, 0x72, 0xdd, 0x86, 0x8c, 0xcd, 0xce, 0x22, 0xfd, 0xa1, 0x21, 0x09, 0x7d, 0x7d, 0x45, @@ -110,7 +111,8 @@ const SAMPLE_PRAND: [u8; 3] = [0x63, 0xf5, 0x69]; const SAMPLE_HASH: [u8; 3] = [0xda, 0x48, 0x19]; - // RSI = hash || prand. In LSO first: bytes 0..3 are hash, bytes 3..6 are prand. + // RSI = hash || prand. In LSO first: bytes 0..3 are hash, bytes 3..6 are + // prand. const SAMPLE_RSI: [u8; 6] = [0xda, 0x48, 0x19, 0x63, 0xf5, 0x69]; #[test] @@ -153,7 +155,8 @@ }; assert!(set.matches_scan_result(&scan_rsi)); - // CSIS Service Data AD Type (0x16) is not an RSI and should return false + // CSIS Service Data AD Type (0x16) is not an RSI and should return + // false let scan_service_data = ScanResult { id: PeerId(2), connectable: true,
diff --git a/rust/bt-vcs/src/lib.rs b/rust/bt-vcs/src/lib.rs index 7300b3c..6fdb2aa 100644 --- a/rust/bt-vcs/src/lib.rs +++ b/rust/bt-vcs/src/lib.rs
@@ -453,8 +453,8 @@ let mut service = FakePeerService::new(); - // No services, error (check between adding each one, should be an error until - // all chars are added. + // No services, error (check between adding each one, should be an error + // until all chars are added. assert!(try_from_service(service.clone()).is_err()); service.add_characteristic(state_chr(), vec![1, 0, 1]); assert!(try_from_service(service.clone()).is_err());