private void parseFrameFileIndexAndPathnameTables(java.nio.ByteBuffer buffer) { int theSectionOffset = buffer.position(); Hashtable <Integer, String> pathnames = new Hashtable <Integer, String>(); for (int i = 0; i < this.numOfFrameFileIndexRecords; i++) { this.frameFileIndexTable.add(new RPFFrameFileIndexRecord(buffer)); } for (int i = 0; i < this.numOfPathnameRecords; i++) { int relOffset = buffer.position() - theSectionOffset; int len = NITFSUtil.getUShort(buffer); pathnames.put(relOffset, NITFSUtil.getString(buffer, len)); } if (0 < this.frameFileIndexTable.size() && 0 < pathnames.size()) { // update pathname field in every RPFFrameFileIndexRecord foreach (RPFFrameFileIndexRecord rec in this.frameFileIndexTable) { int offset = (int)rec.getPathnameRecordOffset(); if (pathnames.containsKey(offset)) { rec.setPathname(pathnames.get(offset)); } else { throw new NITFSRuntimeException("NITFSReader.CorrespondingPathnameWasNotFound"); } } } }
public RPFFrameFileComponents(java.nio.ByteBuffer buffer) { this.componentLocationTable = new RPFLocationSection(buffer); if (0 < this.componentLocationTable.getCoverageSectionSubheaderLength()) { this.parseRPFCoverageSection(buffer); } if (0 < this.componentLocationTable.getColorGrayscaleSectionSubheaderLength()) { this.parseColorGrayscaleSection(buffer); } if (0 < this.componentLocationTable.getColormapSubsectionLength()) { this.parseColormapSubSection(buffer); } if (0 < this.componentLocationTable.getColorConverterSubsectionLength()) { this.parseColorConverterSubsection(buffer); } if (0 < this.componentLocationTable.getImageDescriptionSubheaderLength()) { buffer.position(this.componentLocationTable.getImageDescriptionSubheaderLocation()); this.parseImageDescriptionSubheader(buffer); } if (0 < this.componentLocationTable.getRelatedImagesSectionSubheaderLength()) { buffer.position(this.componentLocationTable.getRelatedImagesSectionSubheaderLocation()); this.relatedImagesSection = new RelatedImagesSection(buffer); } }
///Upon return, `bb.position()` will be at the end of the message. /// <exception cref="System.IO.IOException"/> public static Capnproto.MessageReader Read(java.nio.ByteBuffer bb, Capnproto.ReaderOptions options) { bb.order(java.nio.ByteOrder.LITTLE_ENDIAN); int segmentCount = 1 + bb.getInt(); if (segmentCount > 512) { throw new System.IO.IOException("too many segments"); } java.nio.ByteBuffer[] segmentSlices = new java.nio.ByteBuffer[segmentCount]; int segmentSizesBase = bb.position(); int segmentSizesSize = segmentCount * 4; int align = Capnproto.Constants.BYTES_PER_WORD - 1; int segmentBase = (segmentSizesBase + segmentSizesSize + align) & ~align; int totalWords = 0; for (int ii = 0; ii < segmentCount; ++ii) { int segmentSize = bb.getInt(segmentSizesBase + ii * 4); bb.position(segmentBase + totalWords * Capnproto.Constants.BYTES_PER_WORD); segmentSlices[ii] = bb.slice(); segmentSlices[ii].limit(segmentSize * Capnproto.Constants.BYTES_PER_WORD); segmentSlices[ii].order(java.nio.ByteOrder.LITTLE_ENDIAN); totalWords += segmentSize; } bb.position(segmentBase + totalWords * Capnproto.Constants.BYTES_PER_WORD); if (totalWords > options.traversalLimitInWords) { throw new Capnproto.DecodeException("Message size exceeds traversal limit."); } return(new Capnproto.MessageReader(segmentSlices, options)); }
public static long write(object nd, FileDescriptor fd, ByteBuffer[] bufs, int offset, int length) { #if FIRST_PASS return(0); #else ByteBuffer[] altBufs = null; List <ArraySegment <byte> > list = new List <ArraySegment <byte> >(length); for (int i = 0; i < length; i++) { ByteBuffer bb = bufs[i + offset]; if (!bb.hasArray()) { if (altBufs == null) { altBufs = new ByteBuffer[bufs.Length]; } ByteBuffer abb = ByteBuffer.allocate(bb.remaining()); int pos = bb.position(); abb.put(bb); bb.position(pos); abb.flip(); bb = altBufs[i + offset] = abb; } list.Add(new ArraySegment <byte>(bb.array(), bb.arrayOffset() + bb.position(), bb.remaining())); } int count; try { count = fd.getSocket().Send(list); } catch (System.Net.Sockets.SocketException x) { if (x.ErrorCode == global::java.net.SocketUtil.WSAEWOULDBLOCK) { count = 0; } else { throw global::java.net.SocketUtil.convertSocketExceptionToIOException(x); } } catch (ObjectDisposedException) { throw new global::java.net.SocketException("Socket is closed"); } int total = count; for (int i = 0; total > 0 && i < length; i++) { ByteBuffer bb = bufs[i + offset]; int consumed = Math.Min(total, bb.remaining()); bb.position(bb.position() + consumed); total -= consumed; } return(count); #endif }
public RPFColorMap(java.nio.ByteBuffer buffer, int colormapSubsectionOffset) { this.parseRPFColorOffsetRecord(buffer); // now let's load color map and histogram int saveOffset = buffer.position(); this.loadColorMaps(buffer, colormapSubsectionOffset); // ok, we can skip histogram for now // this.loadHistogram(buffer, colormapSubsectionOffset); buffer.position(saveOffset); }
public override java.nio.LongBuffer compact() { if (byteBuffer.isReadOnly()) { throw new java.nio.ReadOnlyBufferException(); } byteBuffer.limit(_limit * libcore.io.SizeOf.LONG); byteBuffer.position(_position * libcore.io.SizeOf.LONG); byteBuffer.compact(); byteBuffer.clear(); _position = _limit - _position; _limit = _capacity; _mark = UNSET_MARK; return(this); }
private void parseColorGrayscaleSection(java.nio.ByteBuffer buffer) { buffer.position(this.componentLocationTable.getColorGrayscaleSectionSubheaderLocation()); this.numOfColorGrayscaleOffsetRecords = NITFSUtil.getByteAsShort(buffer); this.numOfColorConverterOffsetRecords = NITFSUtil.getByteAsShort(buffer); this.externalColorGrayscaleFilename = NITFSUtil.getString(buffer, 12); }
public byte[] ToArray() { java.nio.ByteBuffer dup = this.buffer.duplicate(); byte[] result = new byte[this.size]; dup.position(this.offset); dup.get(result, 0, this.size); return(result); }
public java.nio.ByteBuffer AsByteBuffer() { java.nio.ByteBuffer dup = this.buffer.asReadOnlyBuffer(); dup.position(this.offset); java.nio.ByteBuffer result = dup.slice(); result.limit(this.size); return(result); }
public RPFFileComponents(java.nio.ByteBuffer buffer) { this.buffer = buffer; this.headerSection = new RPFHeaderSection(buffer); buffer.position(this.headerSection.locationSectionLocation); this.locationSection = new RPFLocationSection(buffer); }
/// <exception cref="System.IO.IOException"/> public int Write(java.nio.ByteBuffer src) { int available = this.buf.remaining(); int size = src.remaining(); if (size <= available) { this.buf.put(src); } else if (size <= this.buf.capacity()) { //# Too much for this buffer, but not a full buffer's worth, //# so we'll go ahead and copy. java.nio.ByteBuffer slice = src.slice(); slice.limit(available); this.buf.put(slice); this.buf.rewind(); while (this.buf.hasRemaining()) { this.inner.Write(this.buf); } this.buf.rewind(); src.position(src.position() + available); this.buf.put(src); } else { //# Writing so much data that we might as well write //# directly to avoid a copy. int pos = this.buf.position(); this.buf.rewind(); java.nio.ByteBuffer slice = this.buf.slice(); slice.limit(pos); while (slice.hasRemaining()) { this.inner.Write(slice); } while (src.hasRemaining()) { this.inner.Write(src); } } return(size); }
public NITFSSegment(NITFSSegmentType segmentType, java.nio.ByteBuffer buffer, int headerStartOffset, int headerLength, int dataStartOffset, int dataLength) { this.buffer = buffer; this.segmentType = segmentType; this.headerStartOffset = headerStartOffset; this.headerLength = headerLength; this.dataStartOffset = dataStartOffset; this.dataLength = dataLength; this.savedBufferOffset = buffer.position(); }
/// <exception cref="System.IO.IOException"/> public static Capnproto.MessageReader Read(java.nio.channels.ReadableByteChannel bc, Capnproto.ReaderOptions options) { java.nio.ByteBuffer firstWord = makeByteBuffer(Capnproto.Constants.BYTES_PER_WORD); fillBuffer(firstWord, bc); int segmentCount = 1 + firstWord.getInt(0); int segment0Size = 0; if (segmentCount > 0) { segment0Size = firstWord.getInt(4); } int totalWords = segment0Size; if (segmentCount > 512) { throw new System.IO.IOException("too many segments"); } //In words. System.Collections.Generic.List <int> moreSizes = new System.Collections.Generic.List <int>(); if (segmentCount > 1) { java.nio.ByteBuffer moreSizesRaw = makeByteBuffer(4 * (segmentCount & ~1)); fillBuffer(moreSizesRaw, bc); for (int ii = 0; ii < segmentCount - 1; ++ii) { int size = moreSizesRaw.getInt(ii * 4); moreSizes.Add(size); totalWords += size; } } if (totalWords > options.traversalLimitInWords) { throw new Capnproto.DecodeException("Message size exceeds traversal limit."); } java.nio.ByteBuffer allSegments = makeByteBuffer(totalWords * Capnproto.Constants.BYTES_PER_WORD); fillBuffer(allSegments, bc); java.nio.ByteBuffer[] segmentSlices = new java.nio.ByteBuffer[segmentCount]; allSegments.rewind(); segmentSlices[0] = allSegments.slice(); segmentSlices[0].limit(segment0Size * Capnproto.Constants.BYTES_PER_WORD); segmentSlices[0].order(java.nio.ByteOrder.LITTLE_ENDIAN); int offset = segment0Size; for (int ii = 1; ii < segmentCount; ++ii) { allSegments.position(offset * Capnproto.Constants.BYTES_PER_WORD); segmentSlices[ii] = allSegments.slice(); segmentSlices[ii].limit(moreSizes[ii - 1] * Capnproto.Constants.BYTES_PER_WORD); segmentSlices[ii].order(java.nio.ByteOrder.LITTLE_ENDIAN); offset += moreSizes[ii - 1]; } return(new Capnproto.MessageReader(segmentSlices, options)); }
public CompressionLookupRecord(java.nio.ByteBuffer buffer, int compressionLookupSubsectionLocation, RPFColorMap[] colormaps // TODO update LUT with the color mapped values to gain performance ) { this.tableID = NITFSUtil.getUShort(buffer); this.numOfRecords = (int)NITFSUtil.getUInt(buffer); this.numOfValuesPerRecord = NITFSUtil.getUShort(buffer); this.valueBitLength = NITFSUtil.getUShort(buffer); this.tableLocation = (int)(NITFSUtil.getUInt(buffer) + compressionLookupSubsectionLocation); int saveOffset = buffer.position(); this.bytesPerRecord = (short)(this.numOfValuesPerRecord * this.valueBitLength / 8L); this.lut = new byte[this.numOfRecords * this.bytesPerRecord]; buffer.position(this.tableLocation); buffer.get(this.lut, 0, this.numOfRecords * this.bytesPerRecord); buffer.position(saveOffset); }
public virtual java.nio.ByteBuffer put(java.nio.ByteBuffer src) { if (src == this) { throw new System.ArgumentException("src == this"); } int srcByteCount = src.remaining(); if (srcByteCount > remaining()) { throw new java.nio.BufferOverflowException(); } if (src.isDirect()) { throw new System.InvalidOperationException(); } byte[] srcObject = java.nio.NioUtils.unsafeArray(src); int srcOffset = src.position(); if (!src.isDirect()) { srcOffset += java.nio.NioUtils.unsafeArrayOffset(src); } java.nio.ByteBuffer dst = this; if (dst.isDirect()) { throw new System.InvalidOperationException(); } byte[] dstObject = java.nio.NioUtils.unsafeArray(dst); int dstOffset = dst.position(); if (!dst.isDirect()) { dstOffset += java.nio.NioUtils.unsafeArrayOffset(dst); } System.Array.Copy(srcObject, srcOffset, dstObject, dstOffset, srcByteCount); src.position(src.limit()); dst.position(dst.position() + srcByteCount); return(this); }
/// <exception cref="System.IO.IOException"/> public int Read(java.nio.ByteBuffer dst) { int size = System.Math.Min(dst.remaining(), this.buf.remaining()); java.nio.ByteBuffer slice = this.buf.slice(); slice.limit(size); dst.buffer = slice.buffer; dst.offset = slice.offset; dst.limit(size); dst.position(size); this.buf.position(this.buf.position() + size); return(size); }
public static String getString(java.nio.ByteBuffer buffer, int offset, int len) { String s = ""; if (null != buffer && buffer.capacity() >= offset + len) { byte[] dest = new byte[len]; buffer.position(offset); buffer.get(dest, 0, len); s = new String(dest).trim(); } return(s); }
private void parseRPFCoverageSection(java.nio.ByteBuffer buffer) { buffer.position(this.componentLocationTable.getCoverageSectionSubheaderLocation()); this.nwUpperLeft = LatLon.fromDegrees(buffer.getDouble(), buffer.getDouble()); this.swLowerleft = LatLon.fromDegrees(buffer.getDouble(), buffer.getDouble()); this.neUpperRight = LatLon.fromDegrees(buffer.getDouble(), buffer.getDouble()); this.seLowerRight = LatLon.fromDegrees(buffer.getDouble(), buffer.getDouble()); this.verticalResolutionNorthSouth = buffer.getDouble(); this.horizontalResolutionEastWest = buffer.getDouble(); this.verticalIntervalLatitude = buffer.getDouble(); this.horizontalIntervalLongitude = buffer.getDouble(); }
private void loadHistogram(java.nio.ByteBuffer buffer, int colormapSubsectionOffset) { if (0 == this.numOfColorRecords) { throw new NITFSRuntimeException("NITFSReader.InvalidNumberOfColorRecords"); } if (0 == this.histogramRecordLength) { throw new NITFSRuntimeException("NITFSReader.InvalidLengthOfHistogramRecordElement"); } // skip the loading of the histogram table, just increment a position in the buffer buffer.position((int)(colormapSubsectionOffset + this.histogramTableOffset + (this.numOfColorRecords * this.histogramRecordLength))); }
public override string ToString() { byte[] bytes = new byte[this.size]; java.nio.ByteBuffer dup = this.buffer.duplicate(); dup.position(this.offset); dup.get(bytes, 0, this.size); try { return(Sharpen.Runtime.GetStringForBytes(bytes, "UTF-8")); } catch (System.Exception) { throw new System.Exception("UTF-8 is unsupported"); } }
private void loadColorMaps(java.nio.ByteBuffer buffer, int colormapSubsectionOffset) { if (0 == this.numOfColorRecords) { throw new NITFSRuntimeException("NITFSReader.InvalidNumberOfColorRecords"); } if (0 == this.colorElementLength) { throw new NITFSRuntimeException("NITFSReader.InvalidLengthOfColorRecordElement"); } buffer.position((int)(colormapSubsectionOffset + this.colorTableOffset)); int mapLength = (int)(this.numOfColorRecords * this.colorElementLength); this.colorMap = new byte[mapLength]; buffer.get(this.colorMap, 0, mapLength); }
/// <exception cref="System.IO.IOException"></exception> private void flushBytes(bool flushUnderlyingStream) { lock (@lock) { checkStatus(); int position = bytes.position(); if (position > 0) { bytes.flip(); @out.write(((byte[])bytes.array()), bytes.arrayOffset(), position); bytes.clear(); } if (flushUnderlyingStream) { @out.flush(); } } }
private void parseColormapSubSection(java.nio.ByteBuffer buffer) { buffer.position(this.componentLocationTable.getColormapSubsectionLocation()); this.colormapOffsetTableOffset = NITFSUtil.getUInt(buffer); this.colormapGrayscaleOffsetRecordLength = NITFSUtil.getUShort(buffer); // read color / grayscale AND histogram records; builds a ColorMap (LUT) if (0 < this.numOfColorGrayscaleOffsetRecords) { rpfColorMaps = new RPFColorMap[this.numOfColorGrayscaleOffsetRecords]; for (int i = 0; i < this.numOfColorGrayscaleOffsetRecords; i++) { rpfColorMaps[i] = new RPFColorMap(buffer, this.componentLocationTable.getColormapSubsectionLocation()); } } else { throw new NITFSRuntimeException("NITFSReader.InvalidNumberOfRPFColorGrayscaleRecords"); } }
/// <summary> /// Decodes bytes starting at the current position of the given input buffer, /// and writes the equivalent character sequence into the given output buffer /// from its current position. /// </summary> /// <remarks> /// Decodes bytes starting at the current position of the given input buffer, /// and writes the equivalent character sequence into the given output buffer /// from its current position. /// <p> /// The buffers' position will be changed with the reading and writing /// operation, but their limits and marks will be kept intact. /// <p> /// A <code>CoderResult</code> instance will be returned according to /// following rules: /// <ul> /// <li> /// <see cref="CoderResult.OVERFLOW">CoderResult.OVERFLOW</see> /// indicates that /// even though not all of the input has been processed, the buffer the /// output is being written to has reached its capacity. In the event of this /// code being returned this method should be called once more with an /// <code>out</code> argument that has not already been filled.</li> /// <li> /// <see cref="CoderResult.UNDERFLOW">CoderResult.UNDERFLOW</see> /// indicates that /// as many bytes as possible in the input buffer have been decoded. If there /// is no further input and no remaining bytes in the input buffer then this /// operation may be regarded as complete. Otherwise, this method should be /// called once more with additional input.</li> /// <li>A /// <see cref="CoderResult.malformedForLength(int)">malformed input</see> /// result /// indicates that some malformed input error has been encountered, and the /// erroneous bytes start at the input buffer's position and their number can /// be got by result's /// <see cref="CoderResult.length()">length</see> /// . This kind of /// result can be returned only if the malformed action is /// <see cref="CodingErrorAction.REPORT">CodingErrorAction.REPORT</see> /// . </li> /// <li>A /// <see cref="CoderResult.unmappableForLength(int)">unmappable character</see> /// result indicates that some unmappable character error has been /// encountered, and the erroneous bytes start at the input buffer's position /// and their number can be got by result's /// <see cref="CoderResult.length()">length</see> /// . This kind of result can be returned /// only if the unmappable character action is /// <see cref="CodingErrorAction.REPORT">CodingErrorAction.REPORT</see> /// . </li> /// </ul> /// <p> /// The <code>endOfInput</code> parameter indicates that the invoker cannot /// provide further input. This parameter is true if and only if the bytes in /// current input buffer are all inputs for this decoding operation. Note /// that it is common and won't cause an error if the invoker sets false and /// then can't provide more input, while it may cause an error if the invoker /// always sets true in several consecutive invocations. This would make the /// remaining input to be treated as malformed input. /// <p> /// This method invokes the /// <see cref="decodeLoop(java.nio.ByteBuffer, java.nio.CharBuffer)">decodeLoop</see> /// method to /// implement the basic decode logic for a specific charset. /// </remarks> /// <param name="in">the input buffer.</param> /// <param name="out">the output buffer.</param> /// <param name="endOfInput">true if all the input characters have been provided.</param> /// <returns> /// a <code>CoderResult</code> instance which indicates the reason /// of termination. /// </returns> /// <exception cref="System.InvalidOperationException"> /// if decoding has started or no more input is needed in this /// decoding progress. /// </exception> /// <exception cref="CoderMalfunctionError"> /// if the /// <see cref="decodeLoop(java.nio.ByteBuffer, java.nio.CharBuffer)">decodeLoop</see> /// method threw an <code>BufferUnderflowException</code> or /// <code>BufferOverflowException</code>. /// </exception> public java.nio.charset.CoderResult decode(java.nio.ByteBuffer @in, java.nio.CharBuffer @out, bool endOfInput) { if ((status == FLUSH) || (!endOfInput && status == END)) { throw new System.InvalidOperationException(); } java.nio.charset.CoderResult result = null; // begin to decode while (true) { java.nio.charset.CodingErrorAction action = null; try { result = decodeLoop(@in, @out); } catch (java.nio.BufferOverflowException ex) { // unexpected exception throw new java.nio.charset.CoderMalfunctionError(ex); } catch (java.nio.BufferUnderflowException ex) { // unexpected exception throw new java.nio.charset.CoderMalfunctionError(ex); } if (result.isUnderflow()) { int remaining = @in.remaining(); status = endOfInput ? END : ONGOING; if (endOfInput && remaining > 0) { result = java.nio.charset.CoderResult.malformedForLength(remaining); } else { return(result); } } if (result.isOverflow()) { return(result); } // set coding error handle action action = _malformedInputAction; if (result.isUnmappable()) { action = _unmappableCharacterAction; } // If the action is IGNORE or REPLACE, we should continue decoding. if (action == java.nio.charset.CodingErrorAction.REPLACE) { if (@out.remaining() < replacementChars.Length) { return(java.nio.charset.CoderResult.OVERFLOW); } @out.put(replacementChars); } else { if (action != java.nio.charset.CodingErrorAction.IGNORE) { return(result); } } @in.position(@in.position() + result.length()); } }
private void parseColorConverterSubsection(java.nio.ByteBuffer buffer) { buffer.position(this.componentLocationTable.getColorConverterSubsectionLocation()); // if (0 < this.numOfColorConverterOffsetRecords) // throw new NITFSRuntimeException("NITFSReader.NotImplemented.ColorConvertorSubsectionReader"); }
/// <exception cref="System.IO.IOException"/> public int Read(java.nio.ByteBuffer outBuf) { if (outBuf.buffer == null) { outBuf.buffer = new byte[outBuf.remaining()]; } int len = outBuf.remaining(); if (len == 0) { return(0); } if (len % 8 != 0) { throw new System.Exception("PackedInputStream reads must be word-aligned"); } int outPtr = outBuf.position(); int outEnd = outPtr + len; java.nio.ByteBuffer inBuf = this.inner.GetReadBuffer(); while (true) { byte tag = 0; if (inBuf.remaining() < 10) { if (outBuf.remaining() == 0) { return(len); } if (inBuf.remaining() == 0) { inBuf = this.inner.GetReadBuffer(); continue; } //# We have at least 1, but not 10, bytes available. We need to read //# slowly, doing a bounds check on each byte. tag = inBuf.get(); for (int i = 0; i < 8; ++i) { if ((tag & (1 << i)) != 0) { if (inBuf.remaining() == 0) { inBuf = this.inner.GetReadBuffer(); } outBuf.put(inBuf.get()); } else { outBuf.put((byte)0); } } if (inBuf.remaining() == 0 && (tag == 0 || tag == 0xff)) { inBuf = this.inner.GetReadBuffer(); } } else { tag = inBuf.get(); for (int n = 0; n < 8; ++n) { bool isNonzero = (tag & (1 << n)) != 0; outBuf.put(unchecked ((byte)(inBuf.get() & (isNonzero? -1 : 0)))); inBuf.position(inBuf.position() + (isNonzero? 0 : -1)); } } if (tag == 0) { if (inBuf.remaining() == 0) { throw new System.Exception("Should always have non-empty buffer here."); } int runLength = (unchecked ((int)(0xff)) & (int)inBuf.get()) * 8; if (runLength > outEnd - outPtr) { throw new System.Exception("Packed input did not end cleanly on a segment boundary"); } for (int i = 0; i < runLength; ++i) { outBuf.put((byte)0); } } else if (tag == 0xff) { int runLength = (unchecked ((int)(0xff)) & (int)inBuf.get()) * 8; if (inBuf.remaining() >= runLength) { //# Fast path. java.nio.ByteBuffer slice = inBuf.slice(); slice.limit(runLength); outBuf.put(slice); inBuf.position(inBuf.position() + runLength); } else { //# Copy over the first buffer, then do one big read for the rest. runLength -= inBuf.remaining(); outBuf.put(inBuf); java.nio.ByteBuffer slice = outBuf.slice(); slice.limit(runLength); this.inner.Read(slice); outBuf.position(outBuf.position() + runLength); if (outBuf.remaining() == 0) { return(len); } inBuf = this.inner.GetReadBuffer(); continue; } } if (outBuf.remaining() == 0) { return(len); } } }
private int parseSegment(NITFSSegmentType segType, int nextSegmentOffset) { int headerLengthSize = segType.getHeaderLengthSize(); int dataLengthSize = segType.getDataLengthSize(); int numOfSegments = Integer.parseInt(NITFSUtil.getString(this.buffer, 3)); for (int i = 0; i < numOfSegments; i++) { int segHeaderLength = Integer.parseInt(NITFSUtil.getString(this.buffer, headerLengthSize)); int seqDataLength = Integer.parseInt(NITFSUtil.getString(this.buffer, dataLengthSize)); int saveOffset = this.buffer.position(); // pass buffer to NITFSSegment to parse their headers' contents NITFSSegment segment; switch (segType) { case IMAGE_SEGMENT: segment = new NITFSImageSegment(this.buffer, nextSegmentOffset, segHeaderLength, nextSegmentOffset + segHeaderLength, seqDataLength); break; case SYMBOL_SEGMENT: segment = new NITFSSymbolSegment(this.buffer, nextSegmentOffset, segHeaderLength, nextSegmentOffset + segHeaderLength, seqDataLength); break; case LABEL_SEGMENT: segment = new NITFSLabelSegment(this.buffer, nextSegmentOffset, segHeaderLength, nextSegmentOffset + segHeaderLength, seqDataLength); break; case TEXT_SEGMENT: segment = new NITFSTextSegment(this.buffer, nextSegmentOffset, segHeaderLength, nextSegmentOffset + segHeaderLength, seqDataLength); break; case DATA_EXTENSION_SEGMENT: segment = new NITFSDataExtensionSegment(this.buffer, nextSegmentOffset, segHeaderLength, nextSegmentOffset + segHeaderLength, seqDataLength); break; case RESERVED_EXTENSION_SEGMENT: segment = new NITFSReservedExtensionSegment(this.buffer, nextSegmentOffset, segHeaderLength, nextSegmentOffset + segHeaderLength, seqDataLength); break; case USER_DEFINED_HEADER_SEGMENT: segment = new RPFUserDefinedHeaderSegment(this.buffer); break; case EXTENDED_HEADER_SEGMENT: // // throw exception - wrong parser for EXTENDED_HEADER_SEGMENT segment = new NITFSExtendedHeaderSegment(this.buffer, nextSegmentOffset, segHeaderLength, nextSegmentOffset + segHeaderLength, seqDataLength); break; default: throw new NITFSRuntimeException("NITFSReader.UnknownOrUnsupportedSegment", segType.ToString()); } this.segments.add(segment); nextSegmentOffset += segHeaderLength + seqDataLength; buffer.position(saveOffset); // restore offset } return(nextSegmentOffset); }
/// <exception cref="System.IO.IOException"/> public int Write(java.nio.ByteBuffer inBuf) { int length = inBuf.remaining(); java.nio.ByteBuffer @out = this.inner.GetWriteBuffer(); java.nio.ByteBuffer slowBuffer = java.nio.ByteBuffer.allocate(20); int inPtr = inBuf.position(); int inEnd = inPtr + length; while (inPtr < inEnd) { if (@out.remaining() < 10) { //# Oops, we're out of space. We need at least 10 //# bytes for the fast path, since we don't //# bounds-check on every byte. if (@out == slowBuffer) { int oldLimit = @out.limit(); @out.limit(@out.position()); @out.rewind(); this.inner.Write(@out); @out.limit(oldLimit); } @out = slowBuffer; @out.rewind(); } int tagPos = @out.position(); @out.position(tagPos + 1); byte curByte; curByte = inBuf.get(inPtr); byte bit0 = (curByte != 0)? unchecked ((byte)1) : unchecked ((byte)0); @out.put(curByte); @out.position(@out.position() + bit0 - 1); inPtr += 1; curByte = inBuf.get(inPtr); byte bit1 = (curByte != 0)? unchecked ((byte)1) : unchecked ((byte)0); @out.put(curByte); @out.position(@out.position() + bit1 - 1); inPtr += 1; curByte = inBuf.get(inPtr); byte bit2 = (curByte != 0)? unchecked ((byte)1) : unchecked ((byte)0); @out.put(curByte); @out.position(@out.position() + bit2 - 1); inPtr += 1; curByte = inBuf.get(inPtr); byte bit3 = (curByte != 0)? unchecked ((byte)1) : unchecked ((byte)0); @out.put(curByte); @out.position(@out.position() + bit3 - 1); inPtr += 1; curByte = inBuf.get(inPtr); byte bit4 = (curByte != 0)? unchecked ((byte)1) : unchecked ((byte)0); @out.put(curByte); @out.position(@out.position() + bit4 - 1); inPtr += 1; curByte = inBuf.get(inPtr); byte bit5 = (curByte != 0)? unchecked ((byte)1) : unchecked ((byte)0); @out.put(curByte); @out.position(@out.position() + bit5 - 1); inPtr += 1; curByte = inBuf.get(inPtr); byte bit6 = (curByte != 0)? unchecked ((byte)1) : unchecked ((byte)0); @out.put(curByte); @out.position(@out.position() + bit6 - 1); inPtr += 1; curByte = inBuf.get(inPtr); byte bit7 = (curByte != 0)? unchecked ((byte)1) : unchecked ((byte)0); @out.put(curByte); @out.position(@out.position() + bit7 - 1); inPtr += 1; byte tag = unchecked ((byte)((bit0 << 0) | (bit1 << 1) | (bit2 << 2) | (bit3 << 3) | (bit4 << 4) | (bit5 << 5) | (bit6 << 6) | (bit7 << 7))); @out.put(tagPos, tag); if (tag == 0) { //# An all-zero word is followed by a count of //# consecutive zero words (not including the first //# one). int runStart = inPtr; int limit = inEnd; if (limit - inPtr > 255 * 8) { limit = inPtr + 255 * 8; } while (inPtr < limit && inBuf.getLong(inPtr) == 0) { inPtr += 8; } @out.put(unchecked ((byte)((inPtr - runStart) / 8))); } else if (tag == unchecked ((byte)unchecked ((int)(0xff)))) { //# An all-nonzero word is followed by a count of //# consecutive uncompressed words, followed by the //# uncompressed words themselves. //# Count the number of consecutive words in the input //# which have no more than a single zero-byte. We look //# for at least two zeros because that's the point //# where our compression scheme becomes a net win. int runStart = inPtr; int limit = inEnd; if (limit - inPtr > 255 * 8) { limit = inPtr + 255 * 8; } while (inPtr < limit) { byte c = 0; for (int ii = 0; ii < 8; ++ii) { c += (inBuf.get(inPtr) == 0 ? (byte)1 : (byte)0); inPtr += 1; } if (c >= 2) { //# Un-read the word with multiple zeros, since //# we'll want to compress that one. inPtr -= 8; break; } } int count = inPtr - runStart; @out.put(unchecked ((byte)(count / 8))); if (count <= @out.remaining()) { //# There's enough space to memcpy. inBuf.position(runStart); java.nio.ByteBuffer slice = inBuf.slice(); slice.limit(count); @out.put(slice); } else { //# Input overruns the output buffer. We'll give it //# to the output stream in one chunk and let it //# decide what to do. if (@out == slowBuffer) { int oldLimit = @out.limit(); @out.limit(@out.position()); @out.rewind(); this.inner.Write(@out); @out.limit(oldLimit); } inBuf.position(runStart); java.nio.ByteBuffer slice = inBuf.slice(); slice.limit(count); while (slice.hasRemaining()) { this.inner.Write(slice); } @out = this.inner.GetWriteBuffer(); } } } if (@out == slowBuffer) { @out.limit(@out.position()); @out.rewind(); this.inner.Write(@out); } inBuf.position(inPtr); return(length); }
public override int read(char[] buffer, int offset, int length) { lock (@lock) { if (!isOpen()) { throw new System.IO.IOException("InputStreamReader is closed"); } java.util.Arrays.checkOffsetAndCount(buffer.Length, offset, length); if (length == 0) { return(0); } java.nio.CharBuffer @out = java.nio.CharBuffer.wrap(buffer, offset, length); java.nio.charset.CoderResult result = java.nio.charset.CoderResult.UNDERFLOW; // bytes.remaining() indicates number of bytes in buffer // when 1-st time entered, it'll be equal to zero bool needInput = !bytes.hasRemaining(); while (@out.hasRemaining()) { // fill the buffer if needed if (needInput) { try { if (@in.available() == 0 && @out.position() > offset) { // we could return the result without blocking read break; } } catch (System.IO.IOException) { } // available didn't work so just try the read int desiredByteCount = bytes.capacity() - bytes.limit(); int off = bytes.arrayOffset() + bytes.limit(); int actualByteCount = @in.read(((byte[])bytes.array()), off, desiredByteCount); if (actualByteCount == -1) { endOfInput = true; break; } else { if (actualByteCount == 0) { break; } } bytes.limit(bytes.limit() + actualByteCount); needInput = false; } // decode bytes result = decoder.decode(bytes, @out, false); if (result.isUnderflow()) { // compact the buffer if no space left if (bytes.limit() == bytes.capacity()) { bytes.compact(); bytes.limit(bytes.position()); bytes.position(0); } needInput = true; } else { break; } } if (result == java.nio.charset.CoderResult.UNDERFLOW && endOfInput) { result = decoder.decode(bytes, @out, true); decoder.flush(@out); decoder.reset(); } if (result.isMalformed() || result.isUnmappable()) { result.throwException(); } return(@out.position() - offset == 0 ? -1 : @out.position() - offset); } }