4 ms·
I've run into two kinds of problems that require unsafe so far. The first is similar to the c extension you described - building data structures with dynamical
by jamii 11y ago
I've run into two kinds of problems that require unsafe so far.
The first is similar to the c extension you described - building data structures with dynamically-sized arrays eg a bitfield followed by population_count(bitfield) entries. It would be great to have some way to express this without having to pay a whole usize for DST eg:
struct Node{
keys: u8,
vals: [ShortPointer<Node>; popcount(keys)],
}
The second is dealing with recursive data-structures or algorithms. Even for tree-shaped stuff, if you are hanging onto state as you walk the tree there are some kinds of patterns that the borrow checker just can't deal with eg
fn join_step<'a>(state: &mut Vec<&'a Value>, ..) {
...
for values in primitive.eval_from_join(&arguments[..], &state[..]).into_iter() {
// promise the borrow checker that we will pop values before we exit this scope
let values = unsafe { ::std::mem::transmute::<&Vec<Value>, &'a Vec<Value>>(&values) };
push_all(state, values);
if join.constraints[ix].iter().all(|constraint| constraint.is_satisfied_by(&state[..])) {
join_step(state, ...)
}
pop_all(state, values);
}
}
It would be nice to have some finer-grained way of making this promise - transmute is overkill and leaves me open to all kinds of mistakes.
- Gankro 11y agoIf you're just trying to demote a lifetime, you should just be able to specify the lifetime on the variable: let values: &'a Vec<Value> = &values; Lifetimes have variance so that you can always put a "bigger" lifetime in a place expecting a "smaller" one safely and it will treated as the smaller one forever. Although it can be a bit of a dangerous game trying to "set" lifetimes manually because lifetime variance is hell (at least to me).
- jamii 11y agoI think that I'm actually doing the opposite - the lifetime of the state vec is longer than the lifetime of values but it's ok in this case because I pop the values again before they die. What I want to do is temporarily demote the lifetime of the state vec for the recursive call. Here is a really simplified version that illustrates the problem - http://is.gd/8AZvZe http://is.gd/8AZvZe