### Install and Use Rerun Binary Source: https://docs.rs/rerun/latest/src/rerun/lib This snippet provides commands for installing the `rerun` CLI and showing its help information. The CLI is used to start the viewer and interact with `.rrd` files. ```bash cargo install rerun --locked rerun --help ``` -------------------------------- ### Tokio Test Runtime Start Paused Configuration (Rust) Source: https://docs.rs/rerun/latest/rerun/external/re_viewer_context/external/tokio/attr Illustrates how to configure the Tokio test runtime to start with its time paused using `start_paused = true`. This feature requires the `test-util` feature to be enabled and is demonstrated with both the macro and the equivalent manual builder setup. ```rust #[tokio::test(start_paused = true)] async fn my_test() { assert!(true); } ``` ```rust #[test] fn my_test() { tokio::runtime::Builder::new_current_thread() .enable_all() .start_paused(true) .build() .unwrap() .block_on(async { assert!(true); }) } ``` -------------------------------- ### ViewportUi Method for Frame Start in Rust Source: https://docs.rs/rerun/latest/rerun/external/re_viewport/struct This Rust code snippet shows the `on_frame_start` method for the ViewportUi. This method is likely called at the beginning of each rendering frame to perform any necessary setup or updates related to the viewport's state. ```rust pub fn on_frame_start(&self, ctx: &ViewerContext<'_>) ``` -------------------------------- ### Rust Tokio Watch Channel Example Source: https://docs.rs/rerun/latest/rerun/external/re_viewer_context/external/tokio/sync/watch/struct Demonstrates a complete usage example of the `Ref` struct with Tokio's `watch` channel, including sending updates, checking for changes, and handling potential errors. ```rust use tokio::sync::watch; #[tokio::main] async fn main() { let (tx, mut rx) = watch::channel("hello"); tx.send("goodbye").unwrap(); // The sender does never consider the value as changed. assert!(!tx.borrow().has_changed()); // Drop the sender immediately, just for testing purposes. drop(tx); // Even if the sender has already been dropped... assert!(rx.has_changed().is_err()); // ...the modified value is still readable and detected as changed. assert_eq!(*rx.borrow(), "goodbye"); assert!(rx.borrow().has_changed()); // Read the changed value and mark it as seen. { let received = rx.borrow_and_update(); assert_eq!(*received, "goodbye"); assert!(received.has_changed()); // Release the read lock when leaving this scope. } // Now the value has already been marked as seen and could // never be modified again (after the sender has been dropped). assert!(!rx.borrow().has_changed()); } ``` -------------------------------- ### Rust NonZero Endianness Conversion Examples (from_be, from_le) Source: https://docs.rs/rerun/latest/rerun/external/re_renderer/external/bytemuck/__core/num/struct Provides examples for `from_be` and `from_le` methods on NonZero u8, which convert integers between big/little endian formats and the target's native endianness. These are nightly-only APIs under the `nonzero_bitwise` feature. ```rust #![feature(nonzero_bitwise)] use std::num::NonZeroU8; let n = NonZero::new(0x1Au8)?; if cfg!(target_endian = "big") { assert_eq!(NonZeroU8::from_be(n), n) } else { assert_eq!(NonZeroU8::from_be(n), n.swap_bytes()) } if cfg!(target_endian = "little") { assert_eq!(NonZeroU8::from_le(n), n) } else { assert_eq!(NonZeroU8::from_le(n), n.swap_bytes()) }; ``` -------------------------------- ### AsyncSeekExt Example: Seeking in a Tokio File Source: https://docs.rs/rerun/latest/rerun/external/re_viewer_context/external/tokio/io/trait Illustrates using the `seek` method from AsyncSeekExt with a Tokio File. This example shows how to open a file, seek to a specific byte offset, and then read data from that point. ```rust use tokio::fs::File; use tokio::io::{AsyncSeekExt, AsyncReadExt}; use std::io::SeekFrom; let mut file = File::open("foo.txt").await?; file.seek(SeekFrom::Start(6)).await?; let mut contents = vec![0u8; 10]; file.read_exact(&mut contents).await?; ``` -------------------------------- ### Rust: Querying BooleanBuffer Properties Source: https://docs.rs/rerun/latest/rerun/external/re_types_core/external/arrow/buffer/struct Provides examples of how to query information about a BooleanBuffer. This includes checking if the buffer is empty, getting its length in bits, counting the number of set bits, and retrieving the offset within the underlying buffer. These methods help in understanding the state and content of the boolean data. ```Rust use rerun::external::re_types_core::external::arrow::buffer::BooleanBuffer; let buffer = BooleanBuffer::new_set(16); // Check if the buffer is empty let is_empty = buffer.is_empty(); // false // Get the length of the buffer in bits let length_in_bits = buffer.len(); // 16 // Count the number of set bits (true values) let set_bits_count = buffer.count_set_bits(); // 16 // Get the offset of this BooleanBuffer in bits within its underlying Buffer let offset_in_bits = buffer.offset(); // 0 (for newly created buffers) ``` -------------------------------- ### Get and Set XKB Device Info (Rust) Source: https://docs.rs/rerun/latest/rerun/external/re_renderer/external/smallvec/alloc/sync/struct Functions to obtain detailed information about an XKB device and to modify button actions and LED info. The get function allows selection of specific features, while the set function applies changes to button actions and LEDs. ```Rust fn xkb_get_device_info(&self, device_spec: u16, wanted: XIFeature, all_buttons: bool, first_button: u8, n_buttons: u8, led_class: LedClass, led_id: A) -> Result, ConnectionError> where A: Into { // implementation omitted } fn xkb_set_device_info<'c, 'input>(&'c self, device_spec: u16, first_btn: u8, change: XIFeature, btn_actions: &'input [Action], leds: &'input [DeviceLedInfo]) -> Result, ConnectionError> { // implementation omitted } ``` -------------------------------- ### GET /websites/rs_rerun with Options Source: https://docs.rs/rerun/latest/rerun/external/re_renderer/external/smallvec/alloc/sync/struct Performs a GET request with specified options to retrieve object data. ```APIDOC ## GET /websites/rs_rerun with Options ### Description Perform a get request with options to retrieve object data. ### Method GET ### Endpoint /websites/rs_rerun ### Parameters #### Path Parameters - **location** (Path) - Required - The path to the object to retrieve. #### Query Parameters - **options** (GetOptions) - Required - Options to customize the GET request. ### Response #### Success Response (200) - **GetResult** (Object) - The retrieved object data and metadata. #### Response Example ```json { "data": "...", "metadata": { ... } } ``` ``` -------------------------------- ### Rust Downcast Example Source: https://docs.rs/rerun/latest/rerun/external/re_viewer_context/external/tokio/sync/watch/struct Demonstrates the use of `downcast` to convert a `Box` back to a concrete type. ```rust impl Downcast for T where T: Any, { fn into_any(self: Box) -> Box { self } } ``` -------------------------------- ### Arc Partial Comparison Example Source: https://docs.rs/rerun/latest/rerun/external/re_renderer/external/smallvec/alloc/sync/struct Provides an example of partial comparison between `Arc` instances using `partial_cmp`. This method returns an `Option` based on the comparison of the wrapped values. ```rust use std::sync::Arc; use std::cmp::Ordering; let five = Arc::new(5); assert_eq!(Some(Ordering::Less), five.partial_cmp(&Arc::new(6))); ``` -------------------------------- ### GET /websites/rs_rerun/list Source: https://docs.rs/rerun/latest/rerun/external/re_renderer/external/smallvec/alloc/sync/struct Lists all objects with an optional prefix. ```APIDOC ## GET /websites/rs_rerun/list ### Description List all the objects with the given prefix. ### Method GET ### Endpoint /websites/rs_rerun/list ### Parameters #### Query Parameters - **prefix** (Path) - Optional - A prefix to filter the list of objects. ### Response #### Success Response (200) - **Stream** (Stream) - A stream of object metadata. #### Response Example (Stream of object metadata) ``` -------------------------------- ### XKB Extension Initialization Source: https://docs.rs/rerun/latest/rerun/external/re_renderer/external/smallvec/alloc/sync/struct Initializes the XKB extension and negotiates version. ```APIDOC ## fn xkb_use_extension( &self, wanted_major: u16, wanted_minor: u16, ) -> Result, ConnectionError> ### Description Initializes the XKB extension, requesting a specific major and minor version. ### Method N/A (Internal function) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) Cookie with UseExtensionReply #### Response Example None ``` -------------------------------- ### GET /slice/iter Source: https://docs.rs/rerun/latest/rerun/external/re_types/datatypes/struct Returns an iterator over the slice. The iterator yields all items from start to end. ```APIDOC ## GET /slice/iter ### Description Returns an iterator over the slice. The iterator yields all items from start to end. ### Method GET ### Endpoint /slice/iter ### Parameters #### Response #### Success Response (200) - **result** (Iter<'_, T>) - Iterator over slice elements #### Response Example ``` let x = &[1, 2, 4]; let mut iterator = x.iter(); assert_eq!(iterator.next(), Some(&1)); assert_eq!(iterator.next(), Some(&2)); assert_eq!(iterator.next(), Some(&4)); assert_eq!(iterator.next(), None); ``` ``` -------------------------------- ### Create and Accept TCP Connections with Tokio TcpListener Source: https://docs.rs/rerun/latest/rerun/external/re_viewer_context/external/tokio/net/struct Demonstrates how to bind a TcpListener to an address and continuously accept incoming connections in a loop. Each accepted connection is processed asynchronously. ```rust use tokio::net::TcpListener; use std::io; async fn process_socket(socket: T) { // do work with socket here } #[tokio::main] async fn main() -> io::Result<()> { let listener = TcpListener::bind("127.0.0.1:8080").await?; loop { let (socket, _) = listener.accept().await?; process_socket(socket).await; } } ``` -------------------------------- ### Consume Array to Get Diagonal Source: https://docs.rs/rerun/latest/rerun/external/re_types/external/ndarray/prelude/struct Consumes the array and returns its diagonal elements as a one-dimensional array. This operation transfers ownership of the data. ```rust pub fn into_diag(self) -> ArrayBase> ``` -------------------------------- ### Initialize XKB Extension Source: https://docs.rs/rerun/latest/rerun/external/re_renderer/external/smallvec/alloc/sync/struct Initializes the XKB (X Keyboard Extension) extension. This function is required to use other XKB functions. It takes the desired major and minor version numbers for the extension. It returns a Cookie for a UseExtensionReply. ```rust fn xkb_use_extension( &self, wanted_major: u16, wanted_minor: u16, ) -> Result, ConnectionError> ``` -------------------------------- ### Get Mutable Diagonal View Source: https://docs.rs/rerun/latest/rerun/external/re_types/external/ndarray/prelude/struct Returns a mutable read-write view over the diagonal elements of the array. This operation requires the array's data to implement the `DataMut` trait. ```rust pub fn diag_mut(&mut self) -> ArrayBase, Dim<[usize; 1]>> where S: DataMut, ``` -------------------------------- ### ViewClassRegistry: Context and Visualizer System Operations Source: https://docs.rs/rerun/latest/rerun/external/re_viewer_context/struct This snippet details methods for executing context systems and instantiating visualizer systems. It allows running static context systems for specified views and provides a way to create new collections for viewers and visualizers. Instantiating a visualizer system is also supported. ```rust use std::collections::HashMap; use std::hash::BuildHasherDefault; impl ViewClassRegistry { // Runs the static execution method for each context system once for each view that needs it. pub fn run_static_context_systems_for_views( &self, viewer_ctx: &ViewerContext<'_>, view_classes: impl Iterator, ) -> HashMap, BuildHasherDefault>> // Creates a new context collection for a given view class identifier. pub fn new_context_collection( &self, view_class_identifier: ViewClassIdentifier, ) -> ViewContextCollection // Creates a new visualizer collection for a given view class identifier. pub fn new_visualizer_collection( &self, view_class_identifier: ViewClassIdentifier, ) -> VisualizerCollection // Instantiates a visualizer system by its identifier. pub fn instantiate_visualizer( &self, visualizer_identifier: ViewSystemIdentifier, ) -> Option> } ``` -------------------------------- ### Get mutable reference to last element (Rust) Source: https://docs.rs/rerun/latest/rerun/external/re_types/external/ndarray/prelude/struct The last_mut method provides a mutable reference to the last element, allowing modification. Returns None when the array has no elements. ```rust use ndarray::Array3; let mut a = Array3::::zeros([3, 4, 2]); *a.last_mut().unwrap() = 42.; assert_eq!(a[[2, 3, 1]], 42.); let mut b = Array3::::zeros([3, 0, 5]); assert_eq!(b_mut(), None); ``` -------------------------------- ### Rust NonZero unsigned_abs Example Source: https://docs.rs/rerun/latest/rerun/external/re_renderer/external/bytemuck/__core/num/struct Demonstrates the use of `unsigned_abs()` on NonZero integers to get their absolute value as an unsigned integer. It shows how positive and negative values, including the minimum value, are converted. ```Rust let u_pos = NonZero::new(1u128)?; let i_pos = NonZero::new(1i128)?; let i_neg = NonZero::new(-1i128)?; let i_min = NonZero::new(i128::MIN)?; let u_max = NonZero::new(u128::MAX / 2 + 1)?; assert_eq!(u_pos, i_pos.unsigned_abs()); assert_eq!(u_pos, i_neg.unsigned_abs()); assert_eq!(u_max, i_min.unsigned_abs()); ``` -------------------------------- ### Policy Combinators Source: https://docs.rs/rerun/latest/rerun/grpc_server/struct Methods for combining policies. ```APIDOC ## PolicyExt for T ### Description Provides extension methods for combining policies. ### Method #### `and(self, other: P) -> And` Creates a new `Policy` that returns `Action::Follow` only if both `self` and `other` policies return `Action::Follow`. Requires `T: Policy` and `P: Policy`. ``` -------------------------------- ### Rust NonZero leading_zeros Example Source: https://docs.rs/rerun/latest/rerun/external/re_renderer/external/bytemuck/__core/num/struct Provides an example of the `leading_zeros` method for `NonZero`, which returns the count of leading zero bits in the binary representation. This method can be more efficient than the standard integer type's equivalent. ```rust let n = NonZero::::new(-1isize)?; assert_eq!(n.leading_zeros(), 0); ``` -------------------------------- ### Get Transposed View of ndarray Array Source: https://docs.rs/rerun/latest/rerun/external/re_types/external/ndarray/prelude/struct Returns a transposed view of the ndarray. This is a shorthand for calling `.view().reversed_axes()`. It provides efficient access to the transposed data without copying. ```rust # // This is a placeholder for the t method, no direct code example provided in source. # fn main() { # use ndarray::arr2; # let a = arr2(&[[1, 2], [3, 4]]); # let transposed_view = a.t(); # // Example assertion (conceptual, actual usage might differ based on context) # // assert_eq!(transposed_view.shape(), &[2, 2]); # } ``` -------------------------------- ### Tokio MPSC Channel: Capacity and Reservation Example Source: https://docs.rs/rerun/latest/rerun/external/re_viewer_context/external/tokio/sync/mpsc/struct Demonstrates the usage of tokio's mpsc channel, focusing on current capacity, reserving capacity, sending, and receiving messages. It shows how channel capacity changes dynamically with operations. ```rust use tokio::sync::mpsc; #[tokio::main] async fn main() { let (tx, mut rx) = mpsc::channel::<()>(5); assert_eq!(tx.capacity(), 5); // Making a reservation drops the capacity by one. let permit = tx.reserve().await.unwrap(); assert_eq!(tx.capacity(), 4); // Sending and receiving a message increases the capacity by one. permit.send(()); rx.recv().await.unwrap(); assert_eq!(tx.capacity(), 5); } ``` -------------------------------- ### Get first element of ndarray array (Rust) Source: https://docs.rs/rerun/latest/rerun/external/re_types/external/ndarray/prelude/struct The first method returns an immutable reference to the first element of an array, or None if the array is empty. It works for any Data array. ```rust use ndarray::Array3; mut a = Array3::::zeros([3, 4, 2]); a[[0, 0, 0]] = 42.; assert_eq!(a.first(), Some(&42.)); let b = Array3::::zeros([3, 0, 5]); assert_eq!(b.first(), None); ``` -------------------------------- ### Create And Policy Source: https://docs.rs/rerun/latest/rerun/external/re_viewer_context/external/tokio/io/unix/struct Creates a new policy that returns `Action::Follow` only if both input policies return `Action::Follow`. This combines two policies using a logical AND operation. It requires two policies with the same generic parameters. ```Rust fn and(self, other: P) -> And where T: Policy, P: Policy{ // Implementation details } ``` -------------------------------- ### Bind Tokio TcpListener to an Address Source: https://docs.rs/rerun/latest/rerun/external/re_viewer_context/external/tokio/net/struct Shows how to create a new TcpListener bound to a specified IP address and port. This is the initial step for setting up a server to listen for incoming connections. ```rust use tokio::net::TcpListener; use std::io; #[tokio::main] async fn main() -> io::Result<()> { let listener = TcpListener::bind("127.0.0.1:2345").await?; // use the listener Ok(()) } ``` -------------------------------- ### element_offset() - Gets the index of an element reference Source: https://docs.rs/rerun/latest/rerun/external/re_types/datatypes/struct The `element_offset` method returns the index corresponding to a reference to an element within the slice. It uses pointer arithmetic and does not compare elements. Returns `None` if the element reference is not at the start of an element. ```APIDOC ## element_offset ### Description Returns the index that an element reference points to. Returns `None` if `element` does not point to the start of an element within the slice. This method is useful for extending slice iterators like `slice::split`. Note that this uses pointer arithmetic and **does not compare elements**. To find the index of an element via comparison, use `.iter().position()` instead. Panics if `T` is zero-sized. ### Method GET ### Endpoint `slice::element_offset()` ### Parameters #### Query Parameters - **element** (&T) - Required - A reference to the element whose index is to be found. ### Request Example ```json { "example": "No request body for this method. Element reference is passed as an argument." } ``` ### Response #### Success Response (200) - **Option** - `Some(index)` if the element reference points to the start of an element, `None` otherwise. #### Response Example ```json { "example": {"Some": 2} } ``` ``` -------------------------------- ### Type Conversions Source: https://docs.rs/rerun/latest/rerun/grpc_server/struct Documentation for different type conversion traits and their methods. ```APIDOC ## Into for T ### Description Converts a type `T` into another type `U` where `U` implements `From`. ### Method #### `into(self) -> U` Calls `U::from(self)`. The conversion logic is defined by the `From for U` implementation. ``` ```APIDOC ## IntoEither for T ### Description Provides methods to convert a type into an `Either` variant. ### Methods #### `into_either(self, into_left: bool) -> Either` Converts `self` into a `Left` variant if `into_left` is `true`, otherwise into a `Right` variant. ``` ```APIDOC ## IntoRequest for T ### Description Wraps a message type `T` into a `tonic::Request`. ### Method #### `into_request(self) -> Request` Wraps the input message `T` in a `tonic::Request`. ``` ```APIDOC ## LosslessTryInto for Src ### Description Performs a lossless conversion from `Src` to `Dst`, returning an `Option`. ### Method #### `lossless_try_into(self) -> Option` Performs the conversion, returning `Some(Dst)` on success or `None` if the conversion fails. ``` ```APIDOC ## LossyInto for Src ### Description Performs a lossy conversion from `Src` to `Dst`. ### Method #### `lossy_into(self) -> Dst` Performs the conversion. This conversion may involve data loss. ``` ```APIDOC ## OverflowingCast for T ### Description Provides methods for casting a value of type `T` to `Dst` with overflow detection. ### Method #### `overflowing_as(self) -> (Dst, bool)` Casts the value, returning the cast value and a boolean indicating if an overflow occurred. ``` ```APIDOC ## OverflowingCastFrom for Dst ### Description Provides methods for casting a value from `Src` to `Dst` with overflow detection. ### Method #### `overflowing_cast_from(src: Src) -> (Dst, bool)` Casts the source value, returning the cast value and a boolean indicating if an overflow occurred. ``` -------------------------------- ### BiLevel Color Map Example Source: https://docs.rs/rerun/latest/rerun/external/re_types/external/image/imageops/colorops/struct Demonstrates how to use the BiLevel color map for palletizing a grayscale image. It shows the creation of a gradient image, its mapping through BiLevel, and assertion against an expected black and white output. ```rust use image::imageops::colorops::{index_colors, BiLevel, ColorMap}; use image::{ImageBuffer, Luma}; let (w, h) = (16, 16); // Create an image with a smooth horizontal gradient from black (0) to white (255). let gray = ImageBuffer::from_fn(w, h, |x, y| -> Luma { [(255 * x / w) as u8].into() }); // Mapping the gray image through the `BiLevel` filter should map gray pixels less than half // intensity (127) to black (0), and anything greater to white (255). let cmap = BiLevel; let palletized = index_colors(&gray, &cmap); let mapped = ImageBuffer::from_fn(w, h, |x, y| { let p = palletized.get_pixel(x, y); cmap.lookup(p.0[0] as usize) .expect("indexed color out-of-range") }); // Create an black and white image of expected output. let bw = ImageBuffer::from_fn(w, h, |x, y| -> Luma { if x <= (w / 2) { [0].into() } else { [255].into() } }); assert_eq!(mapped, bw); ``` -------------------------------- ### Get Number of Columns in 2D ndarray Source: https://docs.rs/rerun/latest/rerun/external/re_types/external/ndarray/prelude/struct Returns the number of columns (length of Axis(1)) in a 2D ndarray. This is equivalent to calling `len_of(Axis(1))` or accessing the second dimension of the array's shape tuple. ```rust use ndarray::{array, Axis}; let array = array![[1., 2.], [3., 4.], [5., 6.]]; assert_eq!(array.ncols(), 2); let (m, n) = array.dim(); assert_eq!(n, array.ncols()); assert_eq!(n, array.len_of(Axis(1))); ``` -------------------------------- ### Get Number of Rows in 2D ndarray Source: https://docs.rs/rerun/latest/rerun/external/re_types/external/ndarray/prelude/struct Returns the number of rows (length of Axis(0)) in a 2D ndarray. This is equivalent to calling `len_of(Axis(0))` or accessing the first dimension of the array's shape tuple. ```rust use ndarray::{array, Axis}; let array = array![[1., 2.], [3., 4.], [5., 6.]]; assert_eq!(array.nrows(), 3); let (m, n) = array.dim(); assert_eq!(m, array.nrows()); assert_eq!(m, array.len_of(Axis(0))); ``` -------------------------------- ### Pointer Mapping Source: https://docs.rs/rerun/latest/rerun/external/re_renderer/external/smallvec/alloc/sync/struct Functions for getting and setting the pointer button mapping. ```APIDOC ## fn set_pointer_mapping<'c, 'input>( &'c self, map: &'input [u8], ) -> Result, ConnectionError> ### Description Sets the pointer button mapping. ### Method N/A (Internal function) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) Cookie with SetPointerMappingReply #### Response Example None ``` ```APIDOC ## fn get_pointer_mapping( &self, ) -> Result, ConnectionError> ### Description Gets the current pointer button mapping. ### Method N/A (Internal function) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) Cookie with GetPointerMappingReply #### Response Example None ``` -------------------------------- ### Get Mutable Pointer to Array Data Source: https://docs.rs/rerun/latest/rerun/external/re_types/external/ndarray/prelude/struct Returns a mutable raw pointer to the first element of the array. This method attempts to ensure unique data ownership. If the data implements `DataMut`, it is guaranteed to be uniquely held upon return. ```rust pub fn as_mut_ptr(&mut self) -> *mut A where S: RawDataMut, ``` -------------------------------- ### Add text with custom format Source: https://docs.rs/rerun/latest/rerun/external/re_ui/syntax_highlighting/struct Creates a new SyntaxHighlightedBuilder with the provided text and custom format. This consumes the current builder and returns a new one with the added text. ```rust pub fn with_format( self, text: &str, format: TextFormat, ) -> SyntaxHighlightedBuilder ``` -------------------------------- ### Rust NonZero rotate_left Example Source: https://docs.rs/rerun/latest/rerun/external/re_renderer/external/bytemuck/__core/num/struct Example of using the `rotate_left` method on a NonZero u8. This method shifts bits to the left, wrapping truncated bits to the end. It requires the `nonzero_bitwise` feature and is a nightly-only API. ```rust #![feature(nonzero_bitwise)] let n = NonZero::new(0x82u8)?; let m = NonZero::new(0xa)?; assert_eq!(n.rotate_left(2), m); ``` -------------------------------- ### Creating Zeroed Option Instances Source: https://docs.rs/rerun/latest/rerun/external/re_renderer/external/bytemuck/__core/prelude/v1/enum These `new_zeroed` function implementations for `Option M>` create new instances initialized with zeroed bytes. They require `Self: Sized` and cover function pointers with varying argument counts. ```rust impl FromZeros for Option M> { fn new_zeroed() -> Self { // Creates an instance of `Self` from zeroed bytes. } } ``` ```rust impl FromZeros for Option M> { fn new_zeroed() -> Self { // Creates an instance of `Self` from zeroed bytes. } } ``` ```rust impl FromZeros for Option M> { fn new_zeroed() -> Self { // Creates an instance of `Self` from zeroed bytes. } } ``` ```rust impl FromZeros for Option M> { fn new_zeroed() -> Self { // Creates an instance of `Self` from zeroed bytes. } } ``` ```rust impl FromZeros for Option M> { fn new_zeroed() -> Self { // Creates an instance of `Self` from zeroed bytes. } } ``` ```rust impl FromZeros for Option M> { fn new_zeroed() -> Self { // Creates an instance of `Self` from zeroed bytes. } } ``` ```rust impl FromZeros for Option M> { fn new_zeroed() -> Self { // Creates an instance of `Self` from zeroed bytes. } } ``` ```rust impl FromZeros for Option M> { fn new_zeroed() -> Self { // Creates an instance of `Self` from zeroed bytes. } } ``` -------------------------------- ### Get Diagonal View Source: https://docs.rs/rerun/latest/rerun/external/re_types/external/ndarray/prelude/struct Returns a view of the diagonal elements of the array. The diagonal is defined by elements where all indices are equal (e.g., (0,0,..0), (1,1,..1)). This operation requires the array to implement the `Data` trait. ```rust pub fn diag(&self) -> ArrayBase, Dim<[usize; 1]>> where S: Data, ``` -------------------------------- ### Current Thread Tokio Test Runtime Configuration (Rust) Source: https://docs.rs/rerun/latest/rerun/external/re_viewer_context/external/tokio/attr Demonstrates the default single-threaded runtime for `#[tokio::test]`, where each test gets its own current-thread runtime. This section also shows the equivalent manual setup using `tokio::runtime::Builder::new_current_thread()`. ```rust #[tokio::test] async fn my_test() { assert!(true); } ``` ```rust #[test] fn my_test() { tokio::runtime::Builder::new_current_thread() .enable_all() .build() .unwrap() .block_on(async { assert!(true); }) } ``` -------------------------------- ### List XKB Components (Rust) Source: https://docs.rs/rerun/latest/rerun/external/re_renderer/external/smallvec/alloc/sync/struct Retrieves a list of XKB component names up to a maximum count for a given device. Useful for enumerating available keyboard extensions. ```Rust fn xkb_list_components(&self, device_spec: u16, max_names: u16) -> Result, ConnectionError> { // implementation omitted } ``` -------------------------------- ### Get element index from reference (Rust - Nightly) Source: https://docs.rs/rerun/latest/rerun/external/re_types/datatypes/struct Returns the index of an element within a slice given a reference to that element. This API is experimental and nightly-only. It uses pointer arithmetic and does not compare element values. Returns `None` if the reference does not point to the start of an element. ```Rust #![feature(substr_range)] let nums: &[u32] = &[1, 7, 1, 1]; let num = &nums[2]; assert_eq!(num, &1); assert_eq!(nums.element_offset(num), Some(2)); let arr: &[[u32; 2]] = &[[0, 1], [2, 3]]; let flat_arr: &[u32] = arr.as_flattened(); let ok_elm: &[u32; 2] = flat_arr[0..2].try_into().unwrap(); let weird_elm: &[u32; 2] = flat_arr[1..3].try_into().unwrap(); assert_eq!(ok_elm, &[0, 1]); assert_eq!(weird_elm, &[1, 2]); assert_eq!(arr.element_offset(ok_elm), Some(0)); assert_eq!(arr.element_offset(weird_elm), None); ``` -------------------------------- ### Rust: Simple From and FromRef Conversions Source: https://docs.rs/rerun/latest/rerun/external/re_types/blueprint/components/struct Provides basic conversion methods. `From for T` returns the argument unchanged, while `FromRef for T` converts from a reference. ```rust /// Returns the argument unchanged. /// /// Source: https://docs.rs/rerun/latest/rerun/trait.From.html#method.from fn from(t: T) -> T; /// Converts to this type from a reference to the input type. /// /// Source: https://docs.rs/rerun/latest/rerun/trait.FromRef.html#method.from_ref fn from_ref(input: &T) -> T; where T: Clone; ``` -------------------------------- ### Get Constant Pointer to Array Data Source: https://docs.rs/rerun/latest/rerun/external/re_types/external/ndarray/prelude/struct Returns a raw pointer to the first element of the array. Accessing elements via this pointer must follow the array's specific strided indexing scheme, calculated as the sum of index products with corresponding strides. ```rust pub fn as_ptr(&self) -> *const A ``` -------------------------------- ### Get and Set XKB Names (Rust) Source: https://docs.rs/rerun/latest/rerun/external/re_renderer/external/smallvec/alloc/sync/struct Functions to retrieve and assign human‑readable names for XKB components such as types, symbols, and indicators. The get function specifies which name details to fetch, while the set function provides a large set of parameters to define new names. Both return Result types with appropriate reply cookies. ```Rust fn xkb_get_names(&self, device_spec: u16, which: NameDetail) -> Result, ConnectionError> { // implementation omitted } fn xkb_set_names<'c, 'input>(&'c self, device_spec: u16, virtual_mods: VMod, first_type: u8, n_types: u8, first_kt_levelt: u8, n_kt_levels: u8, indicators: u32, group_names: SetOfGroup, n_radio_groups: u8, first_key: u8, n_keys: u8, n_key_aliases: u8, total_kt_level_names: u16, values: &'input SetNamesAux) ->, ConnectionError> { // implementation omitted } ``` -------------------------------- ### Trait Implementations Source: https://docs.rs/rerun/latest/rerun/external/re_viewer_context/external/tokio/net/unix/struct Documentation for various trait implementations. ```APIDOC ### `impl Allocation for T` Requires `T: RefUnwindSafe + Send + Sync`. ### `impl ErasedDestructor for T` Requires `T: 'static`. ### `impl WasmNotSend for T` Requires `T: Send`. ### `impl WasmNotSendSync for T` Requires `T: WasmNotSend + WasmNotSync`. ``` -------------------------------- ### Get Element Offset in a Slice (Rust - Nightly) Source: https://docs.rs/rerun/latest/rerun/external/re_renderer/external/smallvec/struct Calculates the byte offset of an element reference within a slice, returning its index. This method relies on pointer arithmetic and does not compare element values. Returns `None` if the element reference is not aligned with the start of an element. Panics if `T` is zero-sized. Requires the `substr_range` feature. ```Rust #![feature(substr_range)] let nums: &[u32] = &[1, 7, 1, 1]; let num = &nums[2]; assert_eq!(num, &1); assert_eq!(nums.element_offset(num), Some(2)); let arr: &[[u32; 2]] = &[[0, 1], [2, 3]]; let flat_arr: &[u32] = arr.as_flattened(); let ok_elm: &[u32; 2] = flat_arr[0..2].try_into().unwrap(); let weird_elm: &[u32; 2] = flat_arr[1..3].try_into().unwrap(); assert_eq!(ok_elm, &[0, 1]); assert_eq!(weird_elm, &[1, 2]); assert_eq!(arr.element_offset(ok_elm), Some(0)); // Points to element 0 assert_eq!(arr.element_offset(weird_elm), None); // Points between element 0 and 1 ``` -------------------------------- ### Create Or Policy Source: https://docs.rs/rerun/latest/rerun/external/re_viewer_context/external/tokio/io/unix/struct Creates a new policy that returns `Action::Follow` if either of the input policies returns `Action::Follow`. This combines two policies using a logical OR operation. It requires two policies with the same generic parameters. ```Rust fn or(self, other: P) -> Or where T: Policy, P: Policy{ // Implementation details } ``` -------------------------------- ### Create Sender from File Unchecked (Rust) Source: https://docs.rs/rerun/latest/rerun/external/re_viewer_context/external/tokio/net/unix/pipe/struct Constructs a Sender from a File without validating pipe properties. Caller must ensure write access, pipe type, and non-blocking mode. Useful for custom setups but risks runtime errors or blocking if misused. Example shows opening with O_NONBLOCK. ```rust use tokio::net::unix::pipe; use std::fs::OpenOptions; use std::os::unix::fs::{FileTypeExt, OpenOptionsExt}; const FIFO_NAME: &str = "path/to/a/fifo"; let file = OpenOptions::new() .write(true) .custom_flags(libc::O_NONBLOCK) .open(FIFO_NAME)?; if file.metadata()?.file_type().is_fifo() { let tx = pipe::Sender::from_file_unchecked(file)?; /* use the Sender */ } ``` -------------------------------- ### Get XKB Controls Source: https://docs.rs/rerun/latest/rerun/external/re_renderer/external/smallvec/alloc/sync/struct Retrieves the current settings for various XKB controls. This includes options like mouse keys, keyboard repetition, and accessX settings. It takes a device specification and returns a Cookie for a GetControlsReply. ```rust fn xkb_get_controls( &self, device_spec: u16, ) -> Result, ConnectionError> ``` -------------------------------- ### Get Motion Events - Rust Source: https://docs.rs/rerun/latest/rerun/external/re_renderer/external/smallvec/alloc/borrow/enum Retrieves a list of pointer motion events within a specified time range for a given window on the X11 server. This function requires a connection to the X server and takes the window ID, start time, and stop time as input. It returns a Cookie containing GetMotionEventsReply on success or a ConnectionError. ```rust fn get_motion_events(&self, window: u32, start: A, stop: B) -> Result, ConnectionError> where A: Into, B: Into, ``` -------------------------------- ### NonZero BITS Constant Example Source: https://docs.rs/rerun/latest/rerun/external/re_renderer/external/bytemuck/__core/num/struct Demonstrates the BITS constant for NonZero, indicating the number of bits in the type. ```rust assert_eq!(NonZero::::BITS, i64::BITS); ``` -------------------------------- ### GET /websites/rs_rerun/list_with_offset Source: https://docs.rs/rerun/latest/rerun/external/re_renderer/external/smallvec/alloc/sync/struct Lists objects with a prefix and an offset. ```APIDOC ## GET /websites/rs_rerun/list_with_offset ### Description List all the objects with the given prefix and a location greater than `offset`. ### Method GET ### Endpoint /websites/rs_rerun/list_with_offset ### Parameters #### Query Parameters - **prefix** (Path) - Optional - A prefix to filter the list of objects. - **offset** (Path) - Required - A location greater than which objects should be listed. ### Response #### Success Response (200) - **Stream** (Stream) - A stream of object metadata. #### Response Example (Stream of object metadata) ``` -------------------------------- ### Example Usage of regexp_is_match in Rust Source: https://docs.rs/rerun/latest/rerun/external/re_types_core/external/arrow/compute/kernels/regexp/fn Demonstrates creating string arrays for input, regex, and flags, then calling the function to get match results, verified with assert_eq. Purpose is to show array-wise regex matching; no additional dependencies beyond standard imports; inputs are vec strings, outputs BooleanArray; handles None flags by type inference. ```rust // First array is the array of strings to match let array = StringArray::from(vec!["Foo", "Bar", "FooBar", "Baz"]); // Second array is the array of regular expressions to match against let regex_array = StringArray::from(vec!["^Foo", "^Foo", "Bar$", "Baz"]); // Third array is the array of flags to use for each regular expression, if desired // (the type must be provided to satisfy type inference for the third parameter) let flags_array: Option<&StringArray> = None; // The result is a BooleanArray indicating when each string in `array` // matches the corresponding regular expression in `regex_array` let result = regexp_is_match(&array, ®ex_array, flags_array).unwrap(); assert_eq!(result, BooleanArray::from(vec![true, false, true, true])); ``` -------------------------------- ### Accept a New TCP Connection with Tokio TcpListener Source: https://docs.rs/rerun/latest/rerun/external/re_viewer_context/external/tokio/net/struct Illustrates how to accept a single incoming TCP connection using the `accept` method on a TcpListener. It returns a TcpStream and the client's SocketAddr upon successful connection. ```rust use tokio::net::TcpListener; use std::io; #[tokio::main] async fn main() -> io::Result<()> { let listener = TcpListener::bind("127.0.0.1:8080").await?; match listener.accept().await { Ok((_socket, addr)) => println!("new client: {:?}", addr), Err(e) => println!("couldn't get client: {:?}", e), } Ok(()) } ``` -------------------------------- ### Configure Tokio Interval to Skip Missed Ticks Source: https://docs.rs/rerun/latest/rerun/external/re_viewer_context/external/tokio/time/enum This example demonstrates how to configure a Tokio `Interval` to use the `MissedTickBehavior::Skip` strategy. It shows the setup of an interval, setting the behavior, and then illustrates how subsequent calls to `tick()` behave after a delay that causes a missed tick. The first `tick()` after the delay resolves immediately, and the second `tick()` resolves at the next scheduled multiple of the period. ```rust use tokio::time::{interval, Duration, MissedTickBehavior}; let mut interval = interval(Duration::from_millis(50)); interval.set_missed_tick_behavior(MissedTickBehavior::Skip); task_that_takes_75_millis().await; // The `Interval` has missed a tick // Since we have exceeded our timeout, this will resolve immediately interval.tick().await; // This one will resolve after 25ms, 100ms after the start of // `interval`, which is the closest multiple of `period` from the start // of `interval` after the call to `tick` up above. interval.tick().await; ``` -------------------------------- ### Pointer Operations Source: https://docs.rs/rerun/latest/rerun/grpc_server/struct Utilities for working with pointers and memory initialization. ```APIDOC ## Pointable for T ### Description Defines an interface for types that can be managed via raw pointers, including initialization and de-initialization. ### Constants #### `ALIGN: usize` The required alignment for pointers to this type. ### Associated Types #### `Init = T` The type used for initializing an instance of `T`. ### Methods #### `init(init: ::Init) -> usize` Initializes an instance of `T` with the given initializer and returns a raw pointer to the initialized memory. #### `deref<'a>(ptr: usize) -> &'a T` Dereferences a raw pointer to obtain an immutable reference to `T`. #### `deref_mut<'a>(ptr: usize) -> &'a mut T` Dereferences a raw pointer to obtain a mutable reference to `T`. #### `drop(ptr: usize)` Drops the object pointed to by the given raw pointer. ``` -------------------------------- ### Manually Create Box from NonNull Pointer using Global Allocator (Nightly) Source: https://docs.rs/rerun/latest/rerun/external/re_renderer/external/smallvec/alloc/boxed/struct This nightly-only example demonstrates creating a `Box` from a manually allocated block of memory, represented as a `NonNull` pointer. It uses `std::alloc::alloc` to get memory, `NonNull::new` to create the pointer, and `Box::from_non_null` to create the `Box`. Proper initialization using `non_null.write(5)` is crucial before constructing the `Box`. ```rust #![feature(box_vec_non_null)] use std::alloc::{alloc, Layout}; use std::ptr::NonNull; unsafe { let non_null = NonNull::new(alloc(Layout::new::()).cast::()) .expect("allocation failed"); // In general .write is required to avoid attempting to destruct // the (uninitialized) previous contents of `non_null`. non_null.write(5); let x = Box::from_non_null(non_null); } ``` -------------------------------- ### Configure X11 Window Source: https://docs.rs/rerun/latest/rerun/external/re_renderer/external/smallvec/alloc/sync/struct Configures the attributes of an X11 window, such as its size, position, and stacking order. Requires the window ID and a list of configuration values. Returns a VoidCookie or a ConnectionError. ```rust fn configure_window<'c, 'input>( &'c self, window: u32, value_list: &'input ConfigureWindowAux, ) -> Result, ConnectionError> ``` -------------------------------- ### Rust Option as_ref() Method Example Source: https://docs.rs/rerun/latest/rerun/external/re_renderer/external/bytemuck/__core/prelude/rust_2021/enum Provides an example of using as_ref() to convert an Option to an Option<&T>. This is useful for borrowing the contained value without consuming the Option, as shown in the example calculating the length of an Option. ```rust let text: Option = Some("Hello, world!".to_string()); // First, cast `Option` to `Option<&String>` with `as_ref`, // then consume *that* with `map`, leaving `text` on the stack. let text_length: Option = text.as_ref().map(|s| s.len()); println!("still can print text: {:?}", text); ``` -------------------------------- ### Service Layering Source: https://docs.rs/rerun/latest/rerun/grpc_server/struct Utilities for applying layers to services. ```APIDOC ## LayerExt for L ### Description Provides extension methods for applying layers to services. ### Method #### `named_layer(&self, service: S) -> Layered<>::Service, S>` Applies the layer to a service and wraps it in `Layered`. This method requires `L: Layer`. ```