Skip to content

Commit 7d1bd90

Browse files
authored
Potential bug in TryWriteBytes (#2049)
InnerText has odd length (3 chars). Integer division means InnerText.Length / 2 == 1, so a 1-byte buffer "matches" the truncated size. The guard on line 142 uses && instead of ||, so it falls through and the loop throws on the last Slice.
1 parent d7aceaa commit 7d1bd90

2 files changed

Lines changed: 14 additions & 1 deletion

File tree

src/DocumentFormat.OpenXml.Framework/SimpleTypes/HexBinaryValue.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,7 @@ bool TryWriteBytes(Span<byte> bytes)
139139
return false;
140140
}
141141

142-
if (InnerText.Length % 2 != 0 && bytes.Length != InnerText.Length / 2)
142+
if (InnerText.Length % 2 != 0 || bytes.Length != InnerText.Length / 2)
143143
{
144144
return false;
145145
}

test/DocumentFormat.OpenXml.Tests/SimpleTypes/HexBinaryValueTests.cs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,19 @@ public void GetBytes()
7474
b => Assert.Equal(0x01, b));
7575
}
7676

77+
[Fact]
78+
public void TryWriteBytesWithOddLengthReturnsFalse()
79+
{
80+
// InnerText has odd length (3 chars). Integer division means
81+
// InnerText.Length / 2 == 1, so a 1-byte buffer "matches" the
82+
// truncated size. The guard on line 142 uses && instead of ||,
83+
// so it falls through and the loop throws on the last Slice.
84+
HexBinaryValue type = new("FFF");
85+
var buffer = new byte[1]; // InnerText.Length / 2 with integer division
86+
87+
Assert.False(type.TryWriteBytes(buffer));
88+
}
89+
7790
[Fact]
7891
public void CreateFromBytes()
7992
{

0 commit comments

Comments
 (0)