// Copyright (c) ppy Pty Ltd . Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable enable using System; using System.Buffers; using System.Diagnostics; using SixLabors.ImageSharp; using SixLabors.ImageSharp.PixelFormats; namespace osu.Framework.Extensions.ImageExtensions { public struct ReadOnlyPixelMemory : IDisposable where TPixel : unmanaged, IPixel { private Image? image; private Memory? memory; private IMemoryOwner? owner; internal ReadOnlyPixelMemory(Image image) { this.image = image; if (image.TryGetSinglePixelSpan(out _)) { owner = null; memory = null; } else { owner = image.CreateContiguousMemory(); memory = owner.Memory; } } /// /// The span of pixels. /// public ReadOnlySpan Span { get { // Occurs when this struct has been default-initialised (the struct itself doesn't accept a nullable image). if (image == null) return Span.Empty; // If the image can be returned without extra contiguous memory allocation. if (image.TryGetSinglePixelSpan(out var pixelSpan)) return pixelSpan; Debug.Assert(memory != null); return memory.Value.Span; } } public void Dispose() { owner?.Dispose(); image = null; memory = null; owner = null; } } }