linked/object.rs
1// Copyright (c) Microsoft Corporation.
2// Copyright (c) Folo authors.
3
4use crate::Family;
5
6/// Operations available on every instance of a [linked object][crate].
7///
8/// The only supported way to implement this is via [`#[linked::object]`][crate::object].
9pub trait Object: From<Family<Self>> + Sized + Clone + 'static {
10 /// The object family that the current instance is linked to.
11 ///
12 /// The returned object can be used to create additional instances linked to the same family.
13 ///
14 /// # Example
15 ///
16 /// ```
17 /// # use std::sync::{Arc, Mutex};
18 /// #
19 /// # #[linked::object]
20 /// # struct SharedResource {
21 /// # data: Arc<Mutex<String>>,
22 /// # }
23 /// #
24 /// # impl SharedResource {
25 /// # pub fn new(initial_data: String) -> Self {
26 /// # let data = Arc::new(Mutex::new(initial_data));
27 /// # linked::new!(Self {
28 /// # data: Arc::clone(&data),
29 /// # })
30 /// # }
31 /// #
32 /// # pub fn get_data(&self) -> String {
33 /// # self.data.lock().unwrap().clone()
34 /// # }
35 /// #
36 /// # pub fn set_data(&self, new_data: String) {
37 /// # *self.data.lock().unwrap() = new_data;
38 /// # }
39 /// # }
40 /// use std::thread;
41 ///
42 /// use linked::Object; // Import trait to access .family() method
43 ///
44 /// let resource = SharedResource::new("initial".to_string());
45 ///
46 /// // Get the family handle from an existing instance
47 /// let family = resource.family();
48 ///
49 /// // Use the family to create a new instance on another thread
50 /// thread::spawn(move || {
51 /// let new_resource: SharedResource = family.into();
52 ///
53 /// // This new instance shares state with the original
54 /// new_resource.set_data("updated".to_string());
55 /// })
56 /// .join()
57 /// .unwrap();
58 ///
59 /// // The original instance sees the update
60 /// assert_eq!(resource.get_data(), "updated");
61 /// ```
62 fn family(&self) -> Family<Self>;
63}