Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Image.WrapMemory<TPixel> APIs wrapping Memory<byte> #1314

Merged
merged 15 commits into from
Sep 1, 2020
Merged
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Fix relative offsetting in Pin() methods
Sergio0694 committed Aug 13, 2020
commit 2383245f14f6c054caa59458fb8532d5f4aa24ec
6 changes: 5 additions & 1 deletion src/ImageSharp/Memory/ByteMemoryManager{T}.cs
Original file line number Diff line number Diff line change
@@ -2,6 +2,7 @@
// Licensed under the Apache License, Version 2.0.
using System;
using System.Buffers;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

namespace SixLabors.ImageSharp.Memory
@@ -42,7 +43,10 @@ public override Span<T> GetSpan()
/// <inheritdoc/>
public override MemoryHandle Pin(int elementIndex = 0)
{
return this.memory.Slice(elementIndex).Pin();
// We need to adjust the offset into the wrapped byte segment,
// as the input index refers to the target-cast memory of T.
// We just have to shift this index by the byte size of T.
return this.memory.Slice(elementIndex * Unsafe.SizeOf<T>()).Pin();
}

/// <inheritdoc/>
10 changes: 9 additions & 1 deletion tests/ImageSharp.Tests/Image/ImageTests.WrapMemory.cs
Original file line number Diff line number Diff line change
@@ -105,7 +105,15 @@ public override Span<TTo> GetSpan()
/// <inheritdoc/>
public override MemoryHandle Pin(int elementIndex = 0)
{
return this.memory.Slice(elementIndex).Pin();
int byteOffset = elementIndex * Unsafe.SizeOf<TTo>();
int shiftedOffset = Math.DivRem(byteOffset, Unsafe.SizeOf<TFrom>(), out int remainder);

if (remainder != 0)
{
ThrowHelper.ThrowArgumentException("The input index doesn't result in an aligned item access", nameof(elementIndex));
}

return this.memory.Slice(shiftedOffset).Pin();
}

/// <inheritdoc/>