### Basic Turbosql Usage Example Source: https://docs.rs/turbosql Demonstrates INSERT, SELECT, UPDATE, and DELETE operations using Turbosql with a Person struct. Requires the Turbosql derive macro and basic functions like select and execute. ```rust use turbosql::{Turbosql, select, execute}; #[derive(Turbosql, Default)] struct Person { rowid: Option, // rowid member required & enforced at compile time name: Option, age: Option, image_jpg: Option> } fn main() -> Result<(), Box> { let name = "Joe"; // INSERT a row let rowid = Person { name: Some(name.to_string()), age: Some(42), ..Default::default() }.insert()?; // SELECT all rows let people = select!(Vec?); // SELECT multiple rows with a predicate let people = select!(Vec "WHERE age > " 21)?; // SELECT a single row with a predicate let mut person = select!(Person "WHERE name = " name)?; // UPDATE based on rowid, rewrites all fields in database row person.age = Some(43); person.update()?; // UPDATE with manual SQL execute!("UPDATE person SET age = " 44 " WHERE name = " name)?; // DELETE execute!("DELETE FROM person WHERE rowid = " 1)?; Ok(()) } ``` -------------------------------- ### Basic Turbosql Usage Example Source: https://docs.rs/turbosql/0.14.0/turbosql/index.html Demonstrates fundamental operations like inserting, selecting, updating, and deleting data using the turbosql crate. Ensure the Person struct derives Turbosql and has a rowid field. ```rust use turbosql::{Turbosql, select, execute}; #[derive(Turbosql, Default)] struct Person { rowid: Option, // rowid member required & enforced at compile time name: Option, age: Option, image_jpg: Option> } fn main() -> Result<(), Box> { let name = "Joe"; // INSERT a row let rowid = Person { name: Some(name.to_string()), age: Some(42), ..Default::default() }.insert()?; // SELECT all rows let people = select!(Vec?); // SELECT multiple rows with a predicate let people = select!(Vec "WHERE age > " 21)?; // SELECT a single row with a predicate let mut person = select!(Person "WHERE name = " name)?; // UPDATE based on rowid, rewrites all fields in database row person.age = Some(43); person.update()?; // UPDATE with manual SQL execute!("UPDATE person SET age = " 44 " WHERE name = " name)?; // DELETE execute!("DELETE FROM person WHERE rowid = " 1)?; Ok(()) } ``` -------------------------------- ### Async Transactions with Tokio Source: https://docs.rs/turbosql/0.14.0/turbosql/index.html Perform transactions in an async context by wrapping blocking database operations within `tokio::task::spawn_blocking`. This example demonstrates inserting a record, beginning a transaction, updating a record, and committing. ```rust use turbosql::{Turbosql, select, execute}; #[derive(Turbosql, Default)] struct Person { rowid: Option, age: Option } #[tokio::main] async fn main() -> Result<(), Box> { tokio::task::spawn_blocking(|| -> Result<(), turbosql::Error> { Person { rowid: None, age: Some(21) }.insert()?; execute!("BEGIN IMMEDIATE TRANSACTION")?; let p = select!(Person "WHERE rowid = ?", 1)?; // [ ...do any other blocking things... ] execute!( "UPDATE person SET age = ? WHERE rowid = ?", p.age.unwrap_or_default() + 1, 1 )?; execute!("COMMIT")?; Ok(()) }).await??; Ok(()) } ``` -------------------------------- ### Create Vec from External Allocation Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html This example demonstrates creating a `Vec` from memory allocated using `std::alloc::alloc`. It's crucial to ensure the allocated memory, layout, and types are compatible to avoid undefined behavior. This method is unsafe and requires careful management of memory and invariants. ```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; } mem.write(1_000_000); Vec::from_raw_parts(mem, 1, 16) }; assert_eq!(vec, &[1_000_000]); assert_eq!(vec.capacity(), 16); } ``` -------------------------------- ### Get Database Path - Rust Source: https://docs.rs/turbosql/0.14.0/turbosql/fn.db_path.html Returns the path to the database. This function is part of the TurboSQL library. ```rust pub fn db_path() -> PathBuf ``` -------------------------------- ### Get Current Time in Milliseconds Source: https://docs.rs/turbosql/0.14.0/turbosql/fn.now_ms.html Use this convenience function to retrieve the current time as milliseconds since the UNIX epoch. No setup or imports are required. ```rust pub fn now_ms() -> i64 ``` -------------------------------- ### Get Current Time in Microseconds Source: https://docs.rs/turbosql/0.14.0/turbosql/fn.now_%C2%B5s.html Use this convenience function to retrieve the current time as a 64-bit integer representing microseconds since the UNIX epoch. No special setup or imports are required. ```rust pub fn now_µs() -> i64 ``` -------------------------------- ### Get Immutable Raw Pointer to Vector Buffer - Rust Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Use `as_ptr` to get a raw pointer to the vector's buffer. Ensure the vector outlives the pointer and do not mutate the memory through this pointer. ```rust let x = vec![1, 2, 4]; let x_ptr = x.as_ptr(); unsafe { for i in 0..x.len() { assert_eq!(*x_ptr.add(i), 1 << i); } } ``` ```rust unsafe { let mut v = vec![0, 1, 2]; let ptr1 = v.as_ptr(); let _ = ptr1.read(); let ptr2 = v.as_mut_ptr().offset(2); ptr2.write(2); // Notably, the write to `ptr2` did *not* invalidate `ptr1` // because it mutated a different element: let _ = ptr1.read(); } ``` -------------------------------- ### Create Vec with capacity (experimental) Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html This nightly-only experimental API `try_with_capacity` constructs a new, empty `Vec` with at least the specified capacity. It returns a Result, indicating success or failure if capacity exceeds limits or allocation fails. ```rust pub fn try_with_capacity(capacity: usize) -> Result, TryReserveError> ``` -------------------------------- ### Get Mutable Raw Pointer to Vector Buffer - Rust Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Use `as_mut_ptr` to get a mutable raw pointer to the vector's buffer. This allows for in-place modification of elements. Ensure the vector outlives the pointer. ```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) }); ``` -------------------------------- ### from_raw_parts_in Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Creates a `Vec` directly from a pointer, a length, a capacity, and an allocator. This is a nightly-only experimental API. ```APIDOC ## pub unsafe fn from_raw_parts_in( ptr: *mut T, length: usize, capacity: usize, alloc: A, ) -> Vec ### Description Creates a `Vec` directly from a pointer, a length, a capacity, and an allocator. ``` -------------------------------- ### Get Length of Vec Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Returns the number of elements currently in the vector. ```rust let a = vec![1, 2, 3]; assert_eq!(a.len(), 3); ``` -------------------------------- ### Convert Vec to Parts with Custom Allocator Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Demonstrates converting a `Vec` into its raw components (pointer, length, capacity, allocator) and then reconstructing it using `Vec::from_parts_in`. This is useful for advanced memory management scenarios. ```rust #![feature(allocator_api)] use std::alloc.System; let mut v: Vec = Vec::new_in(System); v.push(-1); v.push(0); v.push(1); let (ptr, len, cap, alloc) = v.into_parts_with_alloc(); 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_in(ptr, len, cap, alloc) }; assert_eq!(rebuilt, [4294967295, 0, 1]); ``` -------------------------------- ### try_with_capacity_in Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Constructs a new, empty `Vec` with at least the specified capacity and the provided allocator. This is a nightly-only experimental API. ```APIDOC ## pub fn try_with_capacity_in( capacity: usize, alloc: A, ) -> Result, TryReserveError> ### Description Constructs a new, empty `Vec` with at least the specified capacity with the provided allocator. The vector will be able to hold at least `capacity` elements without reallocating. This method is allowed to allocate for more elements than `capacity`. If `capacity` is zero, the vector will not allocate. ### Errors Returns an error if the capacity exceeds `isize::MAX` _bytes_ , or if the allocator reports allocation failure. ``` -------------------------------- ### into_iter Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Creates a consuming iterator, that is, one that moves each value out of the vector (from start to end). The vector cannot be used after calling this. ```APIDOC ## fn into_iter(self) -> as IntoIterator>::IntoIter ### Description Creates a consuming iterator, that is, one that moves each value out of the vector (from start to end). The vector cannot be used after calling this. ### Returns - as IntoIterator>::IntoIter - An iterator that consumes the vector. ``` -------------------------------- ### Extend Vec from Range (From Index) Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Appends cloned elements from a specified range (starting from an index to the end) to the Vec. ```rust let mut characters = vec!['a', 'b', 'c', 'd', 'e']; characters.extend_from_within(2..); assert_eq!(characters, ['a', 'b', 'c', 'd', 'e', 'c', 'd', 'e']); ``` -------------------------------- ### Create Vec from External Memory with Global Allocator Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Shows how to allocate memory using the Global allocator, create a Vec from this memory using `from_raw_parts_in`, and then use the Vec. This requires careful handling of memory layout and potential allocation errors. ```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); } ``` -------------------------------- ### Get Immutable Slice of Vector Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Extracts an immutable slice that references the entire vector's data. This is equivalent to `&s[..]`. ```rust use std::io::{self, Write}; let buffer = vec![1, 2, 3, 5, 8]; io::sink().write(buffer.as_slice()).unwrap(); ``` -------------------------------- ### Get Mutable Slice of Vector Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Extracts a mutable slice that references the entire vector's data. This is equivalent to `&mut s[..]`. ```rust use std::io::{self, Read}; let mut buffer = vec![0; 3]; io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap(); ``` -------------------------------- ### Create Vec with Capacity and Custom Allocator (Nightly) Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Use `try_with_capacity_in` to create a Vec with a specified capacity and allocator. It may allocate more than requested and returns an error on failure. ```rust let capacity: usize = 10; let alloc = std::alloc.System; let result: Result, _> = Vec::try_with_capacity_in(capacity, alloc); match result { Ok(vec) => { // Use the vec } Err(e) => { // Handle error } } ``` -------------------------------- ### Append Element and Get Mutable Reference Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Appends an element to the back of a vector, returning a mutable reference to it. Panics if the new capacity exceeds `isize::MAX` bytes. ```rust let mut vec = vec![1, 2]; let last = vec.push_mut(3); assert_eq!(*last, 3); assert_eq!(vec, [1, 2, 3]); let last = vec.push_mut(3); *last += 1; assert_eq!(vec, [1, 2, 3, 4]); ``` -------------------------------- ### Generated SQL Schema and Queries Source: https://docs.rs/turbosql/0.14.0/turbosql/index.html Illustrates the SQL `CREATE TABLE` statement and `INSERT`/`SELECT` prepared statements generated by turbosql from the `Person` struct. Also shows how a `SELECT` query with a predicate is translated. ```sql CREATE TABLE person ( rowid INTEGER PRIMARY KEY, name TEXT, age INTEGER, image_jpg BLOB, ) STRICT INSERT INTO person (rowid, name, age, image_jpg) VALUES (?, ?, ?, ?) SELECT rowid, name, age, image_jpg FROM person ``` ```rust let people = select!(Vec "WHERE age > ?", 21); SELECT rowid, name, age, image_jpg FROM person WHERE age > ? ``` -------------------------------- ### Decompose Vec into NonNull Raw Parts (Nightly) Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Use the nightly-only `into_parts` to get a NonNull pointer, length, and capacity. Memory management is handled by reconstructing the Vec using `from_parts`. ```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]); ``` -------------------------------- ### from<&str> Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Allocates a `Vec` and fills it with a UTF-8 string. ```APIDOC fn from(s: &str) -> Vec ##### §Examples ``` assert_eq!(Vec::from("123"), vec![b'1', b'2', b'3']); ``` ``` -------------------------------- ### Vec with Capacity in Specific Allocator Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Demonstrates creating a vector with a specified capacity and allocator, showing its length and capacity behavior during element additions, including a case for zero-sized types. ```rust #![feature(allocator_api)] use std::alloc.System; let mut vec = Vec::with_capacity_in(10, System); // The vector contains no items, even though it has capacity for more assert_eq!(vec.len(), 0); assert!(vec.capacity() >= 10); // These are all done without reallocating... for i in 0..10 { vec.push(i); } assert_eq!(vec.len(), 10); assert!(vec.capacity() >= 10); // ...but this may make the vector reallocate vec.push(11); assert_eq!(vec.len(), 11); assert!(vec.capacity() >= 11); // A vector of a zero-sized type will always over-allocate, since no // allocation is necessary let vec_units = Vec::<(), System>::with_capacity_in(10, System); assert_eq!(vec_units.capacity(), usize::MAX); ``` -------------------------------- ### Decompose Vec into Raw Parts Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Use `into_raw_parts` to get the raw pointer, length, and capacity of a Vec. The caller becomes responsible for managing the memory. Reconstruct the Vec using `from_raw_parts`. ```rust let v: Vec = vec![-1, 0, 1]; let (ptr, len, cap) = v.into_raw_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 as *mut u32; Vec::from_raw_parts(ptr, len, cap) }; assert_eq!(rebuilt, [4294967295, 0, 1]); ``` -------------------------------- ### from> Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Converts a `BinaryHeap` into a `Vec`. This conversion requires no data movement or allocation, and has constant time complexity. ```APIDOC fn from(heap: BinaryHeap) -> Vec ``` -------------------------------- ### split_off Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Splits the vector into two at the given index. Returns a new vector containing elements from the index to the end, leaving the original vector with elements from the start to the index. Panics if `at > len`. ```APIDOC ## pub fn split_off(&mut self, at: usize) -> Vec ### Description Splits the collection into two at the given index. Returns a newly allocated vector containing the elements in the range `[at, len)`. After the call, the original vector will be left containing the elements `[0, at)` with its previous capacity unchanged. ### Method `split_off` ### Parameters - `at`: The index at which to split the vector. ### Panics Panics if `at > len`. ### Notes - If you want to take ownership of the entire contents and capacity of the vector, see `mem::take` or `mem::replace`. - If you don’t need the returned vector at all, see `Vec::truncate`. - If you want to take ownership of an arbitrary subslice, or you don’t necessarily want to store the removed items in a vector, see `Vec::drain`. ### Request Example ```rust let mut v = vec![1, 2, 3, 4, 5]; let v2 = v.split_off(3); assert_eq!(v, &[1, 2, 3]); assert_eq!(v2, &[4, 5]); ``` ``` -------------------------------- ### Deconstruct and Reconstruct Vec Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Use `into_raw_parts` to get the raw pointer, length, and capacity of a vector. This is useful for modifying the vector's contents in place before reconstructing it. Ensure all invariants are maintained when modifying the data. ```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]); } ``` -------------------------------- ### db_path() Source: https://docs.rs/turbosql/0.14.0/turbosql/fn.db_path.html Returns the path to the database. ```APIDOC ## db_path() ### Description Returns the path to the database. ### Signature ```rust pub fn db_path() -> PathBuf ``` ### Returns - `PathBuf`: The path to the database. ``` -------------------------------- ### Split Vec at Index Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Splits the vector into two at the given index. Returns a new vector with elements from the index to the end. The original vector retains elements from the start up to the index. Panics if the index is out of bounds. ```rust let mut vec = vec![1, 2, 3]; let vec2 = vec.split_off(1); assert_eq!(vec, [1]); assert_eq!(vec2, [2, 3]); ``` -------------------------------- ### Deconstruct and Reconstruct Vec with Custom Allocator Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Demonstrates how to safely deconstruct a Vec into its raw parts (pointer, length, capacity, allocator) and then reconstruct it after modifying the underlying memory. Ensure all safety invariants are met before reconstruction. ```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]); } ``` -------------------------------- ### from<&[T]> Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Allocates a `Vec` and fills it by cloning `s`’s items. ```APIDOC fn from(s: &[T]) -> Vec ##### §Examples ``` assert_eq!(Vec::from(&[1, 2, 3][..]), vec![1, 2, 3]); ``` ``` -------------------------------- ### pub unsafe fn from_parts_in(ptr: NonNull, length: usize, capacity: usize, alloc: A) -> Vec Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html This is a nightly-only experimental API that creates a `Vec` directly from a `NonNull` pointer, a length, a capacity, and an allocator. Ensure all safety invariants are upheld when using this function. ```APIDOC ## pub unsafe fn from_parts_in( ptr: NonNull, length: usize, capacity: usize, alloc: A, ) -> Vec ### Description Creates a `Vec` directly from a `NonNull` pointer, a length, a capacity, and an allocator. ### Safety This is highly unsafe, due to the number of invariants that aren’t checked: * `ptr` must be _currently allocated_ via the given allocator `alloc`. * `T` needs to have the same alignment as what `ptr` was allocated with. * The size of `T` times the `capacity` needs to be the same size as the pointer was allocated with. * `length` needs to be less than or equal to `capacity`. * The first `length` values must be properly initialized values of type `T`. * `capacity` needs to _fit_ the layout size that the pointer was allocated with. * The allocated size in bytes must be no larger than `isize::MAX`. Violating these may cause problems like corrupting the allocator’s internal data structures. ### Parameters #### Path Parameters - **ptr** (NonNull) - Description: A non-null pointer to the allocated memory. - **length** (usize) - Description: The number of elements currently in the vector. - **capacity** (usize) - Description: The total number of elements the allocated memory can hold. - **alloc** (A) - Description: The allocator used to manage the memory. ### Returns - **Vec** - A new `Vec` instance created from the provided parts and allocator. ``` -------------------------------- ### Try Shrink Vector Capacity to Minimum (Nightly) Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Attempts to shrink the vector's capacity to be at least `min_capacity` or its current length. This is a nightly-only experimental API. It returns a `Result` indicating success or failure if the allocator fails. ```rust #![feature(vec_fallible_shrink)] let mut vec = Vec::with_capacity(10); vec.extend([1, 2, 3]); assert!(vec.capacity() >= 10); vec.try_shrink_to(4).expect("why is the test harness failing to shrink to 12 bytes"); assert!(vec.capacity() >= 4); vec.try_shrink_to(0).expect("this is a no-op and thus the allocator isn't involved."); assert!(vec.capacity() >= 3); ``` -------------------------------- ### Get Non-Null Pointer to Vector Buffer Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Returns a NonNull pointer to the vector's buffer. This is a nightly-only experimental API. Ensure the vector outlives the pointer and be aware that modifications to the vector may invalidate the pointer. ```rust #![feature(box_vec_non_null)] // Allocate vector big enough for 4 elements. let size = 4; let mut x: Vec = Vec::with_capacity(size); let x_ptr = x.as_non_null(); // Initialize elements via raw pointer writes, then set length. unsafe { for i in 0..size { x_ptr.add(i).write(i as i32); } x.set_len(size); } assert_eq!(&*x, &[0, 1, 2, 3]); ``` ```rust #![feature(box_vec_non_null)] unsafe { let mut v = vec![0]; let ptr1 = v.as_non_null(); ptr1.write(1); let ptr2 = v.as_non_null(); ptr2.write(2); // Notably, the write to `ptr2` did *not* invalidate `ptr1`: ptr1.write(3); } ``` -------------------------------- ### from<&mut [T; N]> Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Allocates a `Vec` and fills it by cloning `s`’s items. ```APIDOC fn from(s: &mut [T; N]) -> Vec ##### §Examples ``` assert_eq!(Vec::from(&mut [1, 2, 3]), vec![1, 2, 3]); ``` ``` -------------------------------- ### fn hash(&self, state: &mut H) Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Feeds this vector into the given `Hasher`. ```APIDOC ## fn hash(&self, state: &mut H) ### Description Feeds this value into the given `Hasher`. ### Parameters #### Path Parameters - **state** (&mut H) - Required - The `Hasher` to feed the vector's data into. ``` -------------------------------- ### Access mutable spare capacity Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Use `spare_capacity_mut()` to get a mutable slice of the vector's unused capacity. This allows direct manipulation of uninitialized memory before marking it as initialized with `set_len`. This is a low-level operation and requires careful handling. ```rust let mut v = Vec::with_capacity(10); let uninit = v.spare_capacity_mut(); uninit[0].write(0); uninit[1].write(1); uninit[2].write(2); unsafe { v.set_len(3); } assert_eq!(&v, &[0, 1, 2]); ``` -------------------------------- ### Extract Elements from Partial Vec Range Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Use `extract_if` with a specific range to process only a portion of the vector. This allows for conditional extraction of elements within a defined start and end, while elements outside the range are unaffected unless a shift is required due to extractions within the range. ```rust let mut items = vec![0, 0, 0, 0, 0, 0, 0, 1, 2, 1, 2, 1, 2]; let ones = items.extract_if(7.., |x| *x == 1).collect::>(); assert_eq!(items, vec![0, 0, 0, 0, 0, 0, 0, 2, 2, 2]); assert_eq!(ones.len(), 3); ``` -------------------------------- ### Compile-time SQL Predicate Validation Source: https://docs.rs/turbosql Illustrates how Turbosql validates SQL queries with predicates at compile time, showing the generated SQL. ```rust let people = select!(Vec "WHERE age > ?", 21); ``` ```sql SELECT rowid, name, age, image_jpg FROM person WHERE age > ? ``` -------------------------------- ### try_reserve_exact Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Tries to reserve the minimum capacity for at least `additional` elements. ```APIDOC ## pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> ### Description Tries to reserve the minimum capacity for at least `additional` elements to be inserted in the given `Vec`. Unlike `try_reserve`, this will not deliberately over-allocate to speculatively avoid frequent allocations. After calling `try_reserve_exact`, capacity will be greater than or equal to `self.len() + additional` if it returns `Ok(())`. Does nothing if the capacity is already sufficient. Note that the allocator may give the collection more space than it requests. Therefore, capacity can not be relied upon to be precisely minimal. Prefer `try_reserve` if future insertions are expected. ### Parameters - **additional** (`usize`): The number of additional elements to reserve capacity for. ### Returns - `Ok(())` if the reservation was successful. - `Err(TryReserveError)` if the capacity overflows or the allocator reports a failure. ### Errors If the capacity overflows, or the allocator reports a failure, then an error is returned. ``` -------------------------------- ### Select Option of String Source: https://docs.rs/turbosql/0.14.0/turbosql/index.html Retrieves an optional string value. Returns `Ok(None)` if no rows are found, or an `Error` if an issue occurs. ```rust let result = select!(Option "name FROM person")?; ``` -------------------------------- ### select!() Macro Source: https://docs.rs/turbosql/0.14.0/turbosql/macro.select.html Executes a SQL SELECT statement with optionally automatic `SELECT` and `FROM` clauses. ```APIDOC ## select!() Macro ### Description Executes a SQL SELECT statement with optionally automatic `SELECT` and `FROM` clauses. ### Syntax ```rust select!() { /* proc-macro */ } ``` ``` -------------------------------- ### Try Shrink Vector Capacity to Fit (Nightly) Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Attempts to shrink the vector's capacity as much as possible. This is a nightly-only experimental API. It returns a `Result` indicating success or failure if the allocator fails. ```rust #![feature(vec_fallible_shrink)] let mut vec = Vec::with_capacity(10); vec.extend([1, 2, 3]); assert!(vec.capacity() >= 10); vec.try_shrink_to_fit().expect("why is the test harness failing to shrink to 12 bytes"); assert!(vec.capacity() >= 3); ``` -------------------------------- ### new_in Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Constructs a new, empty `Vec` with the specified allocator. The vector will not allocate until elements are pushed onto it. This is a nightly-only experimental API. ```APIDOC ## pub const fn new_in(alloc: A) -> Vec ### Description Constructs a new, empty `Vec`. The vector will not allocate until elements are pushed onto it. ### Examples ```rust #![feature(allocator_api)] use std::alloc.System; let mut vec: Vec = Vec::new_in(System); ``` ``` -------------------------------- ### from<&[T; N]> Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Allocates a `Vec` and fills it by cloning `s`’s items. ```APIDOC fn from(s: &[T; N]) -> Vec ##### §Examples ``` assert_eq!(Vec::from(&[1, 2, 3]), vec![1, 2, 3]); ``` ``` -------------------------------- ### Create Vec with Capacity and Allocator Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Constructs a new, empty `Vec` with a specified minimum capacity and a given allocator. The vector can hold at least `capacity` elements without reallocating. This is a nightly-only experimental API. ```rust let mut vec = Vec::::with_capacity_in(10, A::default()); ``` -------------------------------- ### Create Vec from Iterator with Fallible Push Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Demonstrates a manual, panic-free alternative to FromIterator for creating a Vec, handling potential allocation errors. ```rust #![feature(vec_push_within_capacity)] use std::collections::TryReserveError; fn from_iter_fallible(iter: impl Iterator) -> Result, TryReserveError> { let mut vec = Vec::new(); for value in iter { if let Err(value) = vec.push_within_capacity(value) { vec.try_reserve(1)?; // this cannot fail, the previous line either returned or added at least 1 free slot let _ = vec.push_within_capacity(value); } } Ok(vec) } assert_eq!(from_iter_fallible(0..100), Ok(Vec::from_iter(0..100))); ``` -------------------------------- ### from Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Converts to this type from the input type. ```APIDOC fn from(s: ByteString) -> Vec ``` -------------------------------- ### from<&mut [T]> Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Allocates a `Vec` and fills it by cloning `s`’s items. ```APIDOC fn from(s: &mut [T]) -> Vec ##### §Examples ``` assert_eq!(Vec::from(&mut [1, 2, 3][..]), vec![1, 2, 3]); ``` ``` -------------------------------- ### Turbosql Schema Generation Source: https://docs.rs/turbosql Shows how the `Turbosql` derive macro on a Rust struct generates a corresponding SQLite schema and prepared SQL statements. ```rust use turbosql::Turbosql; #[derive(Turbosql, Default)] struct Person { rowid: Option, // rowid member required & enforced name: Option, age: Option, image_jpg: Option> } ``` ```sql CREATE TABLE person ( rowid INTEGER PRIMARY KEY, name TEXT, age INTEGER, image_jpg BLOB, ) STRICT INSERT INTO person (rowid, name, age, image_jpg) VALUES (?, ?, ?, ?) SELECT rowid, name, age, image_jpg FROM person ``` -------------------------------- ### Try to Reserve Exact Additional Capacity in Vec Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Demonstrates `try_reserve_exact` for reserving the minimum capacity for `additional` elements in a `Vec`. It returns a `Result` and is suitable when precise capacity is desired, though the allocator may still provide more space. ```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) } ``` -------------------------------- ### try_shrink_to_fit Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Tries to shrink the capacity of the vector as much as possible. This is a nightly-only experimental API. ```APIDOC ## pub fn try_shrink_to_fit(&mut self) -> Result<(), TryReserveError> ### Description This is a nightly-only experimental API. (`vec_fallible_shrink`) Tries to shrink the capacity of the vector as much as possible. The behavior of this method depends on the allocator, which may either shrink the vector in-place or reallocate. The resulting vector might still have some excess capacity, just as is the case for `with_capacity`. See `Allocator::shrink` for more details. ### Errors This function returns an error if the allocator fails to shrink the allocation; the vector thereafter is still safe to use, the capacity remains unchanged however. See `Allocator::shrink`. ### Examples ``` #![feature(vec_fallible_shrink)] let mut vec = Vec::with_capacity(10); vec.extend([1, 2, 3]); assert!(vec.capacity() >= 10); vec.try_shrink_to_fit().expect("why is the test harness failing to shrink to 12 bytes"); assert!(vec.capacity() >= 3); ``` ``` -------------------------------- ### checkpoint() Source: https://docs.rs/turbosql/0.14.0/turbosql/fn.checkpoint.html Checkpoints the DB. If no other threads have open connections, this will clean up the -wal and -shm files as well. ```APIDOC ## checkpoint() ### Description Checkpoints the DB. If no other threads have open connections, this will clean up the -wal and -shm files as well. ### Signature ```rust pub fn checkpoint() -> Result ``` ``` -------------------------------- ### Create Vec from External Memory Allocation Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Shows how to create a Vec from memory that was allocated externally using a custom allocator. This requires careful handling of memory layout and ownership. ```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::(), Err(AllocError) => return, }; mem.write(1_000_000); Vec::from_parts_in(mem, 1, 16, Global) }; assert_eq!(vec, &[1_000_000]); assert_eq!(vec.capacity(), 16); } ``` -------------------------------- ### Partial Ordering Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Implements lexicographical comparison of vectors. ```APIDOC ## fn partial_cmp(&self, other: &Vec) -> Option ### Description This method returns an ordering between `self` and `other` values if one exists. ### Method `partial_cmp` ``` ```APIDOC ## fn lt(&self, other: &Rhs) -> bool ### Description Tests less than (for `self` and `other`) and is used by the `<` operator. ### Method `lt` ``` ```APIDOC ## fn le(&self, other: &Rhs) -> bool ### Description Tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. ### Method `le` ``` ```APIDOC ## fn gt(&self, other: &Rhs) -> bool ### Description Tests greater than (for `self` and `other`) and is used by the `>` operator. ### Method `gt` ``` ```APIDOC ## fn ge(&self, other: &Rhs) -> bool ### Description Tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. ### Method `ge` ``` -------------------------------- ### Set Database Path in Turbosql Source: https://docs.rs/turbosql/0.14.0/turbosql/fn.set_db_path.html Call this function before any Turbosql macros to specify the SQLite database file path. Failure to do so will result in an error. ```rust pub fn set_db_path(path: &Path) -> Result<(), Error> ``` -------------------------------- ### Vec::from_raw_parts Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Creates a `Vec` directly from a `NonNull` pointer, a length, and a capacity. This is a nightly-only experimental API. ```APIDOC ## pub unsafe fn from_parts( ptr: NonNull, length: usize, capacity: usize, ) -> Vec ### Description Creates a `Vec` directly from a `NonNull` pointer, a length, and a capacity. ### Method `from_parts` ### Parameters #### Path Parameters - **ptr** (NonNull) - Required - The 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 vector can hold. ### Safety This function is highly unsafe due to the number of invariants that aren't checked. Violating these may cause problems like corrupting the allocator's internal data structures. Ensure that nothing else uses the pointer after calling this function, as ownership is effectively transferred to the `Vec`. ``` -------------------------------- ### ne (ByteString comparison) Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. ```APIDOC ## fn ne(&self, other: &ByteString) -> bool ### Description Tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. ### Parameters - **other** (&ByteString) - Required - The ByteString to compare with. ### Returns - bool - `true` if the vector is not equal to the ByteString, `false` otherwise. ``` -------------------------------- ### allocator Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Returns a reference to the underlying allocator. This is a nightly-only experimental API. ```APIDOC ## pub fn allocator(&self) -> &A ### Description Returns a reference to the underlying allocator. ### Method `allocator` ### Parameters None ### Response - Returns a reference to the underlying allocator (`&A`). ``` -------------------------------- ### Create Vec with `from_fn` (Mutable State) Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Demonstrates using `Vec::from_fn` with a closure that maintains mutable state across calls. The closure is called sequentially, allowing for stateful element generation. ```rust #![feature(vec_from_fn)] let mut state = 1; let a = Vec::from_fn(6, |_| { let x = state; state *= 2; x }); assert_eq!(a, [1, 2, 4, 8, 16, 32]); ``` -------------------------------- ### Create Vec from Raw Parts and Allocator (Nightly) Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Use `from_raw_parts_in` to construct a Vec from raw components and a specified allocator. This is an unsafe operation. ```rust let ptr: *mut i32 = std::ptr::null_mut(); let length: usize = 0; let capacity: usize = 10; let alloc = std::alloc.System; let vec: Vec = unsafe { Vec::from_raw_parts_in(ptr, length, capacity, alloc) }; ``` -------------------------------- ### Select Custom Struct Source: https://docs.rs/turbosql Retrieves data into a custom struct that derives Turbosql. Column names in the SQL must match the struct fields. ```rust let result = select!(Person "WHERE name = ?", name?); ``` -------------------------------- ### from<[T; N]> Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Allocates a `Vec` and moves `s`’s items into it. ```APIDOC fn from(s: [T; N]) -> Vec ##### §Examples ``` assert_eq!(Vec::from([1, 2, 3]), vec![1, 2, 3]); ``` ``` -------------------------------- ### now_ms() Source: https://docs.rs/turbosql/0.14.0/turbosql/fn.now_ms.html Returns the current time as milliseconds since the UNIX epoch. ```APIDOC ## now_ms() ### Description Convenience function that returns the current time as milliseconds since UNIX epoch. ### Signature ```rust pub fn now_ms() -> i64 ``` ### Returns - `i64`: The current time in milliseconds since the UNIX epoch. ``` -------------------------------- ### reserve_exact Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Reserves the minimum capacity for at least `additional` more elements. ```APIDOC ## pub fn reserve_exact(&mut self, additional: usize) ### Description Reserves the minimum capacity for at least `additional` more elements to be inserted in the given `Vec`. Unlike `reserve`, this will not deliberately over-allocate to speculatively avoid frequent allocations. After calling `reserve_exact`, capacity will be greater than or equal to `self.len() + additional`. Does nothing if the capacity is already sufficient. Note that the allocator may give the collection more space than it requests. Therefore, capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future insertions are expected. ### Parameters - **additional** (`usize`): The number of additional elements to reserve capacity for. ### Panics Panics if the new capacity exceeds `isize::MAX` _bytes_. ``` -------------------------------- ### ne (ByteStr comparison) Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html Tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. ```APIDOC ## fn ne(&self, other: &ByteStr) -> bool ### Description Tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. ### Parameters - **other** (&ByteStr) - Required - The ByteStr to compare with. ### Returns - bool - `true` if the vector is not equal to the ByteStr, `false` otherwise. ``` -------------------------------- ### Split Vec into initialized and spare capacity slices (Nightly) Source: https://docs.rs/turbosql/0.14.0/turbosql/type.Blob.html This nightly-only experimental API, `split_at_spare_mut()`, returns two slices: one for the initialized elements and one for the mutable spare capacity. It's a low-level optimization tool for advanced use cases, intended for scenarios where direct memory manipulation is necessary. ```rust #![feature(vec_split_at_spare)] let mut v = vec![1, 1, 2]; v.reserve(10); let (init, uninit) = v.split_at_spare_mut(); let sum = init.iter().copied().sum::(); uninit[0].write(sum); uninit[1].write(sum * 2); uninit[2].write(sum * 3); uninit[3].write(sum * 4); unsafe { let len = v.len(); v.set_len(len + 4); } assert_eq!(&v, &[1, 1, 2, 4, 8, 12, 16]); ```