A game framework written with osu! in mind.
at master 1.8 kB view raw
1// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. 2// See the LICENCE file in the repository root for full licence text. 3 4#nullable enable 5 6using System; 7using System.Buffers; 8using System.Diagnostics; 9using SixLabors.ImageSharp; 10using SixLabors.ImageSharp.PixelFormats; 11 12namespace osu.Framework.Extensions.ImageExtensions 13{ 14 public struct ReadOnlyPixelMemory<TPixel> : IDisposable 15 where TPixel : unmanaged, IPixel<TPixel> 16 { 17 private Image<TPixel>? image; 18 private Memory<TPixel>? memory; 19 private IMemoryOwner<TPixel>? owner; 20 21 internal ReadOnlyPixelMemory(Image<TPixel> image) 22 { 23 this.image = image; 24 25 if (image.TryGetSinglePixelSpan(out _)) 26 { 27 owner = null; 28 memory = null; 29 } 30 else 31 { 32 owner = image.CreateContiguousMemory(); 33 memory = owner.Memory; 34 } 35 } 36 37 /// <summary> 38 /// The span of pixels. 39 /// </summary> 40 public ReadOnlySpan<TPixel> Span 41 { 42 get 43 { 44 // Occurs when this struct has been default-initialised (the struct itself doesn't accept a nullable image). 45 if (image == null) 46 return Span<TPixel>.Empty; 47 48 // If the image can be returned without extra contiguous memory allocation. 49 if (image.TryGetSinglePixelSpan(out var pixelSpan)) 50 return pixelSpan; 51 52 Debug.Assert(memory != null); 53 return memory.Value.Span; 54 } 55 } 56 57 public void Dispose() 58 { 59 owner?.Dispose(); 60 image = null; 61 memory = null; 62 owner = null; 63 } 64 } 65}