### Rust Vec as_mut_ptr examples for initialization and aliasing Source: https://docs.rs/weedle/latest/weedle/namespace/type.NamespaceMembers_search= Illustrates initializing vector elements using `as_mut_ptr` and raw pointer writes. It also shows how writes via `as_mut_ptr` to different elements maintain pointer validity due to aliasing guarantees. Includes an example of deallocating vector memory using Box. ```rust // Allocate vector big enough for 4 elements. let size = 4; let mut x: Vec = Vec::with_capacity(size); let x_ptr = x.as_mut_ptr(); // Initialize elements via raw pointer writes, then set length. unsafe { for i in 0..size { *x_ptr.add(i) = i as i32; } x.set_len(size); } assert_eq!(&*x, &[0, 1, 2, 3]); ``` ```rust unsafe { let mut v = vec![0]; let ptr1 = v.as_mut_ptr(); ptr1.write(1); let ptr2 = v.as_mut_ptr(); ptr2.write(2); // Notably, the write to `ptr2` did *not* invalidate `ptr1`: ptr1.write(3); } ``` ```rust use std::mem::{ManuallyDrop, MaybeUninit}; let mut v = ManuallyDrop::new(vec![0, 1, 2]); let ptr = v.as_mut_ptr(); let capacity = v.capacity(); let slice_ptr: *mut [MaybeUninit] = std::ptr::slice_from_raw_parts_mut(ptr.cast(), capacity); drop(unsafe { Box::from_raw(slice_ptr) }); ``` -------------------------------- ### Clone_from Method Example Source: https://docs.rs/weedle/latest/weedle/dictionary/type.DictionaryMembers_search=u32+-%3E+bool Demonstrates how to efficiently clone the contents of one vector into another, potentially reusing allocation. ```APIDOC ## POST /clone_from ### Description Overwrites the contents of `self` with a clone of the contents of `source`. This method is preferred over `self = source.clone()` as it avoids reallocation if possible. ### Method POST ### Endpoint /clone_from ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **self** (Vec) - The vector to be overwritten. - **source** (Vec) - The vector to clone from. ### Request Example ```rust let x = vec![5, 6, 7]; let mut y = vec![8, 9, 10]; let yp: *const i32 = y.as_ptr(); y.clone_from(&x); assert_eq!(x, y); assert_eq!(yp, y.as_ptr()); // Indicates no reallocation ``` ### Response #### Success Response (200) - **message** (string) - Indicates successful cloning. #### Response Example ```json { "message": "Vector cloned successfully." } ``` ``` -------------------------------- ### Rust Vec from_raw_parts_in Example Source: https://docs.rs/weedle/latest/weedle/namespace/type.NamespaceMembers_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates creating a `Vec` from a raw pointer, length, capacity, and allocator. It shows how to deconstruct an existing Vec into its raw parts and then reconstruct it using `from_raw_parts_in`, including overwriting the data. ```rust #![feature(allocator_api)] use std::alloc::System; use std::ptr; let mut v = Vec::with_capacity_in(3, System); v.push(1); v.push(2); v.push(3); // Deconstruct the vector into parts. let (p, len, cap, alloc) = v.into_raw_parts_with_alloc(); unsafe { // Overwrite memory with 4, 5, 6 for i in 0..len { ptr::write(p.add(i), 4 + i); } // Put everything back together into a Vec let rebuilt = Vec::from_raw_parts_in(p, len, cap, alloc.clone()); assert_eq!(rebuilt, [4, 5, 6]); } ``` -------------------------------- ### Rust Vec into_parts and from_parts Example Source: https://docs.rs/weedle/latest/weedle/interface/type.InterfaceMembers_search=u32+-%3E+bool Demonstrates how to decompose a Vec into its raw pointer, length, and capacity using `into_parts`, and then reconstruct it using `from_parts`. This allows for low-level manipulation of the vector's components. ```rust #![feature(box_vec_non_null)] let v: Vec = vec![-1, 0, 1]; let (ptr, len, cap) = v.into_parts(); let rebuilt = unsafe { // We can now make changes to the components, such as // transmuting the raw pointer to a compatible type. let ptr = ptr.cast::(); Vec::from_parts(ptr, len, cap) }; assert_eq!(rebuilt, [4294967295, 0, 1]); ``` -------------------------------- ### Rust Vec try_reserve_exact Example Source: https://docs.rs/weedle/latest/weedle/dictionary/type.DictionaryMembers_search=std%3A%3Avec Demonstrates using `try_reserve_exact` to pre-allocate memory for a Vec. It handles potential allocation errors by returning a `TryReserveError`. This ensures subsequent operations like `extend` do not cause out-of-memory errors. ```rust use std::collections::TryReserveError; fn process_data(data: &[u32]) -> Result, TryReserveError> { let mut output = Vec::new(); // Pre-reserve the memory, exiting if we can't output.try_reserve_exact(data.len())?; // Now we know this can't OOM in the middle of our complex work output.extend(data.iter().map(|&val| { val * 2 + 5 // very complicated })); Ok(output) } ``` -------------------------------- ### Rust Vec shrink_to Example Source: https://docs.rs/weedle/latest/weedle/dictionary/type.DictionaryMembers_search=std%3A%3Avec Shows how to shrink a Vec's capacity to a minimum specified size using `shrink_to`. The capacity will be at least the length of the vector and the provided minimum. If the current capacity is already below the minimum, the method has no effect. ```rust let mut vec = Vec::with_capacity(10); vec.extend([1, 2, 3]); assert!(vec.capacity() >= 10); vec.shrink_to(4); assert!(vec.capacity() >= 4); vec.shrink_to(0); assert!(vec.capacity() >= 3); ``` -------------------------------- ### Rust Vec shrink_to_fit Example Source: https://docs.rs/weedle/latest/weedle/dictionary/type.DictionaryMembers_search=std%3A%3Avec Illustrates shrinking a Vec's capacity to its minimal required size using `shrink_to_fit`. This method helps in reducing memory usage after elements have been added, though the exact behavior depends on the allocator. ```rust let mut vec = Vec::with_capacity(10); vec.extend([1, 2, 3]); assert!(vec.capacity() >= 10); vec.shrink_to_fit(); assert!(vec.capacity() >= 3); ``` -------------------------------- ### Blanket Implementations for Rust Generic Types Source: https://docs.rs/weedle/latest/weedle/term/struct.Namespace_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates blanket implementations for generic types, which apply to many types without explicit individual implementation. Examples include implementations of Any, Borrow, BorrowMut, CloneToUninit, From, Into, ToOwned, TryFrom, and TryInto. ```rust impl Any for T where T: 'static + ?Sized { // ... } impl Borrow for T where T: ?Sized { // ... } impl BorrowMut for T where T: ?Sized { // ... } impl CloneToUninit for T where T: Clone { // ... } impl From for T { // ... } impl Into for T where U: From { // ... } impl ToOwned for T where T: Clone { // ... } impl TryFrom for T where U: Into { // ... } impl TryInto for T where U: TryFrom { // ... } ``` -------------------------------- ### Implement Blanket Trait Implementations in Rust Source: https://docs.rs/weedle/latest/weedle/term/struct.Uint8ClampedArray_search=u32+-%3E+bool Shows examples of blanket implementations for common traits like Any, Borrow, BorrowMut, CloneToUninit, From, Into, ToOwned, and TryFrom, which apply to many types. ```rust impl Any for T where T: 'static + ?Sized { fn type_id(&self) -> TypeId; } impl Borrow for T where T: ?Sized { fn borrow(&self) -> &T; } impl BorrowMut for T where T: ?Sized { fn borrow_mut(&mut self) -> &mut T; } impl CloneToUninit for T where T: Clone { unsafe fn clone_to_uninit(&self, dest: *mut u8); } impl From for T { fn from(t: T) -> T; } impl Into for T where U: From { fn into(self) -> U; } impl ToOwned for T where T: Clone { type Owned = T; fn to_owned(&self) -> T; fn clone_into(&self, target: &mut T); } impl TryFrom for T where U: Into { type Error = Infallible; fn try_from(value: U) -> Result; } ``` -------------------------------- ### Rust Vec from_raw_parts_in with External Allocation Source: https://docs.rs/weedle/latest/weedle/namespace/type.NamespaceMembers_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Illustrates using `Vec::from_raw_parts_in` with memory allocated independently of a `Vec`, using `std::alloc::Global`. This example highlights the importance of matching layout and capacity for safe operation. ```rust #![feature(allocator_api)] use std::alloc::{AllocError, Allocator, Global, Layout}; fn main() { let layout = Layout::array::(16).expect("overflow cannot happen"); let vec = unsafe { let mem = match Global.allocate(layout) { Ok(mem) => mem.cast::().as_ptr(), Err(AllocError) => return, }; mem.write(1_000_000); Vec::from_raw_parts_in(mem, 1, 16, Global) }; assert_eq!(vec, &[1_000_000]); assert_eq!(vec.capacity(), 16); } ``` -------------------------------- ### Rust Result::is_ok_and() Example Source: https://docs.rs/weedle/latest/weedle/type.IResult_search=u32+-%3E+bool Illustrates the `is_ok_and()` method, which checks if a `Result` is `Ok` and its contained value satisfies a given predicate. This allows for conditional checks on the success value. ```rust let x: Result = Ok(2); assert_eq!(x.is_ok_and(|x| x > 1), true); let x: Result = Ok(0); assert_eq!(x.is_ok_and(|x| x > 1), false); let x: Result = Err("hey"); assert_eq!(x.is_ok_and(|x| x > 1), false); let x: Result = Ok("ownership".to_string()); assert_eq!(x.as_ref().is_ok_and(|x| x.len() > 1), true); println!("still alive {:?}", x); ``` -------------------------------- ### Rust Vec as_slice Example Source: https://docs.rs/weedle/latest/weedle/dictionary/type.DictionaryMembers_search=std%3A%3Avec Demonstrates obtaining an immutable slice of the entire Vec's contents using `as_slice`. This is useful for passing Vec data to functions that expect slices, such as I/O operations. ```rust use std::io::{self, Write}; let buffer = vec![1, 2, 3, 5, 8]; io::sink().write(buffer.as_slice()).unwrap(); ``` -------------------------------- ### Rust Result::as_ref() Example Source: https://docs.rs/weedle/latest/weedle/type.IResult_search=u32+-%3E+bool Explains the `as_ref()` method, which converts a `&Result` into a `Result<&T, &E>`. This allows borrowing references to the contained values without consuming the original `Result`. ```rust let x: Result = Ok(2); assert_eq!(x.as_ref(), Ok(&2)); let x: Result = Err("Error"); assert_eq!(x.as_ref(), Err(&"Error")); ``` -------------------------------- ### Get Reference to Result Ok/Err Value in Rust Source: https://docs.rs/weedle/latest/weedle/type.IResult_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Explains the `as_ref` method for `Result`. This method converts a `&Result` into a `Result<&T, &E>`, providing references to the contained values without taking ownership. Examples show both `Ok` and `Err` cases. ```rust let x: Result = Ok(2); assert_eq!(x.as_ref(), Ok(&2)); let x: Result = Err("Error"); assert_eq!(x.as_ref(), Err(&"Error")); ``` -------------------------------- ### Implement Blanket Blanket Implementations for Generics in Rust Source: https://docs.rs/weedle/latest/weedle/term/struct.Asterisk_search=std%3A%3Avec Shows examples of blanket implementations for generic types in Rust, such as Any, Borrow, BorrowMut, CloneToUninit, From, Into, ToOwned, TryFrom, and TryInto. ```rust impl Any for T where T: 'static + ?Sized { fn type_id(&self) -> TypeId; } impl Borrow for T where T: ?Sized { fn borrow(&self) -> &T; } impl BorrowMut for T where T: ?Sized { fn borrow_mut(&mut self) -> &mut T; } impl CloneToUninit for T where T: Clone { unsafe fn clone_to_uninit(&self, dest: *mut u8); } impl From for T { fn from(t: T) -> T; } impl Into for T where U: From { fn into(self) -> U; } impl ToOwned for T where T: Clone { type Owned = T; fn to_owned(&self) -> T; fn clone_into(&self, target: &mut T); } impl TryFrom for T where U: Into { type Error = Infallible; fn try_from(value: U) -> Result>::Error>; } impl TryInto for T where U: TryFrom; ``` -------------------------------- ### Get Mutable Reference to Result Ok/Err Value in Rust Source: https://docs.rs/weedle/latest/weedle/type.IResult_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates the `as_mut` method for `Result`. This method converts a `&mut Result` into a `Result<&mut T, &mut E>`, allowing mutable access to the contained values. The example shows how to modify values in both `Ok` and `Err` variants. ```rust fn mutate(r: &mut Result) { match r.as_mut() { Ok(v) => *v = 42, Err(e) => *e = 0, } } let mut x: Result = Ok(2); mutate(&mut x); assert_eq!(x.unwrap(), 42); let mut x: Result = Err(13); mutate(&mut x); assert_eq!(x.unwrap_err(), 0); ``` -------------------------------- ### Rust Result::ok() Example Source: https://docs.rs/weedle/latest/weedle/type.IResult_search=u32+-%3E+bool Shows the `ok()` method, which converts a `Result` into an `Option`. It consumes the `Result`, returning `Some(T)` if it was `Ok`, and `None` if it was `Err`, discarding the error value. ```rust let x: Result = Ok(2); assert_eq!(x.ok(), Some(2)); let x: Result = Err("Nothing here"); assert_eq!(x.ok(), None); ``` -------------------------------- ### Vec Recycle Slice/Trait Object Limitation Example Source: https://docs.rs/weedle/latest/weedle/mixin/type.MixinMembers_search=u32+-%3E+bool Highlights a runtime limitation of the recycle() method when dealing with slices, trait objects, or other exotic types. This example demonstrates a common pattern of reusing a Vec as a buffer, but the recycle operation is currently restricted for these complex types. ```rust #![feature(vec_recycle, transmutability)] let mut storage: Vec<&[&str]> = Vec::new(); for input in inputs { let mut buffer: Vec<&str> = storage.recycle(); buffer.extend(input.split(" ")); process(&buffer); storage = buffer.recycle(); } ``` -------------------------------- ### Process String Lines in Rust Source: https://docs.rs/weedle/latest/weedle/type.IResult_search=u32+-%3E+bool This example demonstrates iterating over lines in a string, parsing each line as an integer, and printing the doubled value. It handles potential parsing errors by ignoring them. ```rust let line = "1\n2\n3\n4\n"; for num in line.lines() { match num.parse::().map(|i| i * 2) { Ok(n) => println!("{n}"), Err(..) => {} } } ``` -------------------------------- ### Inheritance Parsing Source: https://docs.rs/weedle/latest/weedle/interface/index_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Parses an inheritance clause, typically starting with a colon followed by an identifier. ```APIDOC ## Parses `inheritance clause : identifier` ### Description Parses an inheritance clause, typically starting with a colon followed by an identifier. ### Method Not Applicable (Parsing Rule) ### Endpoint Not Applicable (Parsing Rule) ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### Create Vec from Allocated Memory using from_parts (Rust) Source: https://docs.rs/weedle/latest/weedle/mixin/type.MixinMembers_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Shows how to allocate memory using `std::alloc::alloc`, cast it, and then construct a `Vec` using `Vec::from_parts`. This example highlights using externally allocated memory and setting its initial state and capacity. Proper memory management and safety invariants must be maintained. ```rust #![feature(box_vec_non_null)] use std::alloc::{alloc, Layout}; use std::ptr::NonNull; fn main() { let layout = Layout::array::(16).expect("overflow cannot happen"); let vec = unsafe { let Some(mem) = NonNull::new(alloc(layout).cast::()) else { panic!("Allocation failed"); }; mem.as_ptr().write(1_000_000); Vec::from_parts(mem, 1, 16) }; assert_eq!(vec, &[1_000_000]); assert_eq!(vec.capacity(), 16); } ``` -------------------------------- ### Vec::from_raw_parts API Source: https://docs.rs/weedle/latest/weedle/type.Definitions_search= This section details the `from_raw_parts` function for constructing a `Vec` from raw memory components. It outlines the safety invariants that must be upheld when using this function, as well as providing illustrative examples. ```APIDOC ## POST /websites/rs_weedle/from_raw_parts ### Description Creates a `Vec` directly from a `NonNull` pointer, a length, and a capacity. This is an unsafe operation and requires the caller to uphold specific memory safety invariants. ### Method POST ### Endpoint /websites/rs_weedle/from_raw_parts ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **ptr** (NonNull) - Required - A non-null pointer to the allocated memory. - **length** (usize) - Required - The number of elements currently in the vector. - **capacity** (usize) - Required - The total number of elements the allocated memory can hold. ### Request Example ```json { "ptr": "", "length": 3, "capacity": 10 } ``` ### Response #### Success Response (200) - **Vec** - The newly created vector. #### Response Example ```json { "vec": [1, 2, 3] } ``` ### Safety Considerations This function is `unsafe` because it bypasses Rust's standard memory management. The caller must ensure the following invariants are met: * **Allocator**: If `T` is not zero-sized and capacity is non-zero, `ptr` must have been allocated using the global allocator. If `T` is zero-sized or capacity is zero, `ptr` must be non-null and aligned. * **Alignment**: `T` must have the same alignment as `ptr` was allocated with. * **Size**: The size of `T` times `capacity` must match the size `ptr` was allocated with. * **Length vs. Capacity**: `length` must be less than or equal to `capacity`. * **Initialization**: The first `length` elements must be properly initialized values of type `T`. * **Capacity Consistency**: `capacity` must match the capacity `ptr` was allocated with. * **Size Limit**: The allocated size in bytes must not exceed `isize::MAX`. Violating these invariants can lead to memory corruption, undefined behavior, and crashes. ### Examples **Deconstructing and Reconstructing a Vector:** ```rust use std::ptr; let v = vec![1, 2, 3]; // Deconstruct the vector into parts. let (p, len, cap) = v.into_raw_parts(); unsafe { // Overwrite memory with 4, 5, 6 for i in 0..len { ptr::write(p.add(i), 4 + i); } // Put everything back together into a Vec let rebuilt = Vec::from_raw_parts(p, len, cap); assert_eq!(rebuilt, [4, 5, 6]); } ``` **Using Memory Allocated Elsewhere:** ```rust use std::alloc::{alloc, Layout}; fn main() { let layout = Layout::array::(16).expect("overflow cannot happen"); let vec = unsafe { let mem = alloc(layout).cast::(); if mem.is_null() { // Handle allocation failure panic!("Memory allocation failed"); } mem.write(1_000_000); Vec::from_raw_parts(mem, 1, 16) }; assert_eq!(vec, &[1_000_000]); assert_eq!(vec.capacity(), 16); } ``` ``` -------------------------------- ### Result Into OK Method Source: https://docs.rs/weedle/latest/weedle/type.IResult_search=std%3A%3Avec Documentation for the `into_ok` method on the Result type. ```APIDOC ## POST /result/into_ok ### Description Returns the contained `Ok` value, but never panics. This method is known to never panic on the result types it is implemented for. ### Method POST ### Endpoint /result/into_ok ### Parameters #### Path Parameters - **None** #### Query Parameters - **None** #### Request Body - **result_value** (any) - Required - The Result value to operate on. The error type must be convertible into `!`, indicating it can never occur. ### Request Example ```json { "result_value": "Ok(\"this is fine\")" } ``` ### Response #### Success Response (200) - **value** (any) - The contained Ok value. #### Response Example ```json { "value": "this is fine" } ``` ``` -------------------------------- ### GET /vectors/{id}/is_empty Source: https://docs.rs/weedle/latest/weedle/namespace/type.NamespaceMembers_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Checks if the vector contains any elements. ```APIDOC ## GET /vectors/{id}/is_empty ### Description Returns `true` if the vector contains no elements, and `false` otherwise. ### Method GET ### Endpoint `/vectors/{id}/is_empty` ### Parameters #### Path Parameters - **id** (string) - Required - The identifier of the vector. #### Request Body None ### Response #### Success Response (200) - **isEmpty** (boolean) - `true` if the vector is empty, `false` otherwise. #### Response Example ```json { "isEmpty": false } ``` #### Error Response (404) - **message** (string) - Vector not found. ``` -------------------------------- ### Rust Vec as_mut_slice Example Source: https://docs.rs/weedle/latest/weedle/dictionary/type.DictionaryMembers_search=std%3A%3Avec Shows how to obtain a mutable slice of the entire Vec's contents using `as_mut_slice`. This allows for in-place modification of the Vec's elements, often used with I/O operations that need to read into a buffer. ```rust use std::io::{self, Read}; let mut buffer = vec![0; 3]; io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap(); ``` -------------------------------- ### CloneToUninit API Source: https://docs.rs/weedle/latest/weedle/enum.Err_search= The `clone_to_uninit` method is an experimental, nightly-only API for performing copy-assignment from self to a mutable pointer. ```APIDOC ## unsafe fn clone_to_uninit(&self, dest: *mut u8) ### Description Performs copy-assignment from `self` to `dest`. ### Method `clone_to_uninit` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Get Vector Length Source: https://docs.rs/weedle/latest/weedle/mixin/type.MixinMembers_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns the number of elements currently in the vector. ```APIDOC ## GET /vec/len ### Description Returns the number of elements in the vector, also referred to as its ‘length’. ### Method GET ### Endpoint `/vec/len` ### Parameters #### Query Parameters None #### Request Body - **vec** (array) - The input vector. ### Request Example ```json { "vec": [1, 2, 3] } ``` ### Response #### Success Response (200) - **usize** - The number of elements in the vector. #### Response Example ```json { "length": 3 } ``` ``` -------------------------------- ### Get Raw Pointer to Vec Buffer with as_ptr Source: https://docs.rs/weedle/latest/weedle/dictionary/type.DictionaryMembers_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Explains how to get a raw, non-null pointer (`*const T`) to the beginning of the Vec's internal buffer using `as_ptr`. It emphasizes the caller's responsibility to ensure the Vec outlives the pointer and to manage memory safety, especially regarding aliasing rules. ```rust pub const fn as_ptr(&self) -> *const T ``` -------------------------------- ### GET /vectors/{id}/len Source: https://docs.rs/weedle/latest/weedle/namespace/type.NamespaceMembers_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns the number of elements currently in the vector. ```APIDOC ## GET /vectors/{id}/len ### Description Returns the number of elements in the vector, also referred to as its ‘length’. ### Method GET ### Endpoint `/vectors/{id}/len` ### Parameters #### Path Parameters - **id** (string) - Required - The identifier of the vector. #### Request Body None ### Response #### Success Response (200) - **length** (integer) - The number of elements in the vector. #### Response Example ```json { "length": 3 } ``` #### Error Response (404) - **message** (string) - Vector not found. ``` -------------------------------- ### Construct Vec from External Allocation using `alloc` and `from_raw_parts` (Rust) Source: https://docs.rs/weedle/latest/weedle/dictionary/type.DictionaryMembers_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E This example demonstrates creating a `Vec` from memory allocated using `std::alloc::alloc`. It emphasizes the need to manually ensure the layout and size match the intended `Vec` and the necessity of an `unsafe` block for raw memory operations and `Vec` construction. Proper error handling for allocation failure is also shown. ```rust use std::alloc::{alloc, Layout}; fn main() { let layout = Layout::array::(16).expect("overflow cannot happen"); let vec = unsafe { let mem = alloc(layout).cast::(); if mem.is_null() { return; // Handle allocation failure } mem.write(1_000_000); Vec::from_raw_parts(mem, 1, 16) }; assert_eq!(vec, &[1_000_000]); assert_eq!(vec.capacity(), 16); } ``` -------------------------------- ### Rust: Getting a Raw Pointer to Vector Buffer Source: https://docs.rs/weedle/latest/weedle/mixin/type.MixinMembers Explains how to get a raw pointer to the vector's internal buffer using `as_ptr`. This method is unsafe and requires careful handling to ensure the vector outlives the pointer and that the memory is not mutated through unsafe means. It's useful for low-level operations or FFI calls. ```Rust let v = vec![1, 2, 3]; let ptr = v.as_ptr(); // ptr is a *const u32 ``` -------------------------------- ### Rust Vec into_boxed_slice Example Source: https://docs.rs/weedle/latest/weedle/dictionary/type.DictionaryMembers_search=std%3A%3Avec Demonstrates converting a Vec into a `Box<[T]>` using `into_boxed_slice`. This method first discards any excess capacity, similar to `shrink_to_fit`, before performing the conversion. The resulting boxed slice can then be converted back into a Vec with its capacity adjusted. ```rust let v = vec![1, 2, 3]; let slice = v.into_boxed_slice(); ``` ```rust let mut vec = Vec::with_capacity(10); vec.extend([1, 2, 3]); assert!(vec.capacity() >= 10); let slice = vec.into_boxed_slice(); assert_eq!(slice.into_vec().capacity(), 3); ``` -------------------------------- ### Rust Vec truncate Example Source: https://docs.rs/weedle/latest/weedle/dictionary/type.DictionaryMembers_search=std%3A%3Avec Provides examples of truncating a Vec to a specified length using `truncate`. If the new length is less than the current length, elements beyond the new length are dropped. If the new length is greater than or equal to the current length, the Vec remains unchanged. Truncating to zero is equivalent to clearing the Vec. ```rust let mut vec = vec![1, 2, 3, 4, 5]; vec.truncate(2); assert_eq!(vec, [1, 2]); ``` ```rust let mut vec = vec![1, 2, 3]; vec.truncate(8); assert_eq!(vec, [1, 2, 3]); ``` ```rust let mut vec = vec![1, 2, 3]; vec.truncate(0); assert_eq!(vec, []); ``` -------------------------------- ### Rust: Implement CloneToUninit (Nightly) Source: https://docs.rs/weedle/latest/weedle/interface/enum.AsyncIterableInterfaceMember_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Showcases the `CloneToUninit` trait, an experimental and nightly-only API in Rust. It provides an `unsafe fn clone_to_uninit` method for performing copy-assignment from `self` to a raw pointer `dest`. ```rust unsafe fn clone_to_uninit(&self, dest: *mut u8) { // Implementation details for copy-assignment to uninitialized memory } ``` -------------------------------- ### Result Iterators Source: https://docs.rs/weedle/latest/weedle/type.IResult_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Provides methods to get iterators over the contained value of a Result. ```APIDOC ## GET /result/iter ### Description Returns an iterator over the possibly contained value. ### Method GET ### Endpoint /result/iter ### Parameters #### Query Parameters - **result_value** (Result) - Required - The Result value to iterate over. ### Request Example ```json { "result_value": "Ok(7)" } ``` ### Response #### Success Response (200) - **iterator_output** (Option<&T>) - The next item from the iterator, or None. #### Response Example ```json { "iterator_output": "Some(&7)" } ``` ``` ```APIDOC ## GET /result/iter_mut ### Description Returns a mutable iterator over the possibly contained value. ### Method GET ### Endpoint /result/iter_mut ### Parameters #### Query Parameters - **result_value** (Result) - Required - The mutable Result value to iterate over. ### Request Example ```json { "result_value": "Ok(7)" } ``` ### Response #### Success Response (200) - **iterator_output** (Option<&mut T>) - The next mutable item from the iterator, or None. #### Response Example ```json { "iterator_output": "Some(&mut 7)" } ``` ``` -------------------------------- ### Rust Vec as_mut_ptr Initialization and Deallocation Source: https://docs.rs/weedle/latest/weedle/type.Definitions_search=u32+-%3E+bool Shows how to use `as_mut_ptr` to initialize Vec elements via raw pointer writes and then set the vector's length. It also includes an example of deallocating the vector's backing memory using `Box::from_raw`, ensuring proper memory management. ```rust // Allocate vector big enough for 4 elements. let size = 4; let mut x: Vec = Vec::with_capacity(size); let x_ptr = x.as_mut_ptr(); // Initialize elements via raw pointer writes, then set length. unsafe { for i in 0..size { *x_ptr.add(i) = i as i32; } x.set_len(size); } assert_eq!(&*x, &[0, 1, 2, 3]); ``` ```rust use std::mem::{ManuallyDrop, MaybeUninit}; let mut v = ManuallyDrop::new(vec![0, 1, 2]); let ptr = v.as_mut_ptr(); let capacity = v.capacity(); let slice_ptr: *mut [MaybeUninit] = std::ptr::slice_from_raw_parts_mut(ptr.cast(), capacity); drop(unsafe { Box::from_raw(slice_ptr) }); ``` ```rust unsafe { let mut v = vec![0]; let ptr1 = v.as_mut_ptr(); ptr1.write(1); let ptr2 = v.as_mut_ptr(); ptr2.write(2); // Notably, the write to `ptr2` did *not* invalidate `ptr1`: ptr1.write(3); } ``` -------------------------------- ### Get Raw Pointer to Vec Buffer with as_ptr Source: https://docs.rs/weedle/latest/weedle/dictionary/type.DictionaryMembers Explains how to get a raw, non-null pointer (`*const T`) to the beginning of a vector's buffer using `as_ptr`. This method provides low-level access but requires careful handling to ensure the pointer remains valid and memory safety is maintained, especially concerning aliasing rules and potential reallocations. ```rust /// Returns a raw pointer to the vector’s buffer, or a dangling raw pointer valid for zero sized reads if the vector didn’t allocate. /// The caller must ensure that the vector outlives the pointer this function returns, or else it will end up dangling. Modifying the vector may cause its buffer to be reallocated, which would also make any pointers to it invalid. /// The caller must also ensure that the memory the pointer (non-transitively) points to is never written to (except inside an `UnsafeCell`) using this pointer or any pointer derived from it. If you need to mutate the contents of the slice, use `as_mut_ptr`. /// This method guarantees that for the purpose of the aliasing model, this method does not materialize a reference to the underlying slice, and thus the returned pointer will remain valid when mixed with other calls to `as_ptr`, `as_mut_ptr`, and `as_non_null`. Note that calling other methods that materialize mutable references to the slice, or mutable references to specific elements you are planning on accessing through this pointer, as well as writing to those elements, may still invalidate this pointer. See the second example below for how this guarantee can be used. const fn as_ptr(&self) -> *const T ``` -------------------------------- ### GET /vectors/{id}/peek_mut Source: https://docs.rs/weedle/latest/weedle/namespace/type.NamespaceMembers_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns a mutable reference to the last item in the vector without removing it. ```APIDOC ## GET /vectors/{id}/peek_mut ### Description Returns a mutable reference to the last item in the vector, or `None` if it is empty. Note: This is an experimental API and may change. ### Method GET ### Endpoint `/vectors/{id}/peek_mut` ### Parameters #### Path Parameters - **id** (string) - Required - The identifier of the vector. #### Request Body None ### Response #### Success Response (200) - **mutableReference** (PeekMut<'_, T, A>) - A mutable reference to the last element, or null if the vector is empty. #### Response Example ```json { "mutableReference": "" } ``` #### Error Response (404) - **message** (string) - Vector not found. ``` -------------------------------- ### Vec Implementations Source: https://docs.rs/weedle/latest/weedle/type.Definitions_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Documentation for common `Vec` implementations in Rust, including constructors like `new`, `with_capacity`, and `try_with_capacity`, as well as the unsafe `from_raw_parts`. ```APIDOC ## Vec Implementations ### Description Provides documentation for various `Vec` constructors and methods, including static methods for creating new vectors and unsafe methods for constructing from raw parts. ### Method `Vec::new()`, `Vec::with_capacity(usize)`, `Vec::try_with_capacity(usize)`, `Vec::from_raw_parts(*mut T, usize, usize)` ### Endpoint N/A (Rust methods) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust // Example for Vec::new() let mut vec: Vec = Vec::new(); // Example for Vec::with_capacity() let mut vec_with_cap = Vec::with_capacity(10); // Example for Vec::try_with_capacity() (requires nightly) // let result_vec: Result, _> = Vec::try_with_capacity(10); // Example for Vec::from_raw_parts() (unsafe) // let mut vec_from_raw = unsafe { Vec::from_raw_parts(ptr, len, capacity) }; ``` ### Response #### Success Response (200) Returns a `Vec` instance. #### Response Example ```json // Vec is a standard Rust data structure, not typically represented as JSON. // The "example" here refers to the Rust code demonstrating its usage. ``` ``` -------------------------------- ### Implement Any for T - Rust Source: https://docs.rs/weedle/latest/weedle/literal/struct.StringLit_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Implements the Any trait for any type T, providing a way to get the TypeId of a value. This is a blanket implementation. ```rust impl Any for T where T: 'static + ?Sized, fn type_id(&self) -> TypeId ``` -------------------------------- ### Rust: Vec splice example Source: https://docs.rs/weedle/latest/weedle/namespace/type.NamespaceMembers_search= Illustrates the `splice` method for `Vec`. This method creates a splicing iterator that replaces a specified range within the vector with elements from another iterator. It yields the removed items. The `splice` method offers flexibility in modifying the vector, allowing insertion, deletion, or replacement of elements efficiently. The example shows both replacing a range and inserting elements at a specific position. ```rust let mut v = vec![1, 2, 3, 4]; let new = [7, 8, 9]; let u: Vec<_> = v.splice(1..3, new).collect(); assert_eq!(v, [1, 7, 8, 9, 4]); assert_eq!(u, [2, 3]); // Using `splice` to insert new items into a vector efficiently at a specific position indicated by an empty range: let mut v = vec![1, 5]; let new = [2, 3, 4]; v.splice(1..1, new); assert_eq!(v, [1, 2, 3, 4, 5]); ``` -------------------------------- ### Implement Copy, Eq, and StructuralPartialEq for BufferSource in Rust Source: https://docs.rs/weedle/latest/weedle/term/struct.BufferSource_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates the implementation of the Copy, Eq, and StructuralPartialEq traits for BufferSource. These traits indicate that BufferSource is a simple type that can be copied, guarantees a total equivalence relation, and supports structural equality. ```rust impl Copy for BufferSource; impl Eq for BufferSource; impl StructuralPartialEq for BufferSource; ``` -------------------------------- ### Create Vec from Allocated Memory (Rust) Source: https://docs.rs/weedle/latest/weedle/namespace/type.NamespaceMembers_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Shows how to allocate memory using `std::alloc::alloc`, create a `Vec` from this raw memory using `Vec::from_raw_parts`, and manage its capacity. This example emphasizes the necessity of `unsafe` blocks for direct memory allocation and `Vec` construction from raw parts. ```rust use std::alloc::{alloc, Layout}; fn main() { let layout = Layout::array::(16).expect("overflow cannot happen"); let vec = unsafe { let mem = alloc(layout).cast::(); if mem.is_null() { // Handle allocation failure, perhaps by returning an empty Vec or panicking return; } mem.write(1_000_000); Vec::from_raw_parts(mem, 1, 16) }; assert_eq!(vec, &[1_000_000]); assert_eq!(vec.capacity(), 16); } ``` -------------------------------- ### Vec Methods Source: https://docs.rs/weedle/latest/weedle/interface/type.InterfaceMembers_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E This section covers the core methods available for the Vec type, including examples of their usage. ```APIDOC ## `recycle()` Method ### Description Recycles the vector's buffer, allowing it to be reused with a potentially different element type `U`. ### Method `recycle()` ### Endpoint N/A (Method on Vec) ### Parameters None ### Request Example ```rust #![feature(vec_recycle, transmutability)] let a: Vec = vec![0; 100]; let capacity = a.capacity(); let addr = a.as_ptr().addr(); let b: Vec = a.recycle(); assert_eq!(b.len(), 0); assert_eq!(b.capacity(), capacity); assert_eq!(b.as_ptr().addr(), addr); ``` ### Response #### Success Response (Recycled Vec) - `Vec` - The recycled vector with the new type `U`. #### Response Example ```json // No direct JSON response, but the returned Vec would have these properties: { "len": 0, "capacity": capacity_value, "ptr_addr": address_value } ``` ## `clone_from()` Method ### Description Overwrites the contents of `self` with a clone of the contents of `source`. This method is preferred over simply assigning `source.clone()` to `self`, as it avoids reallocation if possible. ### Method `clone_from(&mut self, source: &Vec)` ### Endpoint N/A (Method on Vec) ### Parameters - `source` (*Vec*) - The vector to clone from. ### Request Example ```rust let x = vec![5, 6, 7]; let mut y = vec![8, 9, 10]; let yp: *const i32 = y.as_ptr(); y.clone_from(&x); assert_eq!(x, y); assert_eq!(yp, y.as_ptr()); ``` ### Response #### Success Response (void) This method modifies `self` in place and does not return a value. #### Response Example N/A ``` -------------------------------- ### POST /websites/rs_weedle/try_with_capacity_in Source: https://docs.rs/weedle/latest/weedle/mixin/type.MixinMembers_search= Safely constructs a new, empty Vec with a specified capacity and allocator, returning a Result. ```APIDOC ## POST /websites/rs_weedle/try_with_capacity_in ### Description Constructs a new, empty `Vec` with at least the specified capacity using the provided allocator. This method returns a `Result` to handle potential allocation failures. ### Method POST ### Endpoint /websites/rs_weedle/try_with_capacity_in ### Parameters #### Path Parameters - **capacity** (usize) - Required - The minimum capacity for the new vector. - **alloc** (A) - Required - The allocator to be used for this vector. ### Request Body (This endpoint does not explicitly define a request body in the provided text.) ### Response #### Success Response (200) - **Vec** - A new, empty vector instance with the specified capacity. #### Error Response (Non-200 Status Code) - **TryReserveError** - An error returned if the capacity exceeds `isize::MAX` bytes or if the allocator reports a failure. #### Response Example (The provided text does not include a concrete response example, but the success case returns a `Vec` and the error case returns a `TryReserveError`.) ##### §Note This is a nightly-only experimental API (`allocator_api`). ``` -------------------------------- ### clone_to_uninit Source: https://docs.rs/weedle/latest/weedle/interface/enum.IterableInterfaceMember_search= This is a nightly-only experimental API that performs copy-assignment from `self` to a mutable pointer `dest` (`*mut u8`). Use with caution as it bypasses standard safety checks. ```APIDOC #### unsafe fn clone_to_uninit(&self, dest: *mut u8) ### Description This is a nightly-only experimental API. Performs copy-assignment from `self` to `dest`. ### Method `clone_to_uninit(dest: *mut u8)` ``` -------------------------------- ### Rust: `from` function example Source: https://docs.rs/weedle/latest/weedle/attribute/struct.ExtendedAttributeNamedArgList_search=u32+-%3E+bool A simple function signature demonstrating the `from` function which returns its argument unchanged. This is often used in trait implementations. ```rust fn from(t: T) -> T { t } ``` -------------------------------- ### POST /websites/rs_weedle/from_raw_parts_in Source: https://docs.rs/weedle/latest/weedle/interface/type.InterfaceMembers_search=std%3A%3Avec Creates a Vec directly from a raw pointer, a length, a capacity, and an allocator. This is an experimental, nightly-only API and requires careful handling due to its unsafe nature. ```APIDOC ## POST /websites/rs_weedle/from_raw_parts_in ### Description Creates a `Vec` directly from a pointer, a length, a capacity, and an allocator. This function is part of the nightly-only experimental `allocator_api` feature. ### Method POST ### Endpoint /websites/rs_weedle/from_raw_parts_in ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **ptr** (*mut T*) - Required - A mutable raw pointer to the allocated memory. - **length** (*usize*) - Required - The number of elements currently in the vector. - **capacity** (*usize*) - Required - The total number of elements the allocated memory can hold. - **alloc** (*A*) - Required - The allocator instance to be used for the vector. ### Request Example ```json { "ptr": "0x...", "length": 3, "capacity": 3, "alloc": "System" } ``` ### Response #### Success Response (200) - **Vec** (Vec) - The newly created vector instance. #### Response Example ```json { "example": "Vec" } ``` ### Safety This function is highly unsafe and requires the caller to uphold several invariants: * `ptr` must be currently allocated via the given allocator `alloc`. * `T` must have the same alignment as `ptr` was allocated with. * The size of `T` times `capacity` must match the allocated size. * `length` must be less than or equal to `capacity`. * The first `length` elements must be properly initialized. * `capacity` must fit the layout size. * The allocated size must not exceed `isize::MAX`. Violating these invariants can lead to memory corruption or allocator data structure corruption. ```