Package io.kaitai.struct
Class KaitaiStream
- java.lang.Object
-
- io.kaitai.struct.KaitaiStream
-
- All Implemented Interfaces:
Closeable,AutoCloseable
- Direct Known Subclasses:
ByteBufferKaitaiStream,RandomAccessFileKaitaiStream
public abstract class KaitaiStream extends Object implements Closeable
KaitaiStream provides implementation of Kaitai Stream API for Java. It provides a wide variety of simple methods to read (parse) binary representations of primitive types, such as integer and floating point numbers, byte arrays and strings, and also provides stream positioning / navigation methods with unified cross-language and cross-toolkit semantics. This is abstract class, which serves as an interface description and a few default method implementations, which are believed to be common for all (or at least most) implementations. Different implementations of this interface may provide way to parse data from local files, in-memory buffers or arrays, remote files, network streams, etc. Typically, end users won't access any of these Kaitai Stream classes manually, but would describe a binary structure format using .ksy language and then would use Kaitai Struct compiler to generate source code in desired target language. That code, in turn, would use this class and API to do the actual parsing job.
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static classKaitaiStream.KaitaiStructErrorCommon ancestor for all error originating from Kaitai Struct usage.static classKaitaiStream.UndecidedEndiannessErrorError that occurs when default endianness should be decided with a switch, but nothing matches (although using endianness expression implies that there should be some positive result).static classKaitaiStream.UnexpectedDataErrorDeprecated.Not used anymore in favour ofValidation*-exceptions.static classKaitaiStream.ValidationExprErrorstatic classKaitaiStream.ValidationFailedErrorCommon ancestor for all validation failures.static classKaitaiStream.ValidationGreaterThanErrorstatic classKaitaiStream.ValidationLessThanErrorstatic classKaitaiStream.ValidationNotAnyOfErrorstatic classKaitaiStream.ValidationNotEqualErrorSignals validation failure: we required "actual" value to be equal to "expected", but it turned out that it's not.static classKaitaiStream.WriteBackHandler
-
Field Summary
Fields Modifier and Type Field Description protected longbitsprotected booleanbitsLeprotected intbitsLeftprotected booleanbitsWriteModeprotected List<KaitaiStream>childStreamsprotected KaitaiStream.WriteBackHandlerwriteBackHandler
-
Constructor Summary
Constructors Constructor Description KaitaiStream()
-
Method Summary
All Methods Static Methods Instance Methods Abstract Methods Concrete Methods Deprecated Methods Modifier and Type Method Description voidaddChildStream(KaitaiStream child)voidalignToByte()static intbyteArrayCompare(byte[] a, byte[] b)Compares two byte arrays in lexicographical order.static intbyteArrayIndexOf(byte[] arr, byte b)Returns the index of the first occurrence of the specified byte in a byte array, or -1 if this byte array does not contain the byte.static intbyteArrayMax(byte[] b)Finds the maximal byte in a byte array, treating bytes as unsigned values.static intbyteArrayMin(byte[] b)Finds the minimal byte in a byte array, treating bytes as unsigned values.static byte[]bytesStripRight(byte[] bytes, byte padByte)static byte[]bytesTerminate(byte[] bytes, byte term, boolean includeTerm)abstract voidclose()protected voidensureBytesLeftToWrite(long n, long pos)byte[]ensureFixedContents(byte[] expected)Deprecated.Not used anymore in favour of validators.abstract booleanisEof()Check if stream pointer is at the end of stream.static intmod(int a, int b)Performs modulo operation between two integers: dividend `a` and divisor `b`.static longmod(long a, long b)Performs modulo operation between two integers: dividend `a` and divisor `b`.abstract intpos()Get current position of a stream pointer.static byte[]processRotateLeft(byte[] data, int amount, int groupSize)Performs a circular left rotation shift for a given buffer by a given amount of bits, using groups of groupSize bytes each time.static byte[]processXor(byte[] data, byte key)Performs a XOR processing with given data, XORing every byte of input with a single given value.static byte[]processXor(byte[] data, byte[] key)Performs a XOR processing with given data, XORing every byte of input with a key array, repeating key array many times, if necessary (i.e.static byte[]processZlib(byte[] data)Performs an unpacking ("inflation") of zlib-compressed data with usual zlib headers.longreadBitsInt(int n)Deprecated.usereadBitsIntBe(int)insteadlongreadBitsIntBe(int n)longreadBitsIntLe(int n)byte[]readBytes(long n)Reads designated number of bytes from the stream.abstract byte[]readBytesFull()Reads all the remaining bytes in a stream as byte array.protected abstract byte[]readBytesNotAligned(long n)Internal method to read the specified number of bytes from the stream.abstract byte[]readBytesTerm(byte term, boolean includeTerm, boolean consumeTerm, boolean eosError)abstract floatreadF4be()abstract floatreadF4le()abstract doublereadF8be()abstract doublereadF8le()abstract bytereadS1()Reads one signed 1-byte integer, returning it properly as Java's "byte" type.abstract shortreadS2be()abstract shortreadS2le()abstract intreadS4be()abstract intreadS4le()abstract longreadS8be()abstract longreadS8le()abstract intreadU1()abstract intreadU2be()abstract intreadU2le()abstract longreadU4be()abstract longreadU4le()longreadU8be()Reads one unsigned 8-byte integer in big-endian encoding.longreadU8le()Reads one unsigned 8-byte integer in little-endian encoding.abstract voidseek(int newPos)Set stream pointer to designated position (int).abstract voidseek(long newPos)Set stream pointer to designated position (long).voidsetWriteBackHandler(KaitaiStream.WriteBackHandler handler)abstract longsize()Get total size of the stream in bytes.abstract KaitaiStreamsubstream(long n)Reserves next `n` bytes from current stream as a KaitaiStream-compatible substream.byte[]toByteArray()protected inttoByteArrayLength(long n)Checks if supplied number of bytes is a valid number of elements for Java byte array: converts it to int, if it is, or throws an exception if it is not.static byte[]unprocessZlib(byte[] data)voidwriteAlignToByte()protected voidwriteBack(KaitaiStream parent)voidwriteBackChildStreams()protected voidwriteBackChildStreams(KaitaiStream parent)voidwriteBitsIntBe(int n, long val)voidwriteBitsIntLe(int n, long val)voidwriteBytes(byte[] buf)Writes given byte array to the stream.voidwriteBytesLimit(byte[] buf, long size, byte term, byte padByte)protected abstract voidwriteBytesNotAligned(byte[] buf)Internal method to write the given byte array to the stream.abstract voidwriteF4be(float v)abstract voidwriteF4le(float v)abstract voidwriteF8be(double v)abstract voidwriteF8le(double v)abstract voidwriteS1(byte v)Writes one signed 1-byte integer.abstract voidwriteS2be(short v)abstract voidwriteS2le(short v)abstract voidwriteS4be(int v)abstract voidwriteS4le(int v)abstract voidwriteS8be(long v)abstract voidwriteS8le(long v)voidwriteStream(KaitaiStream other)voidwriteU1(int v)voidwriteU2be(int v)voidwriteU2le(int v)voidwriteU4be(long v)voidwriteU4le(long v)voidwriteU8be(long v)voidwriteU8le(long v)
-
-
-
Field Detail
-
bitsLeft
protected int bitsLeft
-
bits
protected long bits
-
bitsLe
protected boolean bitsLe
-
bitsWriteMode
protected boolean bitsWriteMode
-
writeBackHandler
protected KaitaiStream.WriteBackHandler writeBackHandler
-
childStreams
protected List<KaitaiStream> childStreams
-
-
Method Detail
-
close
public abstract void close() throws IOException- Specified by:
closein interfaceAutoCloseable- Specified by:
closein interfaceCloseable- Throws:
IOException
-
isEof
public abstract boolean isEof()
Check if stream pointer is at the end of stream.- Returns:
- true if we are located at the end of the stream
-
seek
public abstract void seek(int newPos)
Set stream pointer to designated position (int).- Parameters:
newPos- new position (offset in bytes from the beginning of the stream)
-
seek
public abstract void seek(long newPos)
Set stream pointer to designated position (long).- Parameters:
newPos- new position (offset in bytes from the beginning of the stream)
-
pos
public abstract int pos()
Get current position of a stream pointer.- Returns:
- pointer position, number of bytes from the beginning of the stream
-
size
public abstract long size()
Get total size of the stream in bytes.- Returns:
- size of the stream in bytes
-
readS1
public abstract byte readS1()
Reads one signed 1-byte integer, returning it properly as Java's "byte" type.- Returns:
- 1-byte integer read from a stream
-
readS2be
public abstract short readS2be()
-
readS4be
public abstract int readS4be()
-
readS8be
public abstract long readS8be()
-
readS2le
public abstract short readS2le()
-
readS4le
public abstract int readS4le()
-
readS8le
public abstract long readS8le()
-
readU1
public abstract int readU1()
-
readU2be
public abstract int readU2be()
-
readU4be
public abstract long readU4be()
-
readU8be
public long readU8be()
Reads one unsigned 8-byte integer in big-endian encoding. As Java does not have a primitive data type to accomodate it, we just reusereadS8be().- Returns:
- 8-byte signed integer (pretending to be unsigned) read from a stream
-
readU2le
public abstract int readU2le()
-
readU4le
public abstract long readU4le()
-
readU8le
public long readU8le()
Reads one unsigned 8-byte integer in little-endian encoding. As Java does not have a primitive data type to accomodate it, we just reusereadS8le().- Returns:
- 8-byte signed integer (pretending to be unsigned) read from a stream
-
readF4be
public abstract float readF4be()
-
readF8be
public abstract double readF8be()
-
readF4le
public abstract float readF4le()
-
readF8le
public abstract double readF8le()
-
alignToByte
public void alignToByte()
-
readBitsIntBe
public long readBitsIntBe(int n)
-
readBitsInt
@Deprecated public long readBitsInt(int n)
Deprecated.usereadBitsIntBe(int)insteadUnused since Kaitai Struct Compiler v0.9+ - compatibility with older versions
-
readBitsIntLe
public long readBitsIntLe(int n)
-
readBytes
public byte[] readBytes(long n)
Reads designated number of bytes from the stream.- Parameters:
n- number of bytes to read- Returns:
- read bytes as byte array
-
readBytesNotAligned
protected abstract byte[] readBytesNotAligned(long n)
Internal method to read the specified number of bytes from the stream. UnlikereadBytes(long), it doesn't align the bit position to the next byte boundary.- Parameters:
n- number of bytes to read- Returns:
- read bytes as a byte array
-
readBytesFull
public abstract byte[] readBytesFull()
Reads all the remaining bytes in a stream as byte array.- Returns:
- all remaining bytes in a stream as byte array
-
readBytesTerm
public abstract byte[] readBytesTerm(byte term, boolean includeTerm, boolean consumeTerm, boolean eosError)
-
ensureFixedContents
@Deprecated public byte[] ensureFixedContents(byte[] expected)
Deprecated.Not used anymore in favour of validators.Checks that next bytes in the stream match match expected fixed byte array. It does so by determining number of bytes to compare, reading them, and doing the actual comparison. If they differ, throws aKaitaiStream.UnexpectedDataErrorruntime exception.- Parameters:
expected- contents to be expected- Returns:
- read bytes as byte array, which are guaranteed to equal to expected
- Throws:
KaitaiStream.UnexpectedDataError- if read data from stream isn't equal to given data
-
bytesStripRight
public static byte[] bytesStripRight(byte[] bytes, byte padByte)
-
bytesTerminate
public static byte[] bytesTerminate(byte[] bytes, byte term, boolean includeTerm)
-
toByteArrayLength
protected int toByteArrayLength(long n)
Checks if supplied number of bytes is a valid number of elements for Java byte array: converts it to int, if it is, or throws an exception if it is not.- Parameters:
n- number of bytes for byte array as long- Returns:
- number of bytes, converted to int
-
ensureBytesLeftToWrite
protected void ensureBytesLeftToWrite(long n, long pos)
-
writeS1
public abstract void writeS1(byte v)
Writes one signed 1-byte integer.
-
writeS2be
public abstract void writeS2be(short v)
-
writeS4be
public abstract void writeS4be(int v)
-
writeS8be
public abstract void writeS8be(long v)
-
writeS2le
public abstract void writeS2le(short v)
-
writeS4le
public abstract void writeS4le(int v)
-
writeS8le
public abstract void writeS8le(long v)
-
writeU1
public void writeU1(int v)
-
writeU2be
public void writeU2be(int v)
-
writeU4be
public void writeU4be(long v)
-
writeU8be
public void writeU8be(long v)
-
writeU2le
public void writeU2le(int v)
-
writeU4le
public void writeU4le(long v)
-
writeU8le
public void writeU8le(long v)
-
writeF4be
public abstract void writeF4be(float v)
-
writeF8be
public abstract void writeF8be(double v)
-
writeF4le
public abstract void writeF4le(float v)
-
writeF8le
public abstract void writeF8le(double v)
-
writeAlignToByte
public void writeAlignToByte()
-
writeBitsIntBe
public void writeBitsIntBe(int n, long val)
-
writeBitsIntLe
public void writeBitsIntLe(int n, long val)
-
writeBytes
public void writeBytes(byte[] buf)
Writes given byte array to the stream.- Parameters:
buf- byte array to write
-
writeBytesNotAligned
protected abstract void writeBytesNotAligned(byte[] buf)
Internal method to write the given byte array to the stream. UnlikewriteBytes(byte[]), it doesn't align the bit position to the next byte boundary.- Parameters:
buf- byte array to write
-
writeBytesLimit
public void writeBytesLimit(byte[] buf, long size, byte term, byte padByte)
-
writeStream
public void writeStream(KaitaiStream other)
-
processXor
public static byte[] processXor(byte[] data, byte key)Performs a XOR processing with given data, XORing every byte of input with a single given value.- Parameters:
data- data to processkey- value to XOR with- Returns:
- processed data
-
processXor
public static byte[] processXor(byte[] data, byte[] key)Performs a XOR processing with given data, XORing every byte of input with a key array, repeating key array many times, if necessary (i.e. if data array is longer than key array).- Parameters:
data- data to processkey- array of bytes to XOR with- Returns:
- processed data
-
processRotateLeft
public static byte[] processRotateLeft(byte[] data, int amount, int groupSize)Performs a circular left rotation shift for a given buffer by a given amount of bits, using groups of groupSize bytes each time. Right circular rotation should be performed using this procedure with corrected amount.- Parameters:
data- source data to processamount- number of bits to shift bygroupSize- number of bytes per group to shift- Returns:
- copy of source array with requested shift applied
-
processZlib
public static byte[] processZlib(byte[] data)
Performs an unpacking ("inflation") of zlib-compressed data with usual zlib headers.- Parameters:
data- data to unpack- Returns:
- unpacked data
- Throws:
RuntimeException- if data can't be decoded
-
unprocessZlib
public static byte[] unprocessZlib(byte[] data)
-
substream
public abstract KaitaiStream substream(long n)
Reserves next `n` bytes from current stream as a KaitaiStream-compatible substream. Substream has its own pointer and addressing in the range of [0, n) bytes. This stream's pointer is advanced to the position right after this substream.- Parameters:
n- number of bytes to reserve for a substream- Returns:
- substream covering n bytes from the current position
-
mod
public static int mod(int a, int b)Performs modulo operation between two integers: dividend `a` and divisor `b`. Divisor `b` is expected to be positive. The result is always 0 <= x <= b - 1.- Parameters:
a- dividendb- divisor- Returns:
- result
-
mod
public static long mod(long a, long b)Performs modulo operation between two integers: dividend `a` and divisor `b`. Divisor `b` is expected to be positive. The result is always 0 <= x <= b - 1.- Parameters:
a- dividendb- divisor- Returns:
- result
-
byteArrayCompare
public static int byteArrayCompare(byte[] a, byte[] b)Compares two byte arrays in lexicographical order. Makes extra effort to compare bytes properly, as *unsigned* bytes, i.e. [0x90] would be greater than [0x10].- Parameters:
a- first byte array to compareb- second byte array to compare- Returns:
- negative number if a < b, 0 if a == b, positive number if a > b
- See Also:
Comparable.compareTo(Object)
-
byteArrayMin
public static int byteArrayMin(byte[] b)
Finds the minimal byte in a byte array, treating bytes as unsigned values.- Parameters:
b- byte array to scan- Returns:
- minimal byte in byte array as integer
-
byteArrayMax
public static int byteArrayMax(byte[] b)
Finds the maximal byte in a byte array, treating bytes as unsigned values.- Parameters:
b- byte array to scan- Returns:
- maximal byte in byte array as integer
-
byteArrayIndexOf
public static int byteArrayIndexOf(byte[] arr, byte b)Returns the index of the first occurrence of the specified byte in a byte array, or -1 if this byte array does not contain the byte.- Parameters:
arr- byte array to search inb- byte to search for- Returns:
- index of the first occurrence of the specified byte in the byte array, or -1 if this byte array does not contain the byte
- See Also:
List.indexOf(Object),String.indexOf(int)
-
toByteArray
public byte[] toByteArray()
-
setWriteBackHandler
public void setWriteBackHandler(KaitaiStream.WriteBackHandler handler)
-
addChildStream
public void addChildStream(KaitaiStream child)
-
writeBackChildStreams
public void writeBackChildStreams()
-
writeBackChildStreams
protected void writeBackChildStreams(KaitaiStream parent)
-
writeBack
protected void writeBack(KaitaiStream parent)
-
-