Skip to content

Commit d508b73

Browse files
committed
Fix MemoryApi.{Read,Write}ByteRange edge cases
1 parent af44a85 commit d508b73

File tree

1 file changed

+8
-4
lines changed

1 file changed

+8
-4
lines changed

src/BizHawk.Client.Common/Api/Classes/MemoryApi.cs

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -246,11 +246,13 @@ public IReadOnlyList<byte> ReadByteRange(long addr, int length, string domain =
246246
var d = NamedDomainOrCurrent(domain);
247247
if (addr < 0) LogCallback($"Warning: Attempted reads on addresses {addr}..-1 outside range of domain {d.Name} in {nameof(ReadByteRange)}()");
248248
var lastReqAddr = addr + length - 1;
249-
var indexAfterLast = Math.Min(lastReqAddr, d.Size - 1) - addr + 1;
249+
var indexAfterLast = Math.Min(Math.Max(-1L, lastReqAddr), d.Size - 1L) + 1L;
250+
var iSrc = Math.Min(Math.Max(0L, addr), d.Size);
251+
var iDst = iSrc - addr;
250252
var bytes = new byte[length];
251253
using (d.EnterExit())
252254
{
253-
for (var i = addr < 0 ? -addr : 0; i != indexAfterLast; i++) bytes[i] = d.PeekByte(addr + i);
255+
while (iSrc < indexAfterLast) bytes[iDst++] = d.PeekByte(iSrc++);
254256
}
255257
if (lastReqAddr >= d.Size) LogCallback($"Warning: Attempted reads on addresses {d.Size}..{lastReqAddr} outside range of domain {d.Name} in {nameof(ReadByteRange)}()");
256258
return bytes;
@@ -266,10 +268,12 @@ public void WriteByteRange(long addr, IReadOnlyList<byte> memoryblock, string do
266268
}
267269
if (addr < 0) LogCallback($"Warning: Attempted writes on addresses {addr}..-1 outside range of domain {d.Name} in {nameof(WriteByteRange)}()");
268270
var lastReqAddr = addr + memoryblock.Count - 1;
269-
var indexAfterLast = Math.Min(lastReqAddr, d.Size - 1) - addr + 1;
271+
var indexAfterLast = Math.Min(Math.Max(-1L, lastReqAddr), d.Size - 1L) + 1L;
272+
var iDst = Math.Min(Math.Max(0L, addr), d.Size);
273+
var iSrc = checked((int) (iDst - addr));
270274
using (d.EnterExit())
271275
{
272-
for (var i = addr < 0 ? (int)-addr : 0; i != indexAfterLast; i++) d.PokeByte(addr + i, memoryblock[i]);
276+
while (iDst < indexAfterLast) d.PokeByte(iDst++, memoryblock[iSrc++]);
273277
}
274278
if (lastReqAddr >= d.Size) LogCallback($"Warning: Attempted writes on addresses {d.Size}..{lastReqAddr} outside range of domain {d.Name} in {nameof(WriteByteRange)}()");
275279
}

0 commit comments

Comments
 (0)