// Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. using System; using System.Buffers; using System.IO; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace SixLabors.Memory { internal static class BufferExtensions { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span GetSpan(this IMemoryOwner buffer) => buffer.Memory.Span; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int Length(this IMemoryOwner buffer) => buffer.GetSpan().Length; /// /// Gets a to an offseted position inside the buffer. /// /// The buffer /// The start /// The [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span Slice(this IMemoryOwner buffer, int start) { return buffer.GetSpan().Slice(start); } /// /// Gets a to an offsetted position inside the buffer. /// /// The buffer /// The start /// The length of the slice /// The [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span Slice(this IMemoryOwner buffer, int start, int length) { return buffer.GetSpan().Slice(start, length); } /// /// Clears the contents of this buffer. /// /// The buffer [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Clear(this IMemoryOwner buffer) { buffer.GetSpan().Clear(); } public static ref T GetReference(this IMemoryOwner buffer) where T : struct => ref MemoryMarshal.GetReference(buffer.GetSpan()); public static void Read(this Stream stream, IManagedByteBuffer buffer) { stream.Read(buffer.Array, 0, buffer.Length()); } public static void Write(this Stream stream, IManagedByteBuffer buffer) { stream.Write(buffer.Array, 0, buffer.Length()); } } }