-
Notifications
You must be signed in to change notification settings - Fork 43
/
LArrayInputStream.scala
77 lines (61 loc) · 1.57 KB
/
LArrayInputStream.scala
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
//--------------------------------------
//
// LArrayInputStream.scala
// Since: 2013/03/21 5:28 PM
//
//--------------------------------------
package xerial.larray
import java.io.InputStream
import xerial.core.log.Logger
object LArrayInputStream {
/**
* Create a new InputStream from a given LArray
* @param array input
* @tparam A element type
* @return input stream
*/
def apply[A](array:LArray[A]) : InputStream = {
array match {
case r:RawByteArray[A] => new RawLArrayInputStream[A](r)
case _ => sys.error(s"cannot create InputStream from this LArray class:${array.getClass}")
}
}
}
/**
* InputStream implementation for LArrays that uses RawByteArray internally.
*
* @author Taro L. Saito
*/
private[larray] class RawLArrayInputStream[A](array:RawByteArray[A]) extends InputStream with Logger {
private var cursor = 0L
private var mark = 0L
def read() = {
val v = array.readByte(cursor)
cursor += 1
v
}
override def read(b: Array[Byte], offset:Int, len:Int) : Int = {
if(cursor >= array.size)
-1
else {
val readLen = math.min(len, array.byteLength - cursor).toInt
array.write(cursor, b, offset, readLen)
cursor += readLen
readLen
}
}
override def available = {
val remaining = array.size - cursor
math.min(Integer.MAX_VALUE, remaining).toInt
}
override def mark(readlimit: Int) {
// read limit can be ignored since all data is in memory
mark = cursor
}
override def reset() {
cursor = mark
}
override def markSupported() = {
true
}
}