package org.bson;
import org.bson.io.Bits;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
public class LazyBSONDecoder implements BSONDecoder {
private static final int BYTES_IN_INTEGER = 4;
@Override
public BSONObject readObject(final byte[] bytes) {
BSONCallback bsonCallback = new LazyBSONCallback();
decode(bytes, bsonCallback);
return (BSONObject) bsonCallback.get();
}
@Override
public BSONObject readObject(final InputStream in) throws IOException {
BSONCallback bsonCallback = new LazyBSONCallback();
decode(in, bsonCallback);
return (BSONObject) bsonCallback.get();
}
@Override
public int decode(final byte[] bytes, final BSONCallback callback) {
try {
return decode(new ByteArrayInputStream(bytes), callback);
} catch (IOException e) {
throw new BSONException("Invalid bytes received", e);
}
}
@Override
public int decode(final InputStream in, final BSONCallback callback) throws IOException {
byte[] documentSizeBuffer = new byte[BYTES_IN_INTEGER];
int documentSize = Bits.readInt(in, documentSizeBuffer);
byte[] documentBytes = Arrays.copyOf(documentSizeBuffer, documentSize);
Bits.readFully(in, documentBytes, BYTES_IN_INTEGER, documentSize - BYTES_IN_INTEGER);
callback.gotBinary(null, (byte) 0, documentBytes);
return documentSize;
}
}