Trying to fill a Rust vector with objects using higher order function - vector

I can create a Rust vector and fill it with struct instances using a loop, but I was wondering if I could get the same result using one of the higher order functions like map or such.
Here is some code that works:
#[derive(Debug)]
pub struct sim {
id: i32,
}
impl Default for sim {
fn default() -> sim {
sim { id: 4 }
}
}
fn main() {
let mut v2 = Vec::<sim>::new();
for i in 0..7 {
v2.push(sim::default())
}
println!("{:?}", v2);
}
I tried the code below, but it did not work.
let mut v3 = Vec::<sim>::new();
(0..7).map(|| v3.push(sim::default()));

Your immediate problem is: that isn't how map works at all. Mapping involves taking a sequence and transforming each element in said sequence, producing a new sequence. You should not be using it to just execute side effects for two reasons:
No one is going to expect you to do that, so your code will be more confusing than it should be to anyone else reading it.
Iterators in Rust are lazily computed, meaning that unless you consume the mapped iterator, nothing will happen.
If you really want to do something 7 times, just use a loop. That's what they're for. If you really, desperately need to do something like this, the itertools crate has a foreach method that does this whilst still communicating what's going on.
As to how to actually construct the collection using higher order functions...
#[derive(Clone, Debug)]
pub struct Sim {
id: i32,
}
impl Default for Sim {
fn default() -> Sim {
Sim { id: 4 }
}
}
fn main() {
use std::iter;
let v1 = vec![Sim::default(); 7];
let v2: Vec<_> = iter::repeat(Sim::default()).take(7).collect();
let v3: Vec<_> = (0..7).map(|_| Sim::default()).collect();
let v4: Vec<_> = iter::once(Sim::default()).cycle().take(7).collect();
}
There are probably more. Note that v1, v2, and v4 require the item type to be Clone so that it can make copies.

Related

How to pass a Reference / Pointer to a Rust Struct to a C ffi interface?

What I am trying to do
I have built a Rust interface, with which I want to interact via C (or C# but it does not really matter for the sake of the question). Because it does not seem to be possible to make a Rust Struct accessible to C I am trying to build some wrapper functions that I can call and that will create the Struct in Rust, call functions of the struct and eventually free the Struct from memory manually.
In order to do this I thought I would pass the pointer to the Struct instance that I create in the init function back to C (or C# and temporary store it as an IntPtr). Then when I call the other functions I would pass the pointer to Rust again, dereference it and call the appropriate functions on the dereferenced Struct, mutating it in the process.
I know that I will have to use unsafe code to do this and I am fine with that. I should probably also point out, that I don't know a lot about life-time management in Rust and it might very well be, that what I am trying to is impossible, because it is quite easy to produce a loose pointer somewhere. In that case, I would wonder how I would need to adjust my approach, because I think I am not the first person who is trying to mutate some sort of state from C inside Rust.
What I tried first
So first of all I made sure to output the correct library and add my native functions to it. In the Cargo.toml I set the lib type to:
[lib]
crate-type = ["cdylib"]
Then I created some functions to interact with the struct and exposed them like this:
#[no_mangle]
pub extern fn init() -> *mut MyStruct {
let mut struct_instance = MyStruct::default();
struct_instance.init();
let raw_pointer_mut = &mut struct_instance as *mut MyStruct;
return raw_pointer_mut;
}
#[no_mangle]
pub extern fn add_item(struct_instance_ref: *mut MyStruct) {
unsafe {
let struct_instance = &mut *struct_instance_ref;
struct_instance.add_item();
}
}
As you can see in the init function I am creating the struct and then I return the (mutable) pointer.
I then take the pointer in the add_item function and use it.
Now I tried to test this implementation, because I had some doubts about the pointer still beeing valid. In another Rust module I loaded the .dll and .lib files (I am on Windows, but that should not matter for the question) and then called the functions accordingly like so:
fn main() {
unsafe {
let struct_pointer = init();
add_item(struct_pointer);
println!("The pointer adress: {:?}", struct_pointer);
}
}
#[link(name = "my_library.dll")]
extern {
fn init() -> *mut u32;
fn add_item(struct_ref: *mut u32);
}
What happened: I did get some memory adress output and (because I am actually creating a file in the real implementation) I could also see that the functions were executed as planned. However the Struct's fields seem to be not mutated. They were basically all empty, what they should not have been after I called the add_item function (and also not after I called the init function).
What I tried after that
I read a bit on life-time management in Rust and therefore tried to allocate the Struct on the heap by using a Box like so:
#[no_mangle]
pub extern fn init() -> *mut Box<MyStruct> {
let mut struct_instance = MyStruct::default();
struct_instance.init();
let raw_pointer_mut = &mut Box::new(struct_instance) as *mut Box<MyStruct>;
return raw_pointer_mut;
}
#[no_mangle]
pub extern fn add_box(struct_instance_ref: *mut Box<MyStruct>) {
unsafe {
let struct_instance = &mut *struct_instance_ref;
struct_instance.add_box();
}
}
unfortunately the result was the same as above.
Additional Information
I figured it might be good to also include how the Struct is made up in principle:
#[derive(Default)]
#[repr(C)]
pub struct MyStruct{
// Some fields...
}
impl MyStruct{
/// Initializes a new struct.
pub fn init(&mut self) {
self.some_field = whatever;
}
/// Adds an item to the struct.
pub fn add_item(
&mut self,
maybe_more_data: of_type // Obviously the call in the external function would need to be adjusted to accomodate for that...
){
some_other_function(self); // Calls another function in Rust, that will take the struct instance as an argument and mutate it.
}
}
Rust has a strong notion of ownership. Ask yourself: who owns the MyStruct instance? It's the struct_instance variable, whose lifetime is the scope of the init() function. So after init() returns, the instance is dropped and an invalid pointer is returned.
Allocating the MyStruct on the heap would be the solution, but not in the way you tried: the instance is moved to the heap, but then the Box wrapper tied to the same problematic lifetime, so it destroys the heap-allocated object.
A solution is to use Box::into_raw to take the heap-allocated value back out of the box before the box is dropped:
#[no_mangle]
pub extern fn init() -> *mut MyStruct {
let mut struct_instance = MyStruct::default();
struct_instance.init();
let box = Box::new(struct_instance);
Box::into_raw(box)
}
To destroy the value later, use Box::from_raw to create a new Box that owns it, then let that box deallocate its contained value when it goes out of scope:
#[no_mangle]
pub extern fn destroy(struct_instance: *mut MyStruct) {
unsafe { Box::from_raw(struct_instance); }
}
This seems like a common problem, so there might be a more idiomatic solution. Hopefully someone more experienced will chime in.
I'm adding a simple answer for anyone who comes across this question but doesn't need to box - &mut struct_instance as *mut _ is the correct syntax to get a mutable pointer to a struct on the stack. This syntax is a bit tricky to find documented anywhere, it's easy to miss the initial mut.
Notably, this does not solve the original poster's issue, as returning a pointer to a local is undefined behavior. However, this is the correct solution for calling something via FFI (for which there don't seem to be any better results on Google).

How to create a read-only struct without boilerplate code?

Despite the fact that Rust has absorbed many good modern programming ideas, it looks like one very basic feature is not presented.
The modern (pseudo-)functional code is based on a large number of classes of the following kind:
pub struct NamedTuple {
a: i8,
b: char,
}
impl NamedTuple {
fn new(a: i8, b: char) -> NamedTuple {
NamedTuple { a: a, b: b }
}
fn a(&self) -> i8 {
self.a
}
fn b(&self) -> char {
self.b
}
}
As you can see, there is a lot of boilerplate code here. Is there really no way to describe such types compactly, without a boilerplate code?
When you have boilerplate, think macros:
macro_rules! ro {
(
pub struct $name:ident {
$($fname:ident : $ftype:ty),*
}
) => {
pub struct $name {
$($fname : $ftype),*
}
impl $name {
fn new($($fname : $ftype),*) -> $name {
$name { $($fname),* }
}
$(fn $fname(&self) -> $ftype {
self.$fname
})*
}
}
}
ro!(pub struct NamedTuple {
a: i8,
b: char
});
fn main() {
let n = NamedTuple::new(42, 'c');
println!("{}", n.a());
println!("{}", n.b());
}
This is a basic macro and could be extended to handle specifying visibility as well as attributes / documentation on the struct and the fields.
I'd challenge that you have as much boilerplate as you think you do. For example, you only show Copy types. As soon as you add a String or a Vec to your structs, this will fall apart and you need to either return a reference or take self.
Editorially, I don't think this is good or idiomatic Rust code. If you have a value type where people need to dig into it, just make the fields public:
pub struct NamedTuple {
pub a: i8,
pub b: char,
}
fn main() {
let n = NamedTuple { a: 42, b: 'c' };
println!("{}", n.a);
println!("{}", n.b);
}
Existing Rust features prevent most of the problems that getter methods attempt to solve in the first place.
Variable binding-based mutability
n.a = 43;
error[E0594]: cannot assign to field `n.a` of immutable binding
The rules of references
struct Something;
impl Something {
fn value(&self) -> &NamedTuple { /* ... */ }
}
fn main() {
let s = Something;
let n = s.value();
n.a = 43;
}
error[E0594]: cannot assign to field `n.a` of immutable binding
If you've transferred ownership of a value type to someone else, who cares if they change it?
Note that I'm making a distinction about value types as described by Growing Object-Oriented Software Guided by Tests, which they distinguish from objects. Objects should not have exposed internals.
Rust doesn't offer a built-in way to generate getters. However, there are multiple Rust features that can be used to tackle boilerplate code! The two most important ones for your question:
Custom Derives via #[derive(...)] attribute
Macros by example via macro_rules! (see #Shepmaster's answer on how to use those to solve your problem)
I think the best way to avoid boilerplate code like this is to use custom derives. This allows you to add a #[derive(...)] attribute to your type and generate these getters at compile time.
There is already a crate that offers exactly this: derive-getters. It works like this:
#[derive(Getters)]
pub struct NamedTuple {
a: i8,
b: char,
}
There is also getset, but it has two problems: getset should have derive in its crate name, but more importantly, it encourages the "getters & setters for everything" anti pattern by offering to also generate setters which don't perform any checks.
Finally, you might want to consider rethinking your approach to programming in Rust. Honestly, from my experience, "getter boilerplate" is hardly a problem. Sure, sometimes you need to write getters, but not "a large number" of them.
Mutability is also not unidiomatic in Rust. Rust is a multi paradigm language, supporting many styles of programming. Idiomatic Rust uses the most useful paradigm for each situation. Completely avoiding mutation might not be the best way to program in Rust. Furthermore, avoiding mutability is not only achieved by providing getters for your fields -- binding and reference mutability is far more important!
So, use read-only access to fields where it's useful, but not everywhere.

How does Rust know which types own resources?

When one has a box pointer to some heap-allocated memory, I assume that Rust has 'hardcoded' knowledge of ownership, so that when ownership is transferred by calling some function, the resources are moved and the argument in the function is the new owner.
However, how does this happen for vectors for example? They too 'own' their resources, and ownership mechanics apply like for box pointers -- yet they are regular values stored in variables themselves, and not pointers. How does Rust (know to) apply ownership mechanics in this situation?
Can I make my own type which owns resources?
tl;dr: "owning" types in Rust are not some magic and they are most certainly not hardcoded into the compiler or language. They are just types which written in a certain way (do not implement Copy and likely have a destructor) and have certain semantics which is enforced through non-copyability and the destructor.
In its core Rust's ownership mechanism is very simple and has very simple rules.
First of all, let's define what move is. It is simple - a value is said to be moved when it becomes available under a new name and stops being available under the old name:
struct X(u32);
let x1 = X(12);
let x2 = x1;
// x1 is no longer accessible here, trying to use it will cause a compiler error
Same thing happens when you pass a value into a function:
fn do_something(x: X) {}
let x1 = X(12);
do_something(x1);
// x1 is no longer accessible here
Note that there is absolutely no magic here - it is just that by default every value of every type behaves like in the above examples. Values of each struct or enum you or someone else creates by default will be moved.
Another important thing is that you can give every type a destructor, that is, a piece of code which is invoked when the value of this type goes out of scope and destroyed. For example, destructors associated with Vec or Box will free the corresponding piece of memory. Destructors can be declared by implementing Drop trait:
struct X(u32);
impl Drop for X {
fn drop(&mut self) {
println!("Dropping {}", x.0);
}
}
{
let x1 = X(12);
} // x1 is dropped here, and "Dropping 12" will be printed
There is a way to opt-out of non-copyability by implementing Copy trait which marks the type as automatically copyable - its values will no longer be moved but copied:
#[derive(Copy, Clone)] struct X(u32);
let x1 = X(12);
let x2 = x1;
// x1 is still available here
The copy is done bytewise - x2 will contain a byte-identical copy of x1.
Not every type can be made Copy - only those which have Copy interior and do not implement Drop. All primitive types (except &mut references but including *const and *mut raw pointers) are Copy in Rust, so each struct which contains only primitives can be made Copy. On the other hand, structs like Vec or Box are not Copy - they deliberately do not implement it because bytewise copy of them will lead to double frees because their destructors can be run twice over the same pointer.
The Copy bit above is a slight digression on my side, just to give a clearer picture. Ownership in Rust is based on move semantics. When we say that some value own something, like in "Box<T> owns the given T", we mean semantic connection between them, not something magical or something which is built into the language. It is just most such values like Vec or Box do not implement Copy and thus moved instead of copied, and they also (optionally) have a destructor which cleans up anything these types may have allocated for them (memory, sockets, files, etc.).
Given the above, of course you can write your own "owning" types. This is one of the cornerstones of idiomatic Rust, and a lot of code in the standard library and external libraries is written in such way. For example, some C APIs provide functions for creating and destroying objects. Writing an "owning" wrapper around them is very easy in Rust and it is probably very close to what you're asking for:
extern {
fn create_widget() -> *mut WidgetStruct;
fn destroy_widget(w: *mut WidgetStruct);
fn use_widget(w: *mut WidgetStruct) -> u32;
}
struct Widget(*mut WidgetStruct);
impl Drop for Widget {
fn drop(&mut self) {
unsafe { destroy_widget(self.0); }
}
}
impl Widget {
fn new() -> Widget { Widget(unsafe { create_widget() }) }
fn use_it(&mut self) -> u32 {
unsafe { use_widget(self.0) }
}
}
Now you can say that Widget owns some foreign resource represented by *mut WidgetStruct.
Here is another example of how a value might own memory and free it when the value is destroyed:
extern crate libc;
use libc::{malloc, free, c_void};
struct OwnerOfMemory {
ptr: *mut c_void
}
impl OwnerOfMemory {
fn new() -> OwnerOfMemory {
OwnerOfMemory {
ptr: unsafe { malloc(128) }
}
}
}
impl Drop for OwnerOfMemory {
fn drop(&mut self) {
unsafe { free(self.ptr); }
}
}
fn main() {
let value = OwnerOfMemory::new();
}

Where is the sine function?

Simple question: Where is sin()? I've searched and only found in the Rust docs that there are traits like std::num::Float that require sin, but no implementation.
The Float trait was removed, and the methods are inherent implementations on the types now (f32, f64). That means there's a bit less typing to access math functions:
fn main() {
let val: f32 = 3.14159;
println!("{}", val.sin());
}
However, it's ambiguous if 3.14159.sin() refers to a 32- or 64-bit number, so you need to specify it explicitly. Above, I set the type of the variable, but you can also use a type suffix:
fn main() {
println!("{}", 3.14159_f64.sin());
}
You can also use fully qualified syntax:
fn main() {
println!("{}", f32::sin(3.14159));
}
Real code should use the PI constant; I've used an inline number to avoid complicating the matter.
Float is Trait, include implementation, import this to apply for f32 or f64.
use std::num::Float;
fn main() {
println!("{}", 1.0f64.sin());
}

How to allocate space for a Vec<T> in Rust?

I want to create a Vec<T> and make some room for it, but I don't know how to do it, and, to my surprise, there is almost nothing in the official documentation about this basic type.
let mut v: Vec<i32> = Vec<i32>(SIZE); // How do I do this ?
for i in 0..SIZE {
v[i] = i;
}
I know I can create an empty Vec<T> and fill it with pushes, but I don't want to do that since I don't always know, when writing a value at index i, if a value was already inserted there yet. I don't want to write, for obvious performance reasons, something like :
if i >= len(v) {
v.push(x);
} else {
v[i] = x;
}
And, of course, I can't use the vec! syntax either.
While vec![elem; count] from the accepted answer is sufficient to create a vector with all elements equal to the same value, there are other convenience functions.
Vec::with_capacity() creates a vector with the given capacity but with zero length. It means that until this capacity is reached, push() calls won't reallocate the vector, making push() essentially free:
fn main() {
let mut v = Vec::with_capacity(10);
for i in 0..10 {
v.push(i);
}
println!("{:?}", v);
}
You can also easily collect() a vector from an iterator. Example:
fn main() {
let v: Vec<_> = (1..10).collect();
println!("{:?}", v);
}
And finally, sometimes your vector contains values of primitive type and is supposed to be used as a buffer (e.g. in network communication). In this case you can use Vec::with_capacity() + set_len() unsafe method:
fn main() {
let mut v = Vec::with_capacity(10);
unsafe { v.set_len(10); }
for i in 0..10 {
v[i] = i;
}
println!("{:?}", v);
}
Note that you have to be extra careful if your vector contains values with destructors or references - it's easy to get a destructor run over a uninitialized piece of memory or to get an invalid reference this way. It will also work right if you only use initialized part of the vector (you have to track it yourself now). To read about all the possible dangers of uninitialized memory, you can read the documentation of mem::uninitialized().
You can use the first syntax of the vec! macro, specifically vec![elem; count]. For example:
vec![1; 10]
will create a Vec<_> containing 10 1s (the type _ will be determined later or default to i32). The elem given to the macro must implement Clone. The count can be a variable, too.
There is the Vec::resize method:
fn resize(&mut self, new_len: usize, value: T)
This code resizes an empty vector to 1024 elements by filling with the value 7:
let mut vec: Vec<i32> = Vec::new();
vec.resize(1024, 7);

Resources