1 # This file is part of NIT (http://www.nitlanguage.org).
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
15 # Tree-based representation of a String.
17 # Ropes are a data structure introduced in a 1995 paper from
18 # Hans J. Boehm, Russ Atkinson and Michael Plass.
22 # > Ropes: an Alternative to Strings,
23 # > *Software - Practice and Experience*,
24 # > Vol. 25(12), 1315-1330 (December 1995).
26 # The implementation developed here provides an automatic change
27 # of data structure depending on the length of the leaves.
29 # The length from which a `Rope` is built from a `flat` string
30 # if defined at top-level (see `maxlen`) and can be redefined by clients
31 # depending on their needs (e.g. if you need to bench the speed of
32 # the creation of concat nodes, lower the size of maxlen).
34 # A Rope as defined in the original paper is a Tree made of concatenation
35 # nodes and containing `Flat` (that is Array-based) strings as Leaves.
43 # "My" " Name" " is" " Simon."
45 # Note that the above example is not representative of the actual implementation
46 # of `Ropes`, since short leaves are merged to keep the rope at an acceptable
47 # height (hence, this rope here might actually be a `FlatString` !).
52 # Maxlen is the maximum length of a Leaf node
54 # When concatenating two leaves, if `new_length` > `maxlen`,
55 # A `Concat` node is created instead
57 # Its purpose is to limit the depth of the `Rope` (this
58 # improves performance when accessing/iterating).
59 fun maxlen
: Int do return 64
61 # String using a tree-based representation with leaves as `FlatStrings`
62 private abstract class Rope
66 private abstract class RopeString
70 redef var chars
is lazy
do return new RopeChars(self)
73 # Node that represents a concatenation between two `String`
77 redef var length
is noinit
79 redef fun substrings
do return new RopeSubstrings(self)
81 redef fun empty
do return ""
83 redef var to_cstring
is lazy
do
85 var ns
= new NativeString(len
+ 1)
88 for i
in substrings
do
90 i
.as(FlatString).items
.copy_to
(ns
, ilen
, i
.as(FlatString).index_from
, off
)
96 # Left child of the node
98 # Right child of the node
102 length
= left
.length
+ right
.length
110 redef fun iterator
do return new RopeIter(self)
114 for j
in [1 .. i
[ do x
+= self
119 var llen
= left
.length
120 if i
>= llen
then return right
[i
- llen
]
124 redef fun substring
(from
, len
) do
125 var llen
= left
.length
127 if from
+ len
< llen
then return left
.substring
(from
,len
)
128 var lsublen
= llen
- from
129 return left
.substring_from
(from
) + right
.substring
(0, len
- lsublen
)
131 return right
.substring
(from
- llen
, len
)
135 redef fun reversed
do return new Concat(right
.reversed
, left
.reversed
)
137 redef fun insert_at
(s
, pos
) do
138 if pos
> left
.length
then
139 return left
+ right
.insert_at
(s
, pos
- left
.length
)
141 return left
.insert_at
(s
, pos
) + right
144 redef fun to_upper
do return new Concat(left
.to_upper
, right
.to_upper
)
146 redef fun to_lower
do return new Concat(left
.to_lower
, right
.to_lower
)
152 return new Concat(self, s
)
156 if rlen
+ slen
> maxlen
then return new Concat(self, s
)
157 return new Concat(left
, r
+ s
)
161 redef fun copy_to_native
(dest
, n
, src_offset
, dest_offset
) do
162 var subs
= new RopeSubstrings.from
(self, src_offset
)
163 var st
= src_offset
- subs
.pos
164 var off
= dest_offset
167 if n
> it
.length
then
168 var cplen
= it
.length
- st
169 it
.items
.copy_to
(dest
, cplen
, st
, off
)
173 it
.items
.copy_to
(dest
, n
, st
, off
)
182 # Mutable `Rope`, optimized for concatenation operations
184 # A `RopeBuffer` is an efficient way of building a `String` when
185 # concatenating small strings.
187 # It does concatenations in an optimized way by having a
188 # mutable part and an immutable part built by efficiently
189 # concatenating strings in chain.
191 # Every concatenation operation is done by copying a string to
192 # the mutable part and flushing it when full.
194 # However, when a long string is appended to the `Buffer`,
195 # the concatenation is done at it would be in a `Rope`.
200 redef var chars
: Sequence[Char] is lazy
do return new RopeBufferChars(self)
202 # The final string being built on the fly
203 private var str
: String is noinit
205 # Current concatenation buffer
206 private var ns
: NativeString is noinit
208 # Next available (e.g. unset) character in the `Buffer`
211 # Keeps track of the buffer's currently dumped part
213 # This might happen if for instance, a String was being
214 # built by concatenating small parts of string and suddenly
215 # a long string (length > maxlen) is appended.
216 private var dumped
: Int is noinit
218 # Length of the complete rope
221 # Length of the mutable part
223 # Is also used as base to compute the size of the next
224 # mutable native string (`ns`)
225 private var buf_size
: Int is noinit
227 redef fun substrings
do return new RopeBufSubstringIterator(self)
229 # Builds an empty `RopeBuffer`
232 ns
= new NativeString(maxlen
)
237 # Builds a new `RopeBuffer` with `str` in it.
238 init from
(str
: String) do
240 ns
= new NativeString(maxlen
)
246 # Resets the informations of the `Buffer`
248 # This is called when doing in-place modifications
249 # on a previously to_s'd `RopeBuffer`
251 var nns
= new NativeString(buf_size
)
252 var blen
= rpos
- dumped
253 ns
.copy_to
(nns
, blen
, dumped
, 0)
260 redef fun empty
do return new RopeBuffer
268 ns
= new NativeString(buf_size
)
273 redef fun substring
(from
, count
) do
274 var strlen
= str
.length
278 if count
< 0 then count
= 0
282 if count
> length
then count
= length
- from
284 if count
== 0 then return empty
286 if from
< strlen
then
287 var subpos
= strlen
- from
288 if count
<= subpos
then
289 return new RopeBuffer.from
(str
.substring
(from
, count
))
291 var l
= str
.substring_from
(from
)
292 var rem
= count
- subpos
293 var nns
= new NativeString(rem
)
294 ns
.copy_to
(nns
, rem
, dumped
, 0)
295 return new RopeBuffer.from
(l
+ nns
.to_s_with_length
(rem
))
298 var nns
= new NativeString(count
)
299 ns
.copy_to
(nns
, count
, dumped
, 0)
300 return new RopeBuffer.from
(nns
.to_s_with_length
(count
))
304 redef fun append
(s
) do
308 if s
isa Rope or slen
> maxlen
then
309 if rp
> 0 and dumped
!= rp
then
310 str
+= new FlatString.with_infos
(ns
, rp
- dumped
, dumped
, rp
- 1)
316 var remsp
= buf_size
- rp
317 var sits
: NativeString
319 if s
isa FlatString then
322 else if s
isa FlatBuffer then
326 if slen
<= remsp
then
333 for i
in [0..remsp
[ do
347 if slen
<= remsp
then
352 sits
.copy_to
(ns
, slen
, begin
, rp
)
356 sits
.copy_to
(ns
, remsp
, begin
, rp
)
359 var nlen
= slen
- remsp
360 sits
.copy_to
(ns
, nlen
, begin
+ remsp
, 0)
367 if rp
>= buf_size
then
377 # Converts the Buffer to a FlatString, appends it to
378 # the final String and re-allocates a new larger Buffer.
379 private fun dump_buffer
do
381 var nstr
= new FlatString.with_infos
(ns
, rpos
- dumped
, dumped
, rpos
- 1)
385 ns
= new NativeString(bs
)
392 new FlatString.with_infos
(ns
, rpos
- dumped
, dumped
, rpos
- 1).output
395 # Enlarge is useless here since the `Buffer`
396 # part is automatically dumped when necessary.
398 # Also, since the buffer can not be overused by a
399 # single string, there is no need for manual
402 # "You have no power here !"
403 redef fun enlarge
(i
) do end
407 var nnslen
= rpos
- dumped
408 if nnslen
== 0 then return str
409 return str
+ new FlatString.with_infos
(ns
, rpos
- dumped
, dumped
, rpos
- 1)
413 # Flush the buffer in order to only have to reverse `str`.
414 if rpos
> 0 and dumped
!= rpos
then
415 str
+= new FlatString.with_infos
(ns
, rpos
- dumped
, dumped
, rpos
- 1)
422 if written
then reset
425 for i
in [0 .. rpos
[ do
426 mits
[i
] = mits
[i
].to_upper
431 if written
then reset
434 for i
in [0 .. rpos
[ do
435 mits
[i
] = mits
[i
].to_lower
440 redef class FlatString
442 redef fun insert_at
(s
, pos
) do
443 var l
= substring
(0, pos
)
444 var r
= substring_from
(pos
)
452 if slen
== 0 then return self
453 if mlen
== 0 then return s
454 var nlen
= slen
+ mlen
455 if s
isa FlatString then
456 if nlen
> maxlen
then return new Concat(self, s
)
458 var sifrom
= s
.index_from
459 var mifrom
= index_from
461 var ns
= new NativeString(nlen
+ 1)
462 mits
.copy_to
(ns
, mlen
, mifrom
, 0)
463 sits
.copy_to
(ns
, slen
, sifrom
, mlen
)
464 return ns
.to_s_with_length
(nlen
)
465 else if s
isa Concat then
467 var sllen
= sl
.length
468 if sllen
+ mlen
> maxlen
then return new Concat(self, s
)
469 return new Concat(self + sl
, s
.right
)
476 # A simple linked list for use with iterators
477 private class RopeIterPiece
478 # The encapsulated node of the `Rope`
480 # Was its left child (if any) visited ?
482 # Was its right child (if any) visited ?
484 # The previous node in the list.
485 var prev
: nullable RopeIterPiece
488 # A reverse iterator capable of working with `Rope` objects
489 private class RopeReviter
490 super IndexedIterator[Char]
492 # Current NativeString
494 # Current position in NativeString
496 # Position in the Rope (0-indexed)
498 # Iterator on the substrings, does the Postfix part of
499 # the Rope traversal.
500 var subs
: IndexedIterator[String]
502 init(root
: RopeString) is old_style_init
do
503 pos
= root
.length
- 1
504 subs
= new ReverseRopeSubstrings(root
)
509 init from
(root
: RopeString, pos
: Int) do
511 subs
= new ReverseRopeSubstrings.from
(root
, pos
)
513 pns
= pos
- subs
.index
516 redef fun index
do return pos
518 redef fun is_ok
do return pos
>= 0
520 redef fun item
do return ns
[pns
]
525 if pns
>= 0 then return
526 if not subs
.is_ok
then return
528 if not subs
.is_ok
then return
534 # Forward iterator on the chars of a `Rope`
535 private class RopeIter
536 super IndexedIterator[Char]
538 # Position in current `String`
540 # Current `String` being iterated on
542 # Substrings of the Rope
543 var subs
: IndexedIterator[String]
544 # Maximum position to iterate on (e.g. Rope.length)
546 # Position (char) in the Rope (0-indexed)
549 init(root
: RopeString) is old_style_init
do
550 subs
= new RopeSubstrings(root
)
553 max
= root
.length
- 1
557 init from
(root
: RopeString, pos
: Int) do
558 subs
= new RopeSubstrings.from
(root
, pos
)
559 pns
= pos
- subs
.index
562 max
= root
.length
- 1
565 redef fun item
do return str
[pns
]
567 redef fun is_ok
do return pos
<= max
569 redef fun index
do return pos
574 if pns
< subs
.item
.length
then return
575 if not subs
.is_ok
then return
577 if not subs
.is_ok
then return
583 # Substrings of a Rope (i.e. Reverse postfix iterator on leaves)
584 private class ReverseRopeSubstrings
585 super IndexedIterator[String]
588 var iter
: RopeIterPiece is noinit
590 var pos
: Int is noinit
593 var str
: String is noinit
595 init(root
: RopeString) is old_style_init
do
596 var r
= new RopeIterPiece(root
, false, true, null)
597 pos
= root
.length
- 1
598 var lnod
: String = root
600 if lnod
isa Concat then
602 r
= new RopeIterPiece(lnod
, false, true, r
)
611 init from
(root
: RopeString, pos
: Int) do
612 var r
= new RopeIterPiece(root
, false, true, null)
613 var rnod
: String = root
616 if rnod
isa Concat then
617 if off
>= rnod
.left
.length
then
618 off
-= rnod
.left
.length
620 r
= new RopeIterPiece(rnod
, false, true, r
)
624 r
= new RopeIterPiece(rnod
, false, true, r
)
636 redef fun item
do return str
638 redef fun index
do return pos
640 redef fun is_ok
do return pos
>= 0
643 if pos
< 0 then return
645 var currit
= curr
.node
646 while curr
!= null do
648 if not currit
isa Concat then
654 if not curr
.rdone
then
656 curr
= new RopeIterPiece(currit
.right
, false, false, curr
)
659 if not curr
.ldone
then
661 curr
= new RopeIterPiece(currit
.left
, false, false, curr
)
670 private class RopeBufSubstringIterator
671 super Iterator[FlatText]
673 # Iterator on the substrings of the building string
674 var iter
: Iterator[FlatText]
675 # Makes a String out of the buffered part of the Ropebuffer
676 var nsstr
: FlatString
677 # Did we attain the buffered part ?
678 var nsstr_done
= false
680 init(str
: RopeBuffer) is old_style_init
do
681 iter
= str
.str
.substrings
682 nsstr
= new FlatString.with_infos
(str
.ns
, str
.rpos
- str
.dumped
, str
.dumped
, str
.rpos
- 1)
683 if str
.length
== 0 then nsstr_done
= true
686 redef fun is_ok
do return iter
.is_ok
or not nsstr_done
690 if iter
.is_ok
then return iter
.item
703 # Substrings of a Rope (i.e. Postfix iterator on leaves)
704 private class RopeSubstrings
705 super IndexedIterator[FlatString]
708 var iter
: RopeIterPiece is noinit
710 var pos
: Int is noinit
711 # Maximum position in `Rope` (i.e. length - 1)
712 var max
: Int is noinit
715 var str
: FlatString is noinit
717 init(root
: RopeString) is old_style_init
do
718 var r
= new RopeIterPiece(root
, true, false, null)
720 max
= root
.length
- 1
721 var rnod
: String = root
723 if rnod
isa Concat then
725 r
= new RopeIterPiece(rnod
, true, false, r
)
727 str
= rnod
.as(FlatString)
735 init from
(root
: RopeString, pos
: Int) do
736 var r
= new RopeIterPiece(root
, true, false, null)
737 max
= root
.length
- 1
738 var rnod
: String = root
741 if rnod
isa Concat then
742 if off
>= rnod
.left
.length
then
744 off
-= rnod
.left
.length
746 r
= new RopeIterPiece(rnod
, true, false, r
)
749 r
= new RopeIterPiece(rnod
, true, false, r
)
752 str
= rnod
.as(FlatString)
761 redef fun item
do return str
763 redef fun is_ok
do return pos
<= max
765 redef fun index
do return pos
769 if pos
> max
then return
773 if not rnod
isa Concat then
776 str
= rnod
.as(FlatString)
777 iter
= it
.as(not null)
783 it
= new RopeIterPiece(rnod
, false, false, it
)
784 else if not it
.rdone
then
787 it
= new RopeIterPiece(rnod
, false, false, it
)
797 # Implementation of a `StringCharView` for `RopeString` objects
798 private class RopeChars
801 redef type SELFTYPE: RopeString
807 redef fun iterator_from
(i
) do return new RopeIter.from
(target
, i
)
809 redef fun reverse_iterator_from
(i
) do return new RopeReviter.from
(target
, i
)
813 # An Iterator over a RopeBuffer.
815 super IndexedIterator[Char]
818 var sit
: IndexedIterator[Char]
820 # Native string iterated over.
823 # Current position in `ns`.
826 # Maximum position iterable.
831 # Init the iterator from a RopeBuffer.
832 init(t
: RopeBuffer) is old_style_init
do
835 sit
= t
.str
.chars
.iterator
840 # Init the iterator from a RopeBuffer starting from `pos`.
841 init from
(t
: RopeBuffer, pos
: Int) do
844 sit
= t
.str
.chars
.iterator_from
(pos
)
845 pns
= pos
- t
.str
.length
849 redef fun is_ok
do return index
< maxpos
852 if sit
.is_ok
then return sit
.item
866 # Reverse iterator over a RopeBuffer.
867 class RopeBufferReviter
868 super IndexedIterator[Char]
871 var sit
: IndexedIterator[Char]
873 # Native string iterated over.
876 # Current position in `ns`.
881 # Init the iterator from a RopeBuffer.
882 init(tgt
: RopeBuffer) is old_style_init
do
883 sit
= tgt
.str
.chars
.reverse_iterator
885 index
= tgt
.length
- 1
889 # Init the iterator from a RopeBuffer starting from `pos`.
890 init from
(tgt
: RopeBuffer, pos
: Int) do
891 sit
= tgt
.str
.chars
.reverse_iterator_from
(pos
- tgt
.rpos
- tgt
.dumped
)
892 pns
= pos
- tgt
.str
.length
897 redef fun is_ok
do return index
> 0
900 if pns
>= 0 then return ns
[pns
]
914 # View on the chars of a `RopeBuffer`
915 class RopeBufferChars
918 redef type SELFTYPE: RopeBuffer
921 if i
< target
.str
.length
then
924 return target
.ns
[i
- target
.str
.length
]
928 redef fun []=(i
,c
) do
929 if i
== target
.length
then target
.add c
930 if i
< target
.str
.length
then
932 var l
= s
.substring
(0, i
)
933 var r
= s
.substring_from
(i
+ 1)
934 target
.str
= l
+ c
.to_s
+ r
936 target
.ns
[i
- target
.str
.length
] = c
940 redef fun add
(c
) do target
.add c
942 redef fun push
(c
) do target
.add c
944 redef fun iterator_from
(i
) do return new RopeBufferIter.from
(target
, i
)
946 redef fun reverse_iterator_from
(i
) do return new RopeBufferReviter.from
(target
, i
)