Repository navigation
Expand file tree
/
Copy pathvec_vs_owned_vec.mere
More file actions
48 lines (42 loc) · 1.69 KB
/
Copy pathvec_vs_owned_vec.mere
File metadata and controls
48 lines (42 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// Phase 12.5: Demo contrasting Vec[R, T] (in-region, Trivial) with
// OwnedVec[T] (heap, with Drop). Implements the "separate types" part of
// the design doc 13_region_std_types.md §9 "(b) separate types + trait
// for unified API".
//
// - Vec[R, T]: placeable in a region; freed in bulk at end of scope; Trivial
// - OwnedVec[T]: heap-allocated; Drop type; not placeable in a region
//
// Internal implementation is the same V_vec (mutable array). They are
// treated as separate things only at the type-system level.
// === Pattern 1: temporary scratch — Vec[R, T] inside a region ===
let regional_sum =
region R {
let v = vec_new () in // type: Vec[R, int] (bound to region R)
{
vec_push v 1;
vec_push v 2;
vec_push v 3;
vec_get v 0 + vec_get v 1 + vec_get v 2
}
} in
// The moment you leave the region, v is invalid. Trying to escape is a type error:
// region R { let v = vec_new () in &R v }
// ^ region escape: value of type `Vec[R, int]` cannot leave region
// === Pattern 2: long-term hold — heap OwnedVec[T] ===
let lasting = owned_vec_new () in // type: int OwnedVec
{
owned_vec_push lasting 100;
owned_vec_push lasting 200;
owned_vec_push lasting 300;
// OwnedVec is a Drop type, so it can't be placed in a region:
// region R { let v = owned_vec_new () in &R v }
// ^ Trivial[R] violated: cannot place value of type `'a OwnedVec`
// into region — type contains a Drop type
print ("regional_sum = " ++ show regional_sum);
print ("lasting len = " ++ show (owned_vec_len lasting));
print ("lasting[1] = " ++ show (owned_vec_get lasting 1))
}
// Expected output:
// regional_sum = 6
// lasting len = 3
// lasting[1] = 200