|
1 | 1 | # This file is a part of Julia. License is MIT: http://julialang.org/license
|
2 | 2 |
|
3 |
| -# SubString, RevString, and RepString types |
| 3 | +# SubString, RevString, RepString, and RopeString types |
4 | 4 |
|
5 | 5 | ## substrings reference original strings ##
|
6 | 6 |
|
@@ -176,3 +176,49 @@ function repeat(s::ByteString, r::Integer)
|
176 | 176 | end
|
177 | 177 |
|
178 | 178 | (^)(s::AbstractString, r::Integer) = repeat(s,r)
|
| 179 | + |
| 180 | +## ropes for efficient concatenation, etc. ## |
| 181 | + |
| 182 | +immutable RopeString <: AbstractString |
| 183 | + head::AbstractString |
| 184 | + tail::AbstractString |
| 185 | + depth::Int32 |
| 186 | + endof::Int |
| 187 | + |
| 188 | + RopeString(h::RopeString, t::RopeString) = |
| 189 | + strdepth(h.tail) + strdepth(t) < strdepth(h.head) ? |
| 190 | + RopeString(h.head, RopeString(h.tail, t)) : |
| 191 | + new(h, t, max(h.depth,t.depth)+1, endof(h)+endof(t)) |
| 192 | + |
| 193 | + RopeString(h::RopeString, t::AbstractString) = |
| 194 | + strdepth(h.tail) < strdepth(h.head) ? |
| 195 | + RopeString(h.head, RopeString(h.tail, t)) : |
| 196 | + new(h, t, h.depth+1, endof(h)+endof(t)) |
| 197 | + |
| 198 | + RopeString(h::AbstractString, t::RopeString) = |
| 199 | + strdepth(t.head) < strdepth(t.tail) ? |
| 200 | + RopeString(RopeString(h, t.head), t.tail) : |
| 201 | + new(h, t, t.depth+1, endof(h)+endof(t)) |
| 202 | + |
| 203 | + RopeString(h::AbstractString, t::AbstractString) = |
| 204 | + new(h, t, 1, endof(h)+endof(t)) |
| 205 | +end |
| 206 | +RopeString(s::AbstractString) = RopeString(s,"") |
| 207 | + |
| 208 | +strdepth(s::AbstractString) = 0 |
| 209 | +strdepth(s::RopeString) = s.depth |
| 210 | + |
| 211 | +function next(s::RopeString, i::Int) |
| 212 | + eh = endof(s.head) |
| 213 | + if i <= eh |
| 214 | + return next(s.head, i) |
| 215 | + else |
| 216 | + c, j = next(s.tail, i-eh) |
| 217 | + return c, j+eh |
| 218 | + end |
| 219 | +end |
| 220 | + |
| 221 | +endof(s::RopeString) = s.endof |
| 222 | +length(s::RopeString) = length(s.head) + length(s.tail) |
| 223 | +write(io::IO, s::RopeString) = (write(io, s.head); write(io, s.tail)) |
| 224 | +sizeof(s::RopeString) = sizeof(s.head) + sizeof(s.tail) |
0 commit comments