Skip to content

Commit bc1316a

Browse files
author
David Rajchenbach-Teller
committed
[Stdlib] rope.rs: concat, now attempts to preserve balance
1 parent cefa97d commit bc1316a

File tree

1 file changed

+28
-6
lines changed

1 file changed

+28
-6
lines changed

src/lib/rope.rs

+28-6
Original file line numberDiff line numberDiff line change
@@ -173,14 +173,36 @@ fn append_rope(left: rope, right: rope) -> rope {
173173
/*
174174
Function: concat
175175
176-
Concatenate many ropes
176+
Concatenate many ropes.
177+
178+
If the ropes are balanced initially and have the same height, the resulting
179+
rope remains balanced. However, this function does not take any further
180+
measure to ensure that the result is balanced.
177181
*/
178182
fn concat(v: [rope]) -> rope {
179-
let acc = node::empty;
180-
for r: rope in v {
181-
acc = append_rope(acc, r);
182-
}
183-
ret bal(acc);
183+
//Copy `v` into a mutable vector
184+
let len = vec::len(v);
185+
if len == 0u { ret node::empty; }
186+
let ropes = vec::init_elt_mut(v[0], len);
187+
uint::range(1u, len) {|i|
188+
ropes[i] = v[i];
189+
}
190+
191+
//Merge progresively
192+
while len > 1u {
193+
uint::range(0u, len/2u) {|i|
194+
ropes[i] = append_rope(ropes[2u*i], ropes[2u*i+1u]);
195+
}
196+
if len%2u != 0u {
197+
ropes[len/2u] = ropes[len - 1u];
198+
len = len/2u + 1u;
199+
} else {
200+
len = len/2u;
201+
}
202+
}
203+
204+
//Return final rope
205+
ret ropes[0];
184206
}
185207

186208

0 commit comments

Comments
 (0)