package org.bson;
import org.bson.io.Bits;
import org.bson.io.ByteBufferBsonInput;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
public class BasicBSONDecoder implements BSONDecoder {
@Override
public BSONObject readObject(final byte[] bytes) {
BSONCallback bsonCallback = new BasicBSONCallback();
decode(bytes, bsonCallback);
return (BSONObject) bsonCallback.get();
}
@Override
public BSONObject readObject(final InputStream in) throws IOException {
return readObject(readFully(in));
}
@Override
public int decode(final byte[] bytes, final BSONCallback callback) {
BsonBinaryReader reader = new BsonBinaryReader(new ByteBufferBsonInput(new ByteBufNIO(ByteBuffer.wrap(bytes))));
try {
BsonWriter writer = new BSONCallbackAdapter(new BsonWriterSettings(), callback);
writer.pipe(reader);
return reader.getBsonInput().getPosition();
} finally {
reader.close();
}
}
@Override
public int decode(final InputStream in, final BSONCallback callback) throws IOException {
return decode(readFully(in), callback);
}
private byte[] readFully(final InputStream input) throws IOException {
byte[] sizeBytes = new byte[4];
Bits.readFully(input, sizeBytes);
int size = Bits.readInt(sizeBytes);
byte[] buffer = new byte[size];
System.arraycopy(sizeBytes, 0, buffer, 0, 4);
Bits.readFully(input, buffer, 4, size - 4);
return buffer;
}
}