set_slice
A Rust macro for easily assigning to slices
rules for using set_slice
- you can only use slices, or anything coerces to a slice
- lvalues must either be identifiers or indexes
- identifier: array, b, vector, something_else
- indexes: array[1..], b[..], vector[1..4], something_else[12..=14]
- range checks are all done at run-time
- the input slice must be the same size as the slice you assign to
- the types must match
- note: set_slice uses a generic function internally to figure out type information
- for unsafe copy values, the size of the slice must be known at compile time, as a constexpr
- for safe references assignments, the internal types must be Clone or Copy to work
set_slice by example
you can set the entire contents of the slice to whatever you want
let slice = &mut as &mut ; // this is to simulate having only a slice without knowning its size
set_slice!
assert_eq!;
// ... or you can only set parts of the slice
let slice = &mut as &mut ;
set_slice!
assert_eq!;
you can also do multiple assigns in one macro call
let slice = &mut as &mut ;
set_slice!
assert_eq!;
You can use expressions to set to the slices, either as values to be moved in, or as references if they are move values you must specify a const expression size in parentheses
let slice = &mut as &mut ;
let array = ;
let vec = vec!;
set_slice!
println!; // fine, array is a copy type
// println!("vec = {:?}", vec); // compile time error, vec is moved into the set_slice and dropped
assert_eq!;
but you don't have to move into set_slice if you get a reference with references you must specify if the contents should be copied or cloned but they must derive Copy or Clone respectively
let slice = &mut as &mut ;
let array = ;
let vec = vec!;
set_slice!
println!; // this is fine, array was borrowed
println!; // this is fine, vec was borrowed
assert_eq!;
;
let slice: = ;
let slice = &mut slice as &mut ;
let array = ;
let vec = vec!;
set_slice!
println!; // this is fine, array was borrowed
println!; // this is fine, vec was borrowed
assert_eq!;
valid use cases
with lists, and ranges
these ranges can be mixed and matched with the other sub-sections
let slice = &mut as &mut ;
let init = 1;
let end = 2;
set_slice!
println!;
panic!;
with move types
let slice = &mut as &mut ;
let vec_move = vec!;
set_slice!
let vec_move = vec!;
set_slice!
let vec_move = vec!;
set_slice!
with references
let slice = &mut as &mut ;
let array = ;
let vec = vec!;
// only works if slice implements copy
set_slice!
// only works if slice implements clone
set_slice!
// works with any type, but is incredibly unsafe
set_slice!
known undefined behaviour or unintended
all of these are when using unsafe slice assignment
- an array of Boxed values share the inner values after assignment
- an array of Mutexes may become corrupted
- an array of Arc<Mutex> is fine