Skip to content

Commit

Permalink
Array usage optimizations etc
Browse files Browse the repository at this point in the history
  • Loading branch information
LTRData committed Nov 24, 2024
1 parent c1408cc commit 0a5a6af
Show file tree
Hide file tree
Showing 68 changed files with 609 additions and 394 deletions.
2 changes: 1 addition & 1 deletion Library/DiscUtils.BootConfig/DeviceElementValue.cs
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ public override string ToString()

internal byte[] GetBytes()
{
var buffer = new byte[_record.Size + 0x10];
var buffer = StreamUtilities.GetUninitializedArray<byte>(_record.Size + 0x10);

EndianUtilities.WriteBytesLittleEndian(_parentObject, buffer, 0);
_record.GetBytes(buffer, 0x10);
Expand Down
2 changes: 1 addition & 1 deletion Library/DiscUtils.BootConfig/IntegerElementValue.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public IntegerElementValue(ulong value)

internal byte[] GetBytes()
{
var bytes = new byte[8];
var bytes = StreamUtilities.GetUninitializedArray<byte>(sizeof(ulong));
EndianUtilities.WriteBytesLittleEndian(_value, bytes, 0);
return bytes;
}
Expand Down
2 changes: 1 addition & 1 deletion Library/DiscUtils.BootConfig/IntegerListElementValue.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ public override string ToString()

internal byte[] GetBytes()
{
var bytes = new byte[_values.Length * 8];
var bytes = StreamUtilities.GetUninitializedArray<byte>(_values.Length * 8);
for (var i = 0; i < _values.Length; ++i)
{
EndianUtilities.WriteBytesLittleEndian(_values[i], bytes, i * 8);
Expand Down
8 changes: 4 additions & 4 deletions Library/DiscUtils.Core/Archives/TarFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ public IEnumerable<TarFileRecord> GetFiles(string dir)

public static IEnumerable<TarFileData> EnumerateFiles(Stream archive)
{
var hdrBuf = new byte[512];
var hdrBuf = StreamUtilities.GetUninitializedArray<byte>(512);

string long_path = null;

Expand Down Expand Up @@ -275,7 +275,7 @@ public static IEnumerable<TarFileData> EnumerateFiles(Stream archive)
}
else
{
var data = new byte[hdr.FileLength];
var data = StreamUtilities.GetUninitializedArray<byte>((int)hdr.FileLength);

archive.ReadExactly(data, 0, data.Length);

Expand All @@ -297,7 +297,7 @@ public static IEnumerable<TarFileData> EnumerateFiles(Stream archive)
#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP
public static async IAsyncEnumerable<TarFileData> EnumerateFilesAsync(Stream archive, [EnumeratorCancellation] CancellationToken cancellationToken)
{
var hdrBuf = new byte[512];
var hdrBuf = StreamUtilities.GetUninitializedArray<byte>(512);

string long_path = null;

Expand Down Expand Up @@ -376,7 +376,7 @@ public static async IAsyncEnumerable<TarFileData> EnumerateFilesAsync(Stream arc
}
else
{
var data = new byte[hdr.FileLength];
var data = StreamUtilities.GetUninitializedArray<byte>((int)hdr.FileLength);

await archive.ReadExactlyAsync(data, cancellationToken).ConfigureAwait(false);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
// Based on "libbzip2", Copyright (C) 1996-2007 Julian R Seward.
//

using DiscUtils.Streams;
using System.IO;

namespace DiscUtils.Compression;
Expand Down Expand Up @@ -76,7 +77,7 @@ private void Initialize(int maxSymbols)
throw new InvalidDataException("Invalid number of selectors");
}

_selectors = new byte[numSelectors];
_selectors = StreamUtilities.GetUninitializedArray<byte>(numSelectors);
var mtf = new MoveToFront(numTrees, true);
for (var i = 0; i < numSelectors; ++i)
{
Expand Down
2 changes: 1 addition & 1 deletion Library/DiscUtils.Core/Compression/BZip2DecoderStream.cs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ public BZip2DecoderStream(Stream stream, Ownership ownsStream)

_rleStream = new BZip2RleStream();
_blockDecoder = new BZip2BlockDecoder(blockSize);
_blockBuffer = new byte[blockSize];
_blockBuffer = StreamUtilities.GetUninitializedArray<byte>(blockSize);

if (ReadBlock() == 0)
{
Expand Down
2 changes: 1 addition & 1 deletion Library/DiscUtils.Core/Compression/LZNT1.cs
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,7 @@ public override int Decompress(ReadOnlySpan<byte> source, Span<byte> decompresse

private static byte[] CalcCompressionBits()
{
var result = new byte[4096];
var result = StreamUtilities.GetUninitializedArray<byte>(4096);
byte offsetBits = 0;

var y = 0x10;
Expand Down
2 changes: 1 addition & 1 deletion Library/DiscUtils.Core/Compression/LzxBitStream.cs
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ public byte[] ReadBytes(int count)
throw new InvalidOperationException("Attempt to read bytes when not byte-aligned");
}

var buffer = new byte[count];
var buffer = StreamUtilities.GetUninitializedArray<byte>(count);
ReadBytes(buffer, 0, count);
return buffer;
}
Expand Down
24 changes: 17 additions & 7 deletions Library/DiscUtils.Core/LogicalDiskManager/DynamicDisk.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
//

using System;
using System.Buffers;
using System.IO;
using DiscUtils.Partitions;
using DiscUtils.Streams;
Expand Down Expand Up @@ -113,16 +114,25 @@ internal static PrivateHeader GetPrivateHeader(VirtualDisk disk)

private TocBlock GetTableOfContents()
{
var buffer = new byte[_header.TocSizeLba * 512];
_disk.Content.Position = _header.ConfigurationStartLba * 512 + 1 * _header.TocSizeLba * 512;
var tocSize = (int)(_header.TocSizeLba * 512);

_disk.Content.ReadExactly(buffer, 0, buffer.Length);
var tocBlock = new TocBlock();
tocBlock.ReadFrom(buffer);
var buffer = ArrayPool<byte>.Shared.Rent(tocSize);
try
{
_disk.Content.Position = _header.ConfigurationStartLba * 512 + 1 * _header.TocSizeLba * 512;

_disk.Content.ReadExactly(buffer, 0, tocSize);
var tocBlock = new TocBlock();
tocBlock.ReadFrom(buffer);

if (tocBlock.Signature == "TOCBLOCK")
if (tocBlock.Signature == "TOCBLOCK")
{
return tocBlock;
}
}
finally
{
return tocBlock;
ArrayPool<byte>.Shared.Return(buffer);
}

return null;
Expand Down
12 changes: 6 additions & 6 deletions Library/DiscUtils.Core/Partitions/GuidPartitionTable.cs
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ public static GuidPartitionTable Initialize(Stream disk, Geometry diskGeometry)
// Write the primary header
var headerBuffer = diskGeometry.BytesPerSector <= 1024
? stackalloc byte[diskGeometry.BytesPerSector]
: new byte[diskGeometry.BytesPerSector];
: StreamUtilities.GetUninitializedArray<byte>(diskGeometry.BytesPerSector);

header.WriteTo(headerBuffer);
disk.Position = header.HeaderLba * diskGeometry.BytesPerSector;
Expand Down Expand Up @@ -312,9 +312,9 @@ internal SparseStream Open(GptEntry entry)
return new SubStream(_diskData, start, end - start);
}

private static uint CalcEntriesCrc(byte[] buffer)
private static uint CalcEntriesCrc(ReadOnlySpan<byte> buffer)
{
return Crc32LittleEndian.Compute(Crc32Algorithm.Common, buffer, 0, buffer.Length);
return Crc32LittleEndian.Compute(Crc32Algorithm.Common, buffer);
}

private static int CountEntries<T>(ICollection<T> values, Func<T, bool> pred)
Expand Down Expand Up @@ -355,7 +355,7 @@ private void Init(Stream disk, Geometry diskGeometry)
disk.Position = diskGeometry.BytesPerSector;
var sector = diskGeometry.BytesPerSector <= 1024
? stackalloc byte[diskGeometry.BytesPerSector]
: new byte[diskGeometry.BytesPerSector];
: StreamUtilities.GetUninitializedArray<byte>(diskGeometry.BytesPerSector);

disk.ReadExactly(sector);

Expand Down Expand Up @@ -536,7 +536,7 @@ private void WritePrimaryHeader()
{
var buffer = _diskGeometry.BytesPerSector <= 1024
? stackalloc byte[_diskGeometry.BytesPerSector]
: new byte[_diskGeometry.BytesPerSector];
: StreamUtilities.GetUninitializedArray<byte>(_diskGeometry.BytesPerSector);

_primaryHeader.EntriesCrc = CalcEntriesCrc(_entryBuffer);
_primaryHeader.WriteTo(buffer);
Expand All @@ -551,7 +551,7 @@ private void WriteSecondaryHeader()
{
var buffer = _diskGeometry.BytesPerSector <= 1024
? stackalloc byte[_diskGeometry.BytesPerSector]
: new byte[_diskGeometry.BytesPerSector];
: StreamUtilities.GetUninitializedArray<byte>(_diskGeometry.BytesPerSector);

_secondaryHeader.EntriesCrc = CalcEntriesCrc(_entryBuffer);
_secondaryHeader.WriteTo(buffer);
Expand Down
9 changes: 5 additions & 4 deletions Library/DiscUtils.Core/VirtualDisk.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
using DiscUtils.Internal;
using DiscUtils.Partitions;
using DiscUtils.Streams;
using LTRData.Extensions.Buffers;

namespace DiscUtils;

Expand Down Expand Up @@ -523,7 +524,7 @@ public static VirtualDisk OpenDisk(string path, string forceType, FileAccess acc
else
{
var extension = Path.GetExtension(uri.AbsolutePath);
if (extension.StartsWith(".", StringComparison.Ordinal))
if (extension.StartsWith('.'))
{
extension = extension.Substring(1);
}
Expand Down Expand Up @@ -566,7 +567,7 @@ public static VirtualDisk OpenDisk(DiscFileSystem fs, string path, FileAccess ac
}

var extension = Path.GetExtension(path);
if (extension.StartsWith(".", StringComparison.Ordinal))
if (extension.StartsWith('.'))
{
extension = extension.Substring(1);
}
Expand Down Expand Up @@ -594,7 +595,7 @@ public void Dispose()
/// <returns>The MBR as a byte array.</returns>
public byte[] GetMasterBootRecord()
{
var sector = new byte[Sizes.Sector];
var sector = StreamUtilities.GetUninitializedArray<byte>(Sizes.Sector);

GetMasterBootRecord(sector);

Expand Down Expand Up @@ -687,7 +688,7 @@ public VirtualDisk CreateDifferencingDisk(string path)
internal static VirtualDiskLayer OpenDiskLayer(FileLocator locator, string path, FileAccess access)
{
var extension = Path.GetExtension(path);
if (extension.StartsWith(".", StringComparison.Ordinal))
if (extension.StartsWith('.'))
{
extension = extension.Substring(1);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using DiscUtils.Streams;
using System;
using System.Globalization;
using System.Text;
Expand Down Expand Up @@ -202,7 +203,7 @@ static void WriteInt(int val, byte[] buffer, int offset)

public byte[] GetSecurityDescriptorBinaryForm()
{
var buffer = new byte[BinaryLength];
var buffer = StreamUtilities.GetUninitializedArray<byte>(BinaryLength);
GetBinaryForm(buffer, 0);
return buffer;
}
Expand Down
15 changes: 14 additions & 1 deletion Library/DiscUtils.Core/WindowsSecurity/SecurityIdentifier.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Globalization;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;

namespace DiscUtils.Core.WindowsSecurity;
Expand All @@ -17,10 +18,14 @@ public sealed class SecurityIdentifier : IdentityReference, IComparable<Security

public SecurityIdentifier(string sddlForm)
{
#if NET6_0_OR_GREATER
ArgumentNullException.ThrowIfNull(sddlForm);
#else
if (sddlForm == null)
{
throw new ArgumentNullException(nameof(sddlForm));
}
#endif

buffer = ParseSddlForm(sddlForm);
}
Expand Down Expand Up @@ -119,10 +124,14 @@ public SecurityIdentifier(WellKnownSidType sidType,
}
else
{
#if NET6_0_OR_GREATER
ArgumentNullException.ThrowIfNull(domainSid);
#else
if (domainSid == null)
{
throw new ArgumentNullException(nameof(domainSid));
}
#endif

buffer = domainSid.CreateSubSid(uint.Parse(acct.RidStr)).buffer;
}
Expand Down Expand Up @@ -204,10 +213,14 @@ public uint GetSidSubAuthority(byte index)
// The comparison was determined to be: authority, then subauthority count, then subauthority.
public int CompareTo(SecurityIdentifier sid)
{
#if NET6_0_OR_GREATER
ArgumentNullException.ThrowIfNull(sid);
#else
if (sid == null)
{
throw new ArgumentNullException(nameof(sid));
}
#endif

int result;
if (0 != (result = SidAuthority.CompareTo(sid.SidAuthority)))
Expand Down Expand Up @@ -456,7 +469,7 @@ private static byte[] ParseSddlForm(string sddlForm)
throw new ArgumentException("Only SIDs with revision 1 are supported");
}

var buffer = new byte[8 + (numSubAuthorities * 4)];
var buffer = StreamUtilities.GetUninitializedArray<byte>(8 + (numSubAuthorities * 4));
buffer[0] = 1;
buffer[1] = (byte)numSubAuthorities;

Expand Down
2 changes: 1 addition & 1 deletion Library/DiscUtils.Fat/ClusterStream.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ internal ClusterStream(FatFileSystem fileSystem, FileAccess access, uint firstCl
}

_currentCluster = uint.MaxValue;
_clusterBuffer = new byte[_reader.ClusterSize];
_clusterBuffer = StreamUtilities.GetUninitializedArray<byte>(_reader.ClusterSize);
}

public override long? GetPositionInBaseStream(Stream baseStream, long virtualPosition)
Expand Down
3 changes: 2 additions & 1 deletion Library/DiscUtils.HfsPlus/BTreeGenericRecord.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
// DEALINGS IN THE SOFTWARE.
//

using DiscUtils.Streams;
using System;

namespace DiscUtils.HfsPlus;
Expand All @@ -38,7 +39,7 @@ public BTreeGenericRecord(int size)

public override int ReadFrom(ReadOnlySpan<byte> buffer)
{
_data = new byte[_size];
_data = StreamUtilities.GetUninitializedArray<byte>(_size);
buffer.Slice(0, _size).CopyTo(_data);
return _size;
}
Expand Down
16 changes: 8 additions & 8 deletions Library/DiscUtils.HfsPlus/File.cs
Original file line number Diff line number Diff line change
Expand Up @@ -144,8 +144,8 @@ public IBuffer FileContent
// The data is stored in the resource fork.
var buffer = new FileBuffer(Context, fileInfo.ResourceFork, fileInfo.FileId);
var compressionFork = new CompressionResourceHeader();
var compressionForkData = new byte[CompressionResourceHeader.Size];
buffer.Read(0, compressionForkData, 0, CompressionResourceHeader.Size);
Span<byte> compressionForkData = stackalloc byte[CompressionResourceHeader.Size];
buffer.Read(0, compressionForkData);
compressionFork.ReadFrom(compressionForkData);

// The data is compressed in a number of blocks. Each block originally accounted for
Expand All @@ -154,25 +154,25 @@ public IBuffer FileContent
// the zlib header but the others don't, so we read them directly as deflate streams.
// For each block, we create a separate stream which we later aggregate.
var blockHeader = new CompressionResourceBlockHead();
var blockHeaderData = new byte[CompressionResourceBlockHead.Size];
buffer.Read(compressionFork.HeaderSize, blockHeaderData, 0, CompressionResourceBlockHead.Size);
Span<byte> blockHeaderData = stackalloc byte[CompressionResourceBlockHead.Size];
buffer.Read(compressionFork.HeaderSize, blockHeaderData);
blockHeader.ReadFrom(blockHeaderData);

var blockCount = blockHeader.NumBlocks;
var blocks = new CompressionResourceBlock[blockCount];
var streams = new SparseStream[blockCount];

Span<byte> blockData = stackalloc byte[CompressionResourceBlock.Size];

for (var i = 0; i < blockCount; i++)
{
// Read the block data, first into a buffer and the into the class.
blocks[i] = new CompressionResourceBlock();
var blockData = new byte[CompressionResourceBlock.Size];

buffer.Read(
compressionFork.HeaderSize + CompressionResourceBlockHead.Size +
i * CompressionResourceBlock.Size,
blockData,
0,
blockData.Length);
blockData);
blocks[i].ReadFrom(blockData);

// Create a SubBuffer which points to the data window that corresponds to the block.
Expand Down
Loading

0 comments on commit 0a5a6af

Please sign in to comment.