Skip to content

Commit

Permalink
Slightly optimized remaining length calculation by using bit shifting…
Browse files Browse the repository at this point in the history
… instead.
  • Loading branch information
MeltyPlayer committed Nov 25, 2024
1 parent 5ab6f0f commit c586fcc
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ public void Write(IBinaryWriter bw) {
}

[Test]
public void TestIntArrayUntilEndOfStream() {
public void TestInt24ArrayUntilEndOfStream() {
BinarySchemaTestUtil.AssertGenerated(
"""
Expand All @@ -114,6 +114,7 @@ namespace foo.bar;
[BinarySchema]
public partial class Wrapper : IBinaryConvertible {
[RSequenceUntilEndOfStream]
[NumberFormat(SchemaNumberType.INT24)]
public int[] Field { get; set; }
}
""",
Expand All @@ -126,7 +127,57 @@ namespace foo.bar;
public partial class Wrapper {
public void Read(IBinaryReader br) {
this.Field = br.ReadInt32s((br.Length - br.Position) / 4);
this.Field = new int[(br.Length - br.Position) / 3];
for (var i = 0; i < this.Field.Length; ++i) {
this.Field[i] = br.ReadInt24();
}
}
}
""",
"""
using System;
using schema.binary;
namespace foo.bar;
public partial class Wrapper {
public void Write(IBinaryWriter bw) {
for (var i = 0; i < this.Field.Length; ++i) {
bw.WriteInt24(this.Field[i]);
}
}
}
""");
}

[Test]
public void TestInt32ArrayUntilEndOfStream() {
BinarySchemaTestUtil.AssertGenerated(
"""
using schema.binary;
using schema.binary.attributes;
namespace foo.bar;
[BinarySchema]
public partial class Wrapper : IBinaryConvertible {
[RSequenceUntilEndOfStream]
public int[] Field { get; set; }
}
""",
"""
using System;
using System.Collections.Generic;
using schema.binary;
namespace foo.bar;
public partial class Wrapper {
public void Read(IBinaryReader br) {
this.Field = br.ReadInt32s((br.Length - br.Position) >> 2);
}
}
Expand Down
16 changes: 12 additions & 4 deletions Schema/src/binary/text/BinarySchemaReaderGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -579,11 +579,19 @@ var qualifiedElementName
out var size)) {
var remainingLengthAccessor =
$"{READER}.Length - {READER}.Position";
var readCountAccessor = size == 1
? remainingLengthAccessor
: $"({remainingLengthAccessor}) / {size}";

// Members that don't need to be cast are the easiest to read.
var sizeLog2 = Math.Log(size, 2);

string readCountAccessor;
if (size == 1) {
readCountAccessor = remainingLengthAccessor;
} else if (sizeLog2 % 1 == 0) {
readCountAccessor
= $"({remainingLengthAccessor}) >> {sizeLog2}";
} else {
readCountAccessor = $"({remainingLengthAccessor}) / {size}";
}

var elementType = arrayType.ElementType;
if (SchemaGeneratorUtil.TryToGetLabelForMethodWithoutCast(
elementType,
Expand Down

0 comments on commit c586fcc

Please sign in to comment.