1// Copyright 2024 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4use fidl_fuchsia_sensors::ManagerControlHandle;
5use std::hash::{Hash, Hasher};
6use std::sync::atomic::AtomicUsize;
7use std::sync::atomic::Ordering::SeqCst;
89static CLIENT_ID_COUNT: AtomicUsize = AtomicUsize::new(0);
1011// TODO(375043170): Remove this when sensors have a better IPC mechanism.
12//
13// There is no way to compare control handles, so instead this helper struct will assign a unique
14// id to each new instance. This will only be used until sensors no longer need to use
15// send_on_sensor_event.
16#[derive(Debug, Clone)]
17pub struct Client {
18 id: usize,
19pub(crate) control_handle: ManagerControlHandle,
20}
2122impl Client {
23pub fn new(control_handle: ManagerControlHandle) -> Self {
24Self { id: CLIENT_ID_COUNT.fetch_add(1, SeqCst), control_handle }
25 }
26}
2728impl PartialEq for Client {
29fn eq(&self, other: &Self) -> bool {
30self.id == other.id
31 }
32}
3334impl Eq for Client {}
3536impl Hash for Client {
37fn hash<H: Hasher>(&self, state: &mut H) {
38self.id.hash(state);
39 }
40}
4142#[cfg(test)]
43mod tests {
44use super::*;
45use fidl::endpoints::*;
46use fidl_fuchsia_sensors::*;
4748#[fuchsia::test]
49async fn test_unique_client_ids() {
50let (_, stream) = create_proxy_and_stream::<ManagerMarker>();
51let client1 = Client::new(stream.control_handle().clone());
52let client2 = Client::new(stream.control_handle().clone());
53assert_ne!(client1.id, client2.id);
54// IDs should start at 0 and monotonically increase.
55assert_eq!(client1.id, 0);
56assert_eq!(client2.id, 1);
57 }
5859#[fuchsia::test]
60async fn test_client_partial_eq() {
61let (_, stream) = create_proxy_and_stream::<ManagerMarker>();
62let client1 = Client::new(stream.control_handle().clone());
63let client2 = Client::new(stream.control_handle().clone());
64assert_ne!(client1, client2);
65assert_eq!(client1, client1.clone());
66 }
67}