rust

Is it undefined behavior to do runtime borrow management with the help of raw pointers in Rust?

…衆ロ難τιáo~ 提交于 2020-01-14 19:50:51
问题 As part of binding a C API to Rust, I have a mutable reference ph: &mut Ph , a struct struct EnsureValidContext<'a> { ph: &'a mut Ph } , and some methods: impl Ph { pub fn print(&mut self, s: &str) { /*...*/ } pub fn with_context<F, R>(&mut self, ctx: &Context, f: F) -> Result<R, InvalidContextError> where F: Fn(EnsureValidContext) -> R, { /*...*/ } /* some others */ } impl<'a> EnsureValidContext<'a> { pub fn print(&mut self, s: &str) { self.ph.print(s) } pub fn close(self) {} /* some others

Drop a immutable borrow to make a mutable borrow

痴心易碎 提交于 2020-01-14 19:29:05
问题 I am still learning Rust and when trying to implement Dikjstra as part of a training project, I encountered this peculiar catch. First I define a HashMap : let mut dist: HashMap<Node, usize> = HashMap::new(); And later: let state = State { node: next_node.clone(), cost: cost + 1 }; let current_dist = dist.get(&state.node); if (current_dist == None) || (state.cost < *current_dist.unwrap()) { dist.insert(state.node.clone(), state.cost); heap.push(state); } Which yields a compile error because

Rudimentary Tree, and Pointers, in Rust

喜夏-厌秋 提交于 2020-01-14 18:50:31
问题 Coming from a scripting language background with some C, trying to 'learn' Rust leads me to question my competence. I'm trying to figure out how to change an owned pointer, and struggling to do it. Besides copying in from the extra libs, I can't figure out the recursion I need on a binary tree. Particularly, I don't know how to swap out the pointer branches. Whereas with a linked list I can cheat and use a temporary vector to return a new list, or prepend a new Cons(value, ~Cons) to the list

Rudimentary Tree, and Pointers, in Rust

女生的网名这么多〃 提交于 2020-01-14 18:49:27
问题 Coming from a scripting language background with some C, trying to 'learn' Rust leads me to question my competence. I'm trying to figure out how to change an owned pointer, and struggling to do it. Besides copying in from the extra libs, I can't figure out the recursion I need on a binary tree. Particularly, I don't know how to swap out the pointer branches. Whereas with a linked list I can cheat and use a temporary vector to return a new list, or prepend a new Cons(value, ~Cons) to the list

Creating a Vec in Rust from a C array pointer and safely freeing it?

只谈情不闲聊 提交于 2020-01-14 14:13:32
问题 I'm calling a C function from Rust which takes a null pointer as as an argument, then allocates some memory to point it to. What is the correct way to efficiently (i.e. avoiding unnecessary copies) and safely (i.e. avoid memory leaks or segfaults) turn data from the C pointer into a Vec ? I've got something like: extern "C" { // C function that allocates an array of floats fn allocate_data(data_ptr: *mut *const f32, data_len: *mut i32); } fn get_vec() -> Vec<f32> { // C will set this to

Creating a Vec in Rust from a C array pointer and safely freeing it?

谁说我不能喝 提交于 2020-01-14 14:13:26
问题 I'm calling a C function from Rust which takes a null pointer as as an argument, then allocates some memory to point it to. What is the correct way to efficiently (i.e. avoiding unnecessary copies) and safely (i.e. avoid memory leaks or segfaults) turn data from the C pointer into a Vec ? I've got something like: extern "C" { // C function that allocates an array of floats fn allocate_data(data_ptr: *mut *const f32, data_len: *mut i32); } fn get_vec() -> Vec<f32> { // C will set this to

When to use Box<Vec<..>> or Vec<Box<..>>?

会有一股神秘感。 提交于 2020-01-14 10:39:28
问题 When would it make sense to design a data structure that is nesting a Box and a Vec (or vice versa)? It seems like in most situations where you want to store multiple fixed-size things on the heap, the Box is redundant, since it's only (?) role is to heap-allocate a ~single value, and a normal Vec is already heap allocating it's storage. Context: I am still wrapping my head around the roles of the various Rust types for building up data structures. 回答1: There are really only a few times you

Splitting Iterator<(A,B)> into Iterator<A> and Iterator<B>

混江龙づ霸主 提交于 2020-01-14 10:16:30
问题 I would like to split the output of an object that implements Iterator<(A,B)> into two objects that implement Iterator<A> and Iterator<B> . Since one of the outputs could be iterated more than the other, I'll need to buffer up the output of the Iterator<(A,B)> (because I can't rely on the Iterator<(A,B)> being cloneable.) The problem is that the iterator could be infinite, so I can't simply collect the output of the iterator into two buffers and return iterators over the two buffers. So it

How do I use a Condvar to limit multithreading?

霸气de小男生 提交于 2020-01-14 09:38:19
问题 I'm trying to use a Condvar to limit the number of threads that are active at any given time. I'm having a hard time finding good examples on how to use Condvar . So far I have: use std::sync::{Arc, Condvar, Mutex}; use std::thread; fn main() { let thread_count_arc = Arc::new((Mutex::new(0), Condvar::new())); let mut i = 0; while i < 100 { let thread_count = thread_count_arc.clone(); thread::spawn(move || { let &(ref num, ref cvar) = &*thread_count; { let mut start = num.lock().unwrap(); if

How do I count unique grapheme clusters in a string in Rust?

做~自己de王妃 提交于 2020-01-14 09:32:16
问题 For example, for let n = count_unique_grapheme_clusters("🇧🇷 🇷🇺 🇧🇷 🇺🇸 🇧🇷"); println!("{}", n); the expected output is (space and three flags: " " , "🇧🇷" , "🇷🇺" , "🇺🇸" ): 4 回答1: We can use the graphemes method from unicode-segmentation crate to iterate over the grapheme clusters and save them in a HashSet<&str> to filter out the duplicates. Then we get the .len() of the container. extern crate unicode_segmentation; // 1.2.1 use std::collections::HashSet; use unicode_segmentation: