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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
|
/* __ *\
** ________ ___ / / ___ Scala API **
** / __/ __// _ | / / / _ | (c) 2003-2010, LAMP/EPFL **
** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ **
** /____/\___/_/ |_/____/_/ | | **
** |/ **
\* */
package scala.collection
package mutable
import generic._
import immutable.{List, Nil, ::}
/** A `Buffer` implementation back up by a list. It provides constant time
* prepend and append. Most other operations are linear.
*
* @author Matthias Zenger
* @author Martin Odersky
* @version 2.8
* @since 1
*
* @tparam A the type of this list buffer's elements.
*
* @define Coll ListBuffer
* @define coll list buffer
* @define thatinfo the class of the returned collection. In the standard library configuration,
* `That` is always `ListBuffer[B]` because an implicit of type `CanBuildFrom[ListBuffer, B, ListBuffer[B]]`
* is defined in object `ListBuffer`.
* @define $bfinfo an implicit value of class `CanBuildFrom` which determines the
* result class `That` from the current representation type `Repr`
* and the new element type `B`. This is usually the `canBuildFrom` value
* defined in object `ListBuffer`.
* @define orderDependent
* @define orderDependentFold
* @define mayNotTerminateInf
* @define willNotTerminateInf
*/
@SerialVersionUID(3419063961353022661L)
final class ListBuffer[A]
extends Buffer[A]
with GenericTraversableTemplate[A, ListBuffer]
with BufferLike[A, ListBuffer[A]]
with Builder[A, List[A]]
with SeqForwarder[A]
with Serializable
{
override def companion: GenericCompanion[ListBuffer] = ListBuffer
import scala.collection.Traversable
private var start: List[A] = Nil
private var last0: ::[A] = _
private var exported: Boolean = false
private var len = 0
protected def underlying: immutable.Seq[A] = start
/** The current length of the buffer.
*
* This operation takes constant time.
*/
override def length = len
// Implementations of abstract methods in Buffer
override def apply(n: Int): A =
if (n < 0 || n >= len) throw new IndexOutOfBoundsException(n.toString())
else super.apply(n)
/** Replaces element at index `n` with the new element
* `newelem`. Takes time linear in the buffer size. (except the
* first element, which is updated in constant time).
*
* @param n the index of the element to replace.
* @param x the new element.
* @throws Predef.IndexOutOfBoundsException if `n` is out of bounds.
*/
def update(n: Int, x: A) {
try {
if (exported) copy()
if (n == 0) {
val newElem = new :: (x, start.tail);
if (last0 eq start) {
last0 = newElem
}
start = newElem
} else {
var cursor = start
var i = 1
while (i < n) {
cursor = cursor.tail
i += 1
}
val newElem = new :: (x, cursor.tail.tail)
if (last0 eq cursor.tail) {
last0 = newElem
}
cursor.asInstanceOf[::[A]].tl = newElem
}
} catch {
case ex: Exception => throw new IndexOutOfBoundsException(n.toString())
}
}
/** Appends a single element to this buffer. This operation takes constant time.
*
* @param x the element to append.
* @return this $coll.
*/
def += (x: A): this.type = {
if (exported) copy()
if (start.isEmpty) {
last0 = new :: (x, Nil)
start = last0
} else {
val last1 = last0
last0 = new :: (x, Nil)
last1.tl = last0
}
len += 1
this
}
override def ++=(xs: TraversableOnce[A]): this.type =
if (xs eq this) ++= (this take size) else super.++=(xs)
override def ++=:(xs: TraversableOnce[A]): this.type =
if (xs eq this) ++=: (this take size) else super.++=:(xs)
/** Clears the buffer contents.
*/
def clear() {
start = Nil
exported = false
len = 0
}
/** Prepends a single element to this buffer. This operation takes constant
* time.
*
* @param x the element to prepend.
* @return this $coll.
*/
def +=: (x: A): this.type = {
if (exported) copy()
val newElem = new :: (x, start)
if (start.isEmpty) last0 = newElem
start = newElem
len += 1
this
}
/** Inserts new elements at the index `n`. Opposed to method
* `update`, this method will not replace an element with a new
* one. Instead, it will insert a new element at index `n`.
*
* @param n the index where a new element will be inserted.
* @param iter the iterable object providing all elements to insert.
* @throws Predef.IndexOutOfBoundsException if `n` is out of bounds.
*/
def insertAll(n: Int, seq: Traversable[A]) {
try {
if (exported) copy()
var elems = seq.toList.reverse
len += elems.length
if (n == 0) {
while (!elems.isEmpty) {
val newElem = new :: (elems.head, start)
if (start.isEmpty) last0 = newElem
start = newElem
elems = elems.tail
}
} else {
var cursor = start
var i = 1
while (i < n) {
cursor = cursor.tail
i += 1
}
while (!elems.isEmpty) {
val newElem = new :: (elems.head, cursor.tail)
if (cursor.tail.isEmpty) last0 = newElem
cursor.asInstanceOf[::[A]].tl = newElem
elems = elems.tail
}
}
} catch {
case ex: Exception =>
throw new IndexOutOfBoundsException(n.toString())
}
}
/** Removes a given number of elements on a given index position. May take
* time linear in the buffer size.
*
* @param n the index which refers to the first element to remove.
* @param count the number of elements to remove.
*/
override def remove(n: Int, count: Int) {
if (exported) copy()
val n1 = n max 0
val count1 = count min (len - n1)
var old = start.head
if (n1 == 0) {
var c = count1
while (c > 0) {
start = start.tail
c -= 1
}
} else {
var cursor = start
var i = 1
while (i < n1) {
cursor = cursor.tail
i += 1
}
var c = count1
while (c > 0) {
if (last0 eq cursor.tail) last0 = cursor.asInstanceOf[::[A]]
cursor.asInstanceOf[::[A]].tl = cursor.tail.tail
c -= 1
}
}
len -= count1
}
// Implementation of abstract method in Builder
def result: List[A] = toList
/** Converts this buffer to a list. Takes constant time. The buffer is
* copied lazily, the first time it is mutated.
*/
override def toList: List[A] = {
exported = !start.isEmpty
start
}
// New methods in ListBuffer
/** Prepends the elements of this buffer to a given list
*
* @param xs the list to which elements are prepended
*/
def prependToList(xs: List[A]): List[A] =
if (start.isEmpty) xs
else { last0.tl = xs; toList }
// Overrides of methods in Buffer
/** Removes the element on a given index position. May take time linear in
* the buffer size.
*
* @param n the index which refers to the element to delete.
* @return n the element that was formerly at position `n`.
* @note an element must exists at position `n`.
* @throws Predef.IndexOutOfBoundsException if `n` is out of bounds.
*/
def remove(n: Int): A = {
if (n < 0 || n >= len) throw new IndexOutOfBoundsException(n.toString())
if (exported) copy()
var old = start.head
if (n == 0) {
start = start.tail
} else {
var cursor = start
var i = 1
while (i < n) {
cursor = cursor.tail
i += 1
}
old = cursor.tail.head
if (last0 eq cursor.tail) last0 = cursor.asInstanceOf[::[A]]
cursor.asInstanceOf[::[A]].tl = cursor.tail.tail
}
len -= 1
old
}
/** Remove a single element from this buffer. May take time linear in the
* buffer size.
*
* @param x the element to remove.
* @return this $coll.
*/
override def -= (elem: A): this.type = {
if (exported) copy()
if (start.isEmpty) {}
else if (start.head == elem) {
start = start.tail
len -= 1
} else {
var cursor = start
while (!cursor.tail.isEmpty && cursor.tail.head != elem) {
cursor = cursor.tail
}
if (!cursor.tail.isEmpty) {
val z = cursor.asInstanceOf[::[A]]
if (z.tl == last0)
last0 = z
z.tl = cursor.tail.tail
len -= 1
}
}
this
}
override def iterator = new Iterator[A] {
var cursor: List[A] = null
def hasNext: Boolean = !start.isEmpty && (cursor ne last0)
def next(): A =
if (!hasNext) {
throw new NoSuchElementException("next on empty Iterator")
} else {
if (cursor eq null) cursor = start else cursor = cursor.tail
cursor.head
}
}
/** expose the underlying list but do not mark it as exported */
override def readOnly: List[A] = start
// Private methods
/** Copy contents of this buffer */
private def copy() {
var cursor = start
val limit = last0.tail
clear
while (cursor ne limit) {
this += cursor.head
cursor = cursor.tail
}
}
override def equals(that: Any): Boolean = that match {
case that: ListBuffer[_] => this.readOnly equals that.readOnly
case _ => super.equals(that)
}
/** Returns a clone of this buffer.
*
* @return a <code>ListBuffer</code> with the same elements.
*/
override def clone(): ListBuffer[A] = (new ListBuffer[A]) ++= this
/** Defines the prefix of the string representation.
*
* @return the string representation of this buffer.
*/
override def stringPrefix: String = "ListBuffer"
}
/** $factoryInfo
* @define Coll ListBuffer
* @define coll list buffer
*/
object ListBuffer extends SeqFactory[ListBuffer] {
implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, ListBuffer[A]] = new GenericCanBuildFrom[A]
def newBuilder[A]: Builder[A, ListBuffer[A]] = new GrowingBuilder(new ListBuffer[A])
}
|