summaryrefslogtreecommitdiff
path: root/src/scalap/scala/tools/scalap/ByteArrayReader.scala
blob: 59f083ee766a7cbf58b1831fad2110398380a2b0 (plain) (blame)
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
/*     ___ ____ ___   __   ___   ___
**    / _// __// _ | / /  / _ | / _ \    Scala classfile decoder
**  __\ \/ /__/ __ |/ /__/ __ |/ ___/    (c) 2003-2013, LAMP/EPFL
** /____/\___/_/ |_/____/_/ |_/_/        http://scala-lang.org/
**
*/

package scala.tools.scalap

class ByteArrayReader(content: Array[Byte]) {

  /** the buffer containing the file
   */
  val buf: Array[Byte] = content

  /** the current input pointer
   */
  var bp: Int = 0

  /** return byte at offset 'pos'
   */
  def byteAt(pos: Int): Byte = buf(pos)

  /** read a byte
   */
  def nextByte: Byte = {
    bp += 1
    buf(bp - 1)
  }

  /** read some bytes
   */
  def nextBytes(len: Int): Array[Byte] = {
    val res = new Array[Byte](len)
    System.arraycopy(buf, bp, res, 0, len)
    bp += len
    res
  }

  /** read a character
   */
  def nextChar: Char = {
    bp += 2
    getChar(bp - 2)
  }

  /** read an integer
   */
  def nextInt: Int = {
    bp += 4
    getInt(bp - 4)
  }

  /** read a long
   */
  def nextLong: Long = {
    bp += 8
    getLong(bp - 8)
  }

  /** read a float
   */
  def nextFloat: Float = java.lang.Float.intBitsToFloat(nextInt)

  /** read a double
   */
  def nextDouble: Double = java.lang.Double.longBitsToDouble(nextLong)

  /** read an UTF8 encoded string
   */
  def nextUTF8(len: Int): String = {
    val cs = scala.io.Codec.fromUTF8(buf, bp, len)
    bp += len
    new String(cs)
  }

  /** extract a character at position bp from buf
   */
  def getChar(bp: Int): Char =
    (((buf(bp) & 0xff) << 8) + (buf(bp + 1) & 0xff)).asInstanceOf[Char]

  /** extract an integer at position bp from buf
   */
  def getInt(bp: Int): Int =
    ((buf(bp  ) & 0xff) << 24) +
    ((buf(bp + 1) & 0xff) << 16) +
    ((buf(bp + 2) & 0xff) << 8) +
     (buf(bp + 3) & 0xff)

  /** extract a long integer at position bp from buf
   */
  def getLong(bp: Int): Long =
    (getInt(bp).toLong << 32) + (getInt(bp + 4).toLong & 0xffffffffL)

  /** extract a float at position bp from buf
   */
  def getFloat(bp: Int): Float = java.lang.Float.intBitsToFloat(getInt(bp))

  /** extract a double at position bp from buf
   */
  def getDouble(bp: Int): Double = java.lang.Double.longBitsToDouble(getLong(bp))

   /** skip next 'n' bytes
    */
  def skip(n: Int): Unit = bp += n
}