Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 21 additions & 19 deletions src/NGrib/BufferedBinaryReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
*/

using System;
using System.Buffers;
using System.IO;
using System.Numerics;
using NGrib.Grib2.Sections;
Expand All @@ -44,8 +45,8 @@ public BufferedBinaryReader(Stream stream, bool leaveOpen = false, int bufferSiz
{
this.stream = stream;
this.leaveOpen = leaveOpen;
this.bufferSize = bufferSize;
buffer = new byte[bufferSize];
buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
this.bufferSize = buffer.Length;
MarkBufferAsUsed();
SaveCurrentPosition();
}
Expand Down Expand Up @@ -77,7 +78,7 @@ private bool FillBuffer()
private void EnsureAvailable(int numBytes)
{
if (NumBytesAvailable >= numBytes) return;

// Try to read from the stream
// and check that we were able to read the bytes we wanted
if (!FillBuffer() && NumBytesAvailable < numBytes)
Expand All @@ -86,12 +87,12 @@ private void EnsureAvailable(int numBytes)
}
}

public byte ReadByte()
{
EnsureAvailable(sizeof(byte));
var val = buffer[bufferOffset];
bufferOffset += sizeof(byte);
return val;
public byte ReadByte()
{
EnsureAvailable(sizeof(byte));
var val = buffer[bufferOffset];
bufferOffset += sizeof(byte);
return val;
}

public int ReadUInt8() => ReadByte();
Expand All @@ -106,13 +107,13 @@ public int ReadUInt16()
return val;
}

public int ReadInt16()
{
EnsureAvailable(sizeof(short));
var val = BigEndianBitConverter.ToInt16(buffer, bufferOffset);
bufferOffset += sizeof(short);
return val;
}
public int ReadInt16()
{
EnsureAvailable(sizeof(short));
var val = BigEndianBitConverter.ToInt16(buffer, bufferOffset);
bufferOffset += sizeof(short);
return val;
}

public long ReadUInt32()
{
Expand Down Expand Up @@ -200,7 +201,7 @@ public int ReadIntN(int nbBit)
var result = ReadUIntN(nbBit);
return result.AsSignedInt(nbBit);
}

public BigInteger ReadUInt64()
{
EnsureAvailable(sizeof(ulong));
Expand Down Expand Up @@ -266,7 +267,7 @@ public SectionInfo ReadSectionInfo()
{
return new SectionInfo(Constants.IndicatorSectionLength, SectionCode.IndicatorSection);
}

if (sectionLength == Constants.GribFileEndCode)
{
return new SectionInfo(Constants.EndSectionLength, SectionCode.EndSection);
Expand Down Expand Up @@ -309,14 +310,15 @@ public void Dispose()
{
stream.Close();
}
ArrayPool<byte>.Shared.Return(buffer);
}

public void SaveCurrentPosition()
{
savedPosition = Position;
}

public long Position => stream.Position - NumBytesAvailable;
public long Position => stream.Position - NumBytesAvailable;

public void SeekToSavedPosition()
{
Expand Down