예제 #1
0
        internal static byte[]? AsUnsafeArray(this IPythonBuffer buffer)
        {
            if (!buffer.IsCContiguous())
            {
                return(null);
            }

            if (buffer.Object is Bytes b)
            {
                return(b.UnsafeByteArray);
            }

            if (buffer.Object is Memory <byte> mem)
            {
                if (MemoryMarshal.TryGetArray(mem, out ArraySegment <byte> seg) && seg.Array != null && seg.Offset == 0 && seg.Count == seg.Array.Length)
                {
                    return(seg.Array);
                }
            }
            else if (buffer.Object is ReadOnlyMemory <byte> rom)
            {
                if (MemoryMarshal.TryGetArray(rom, out ArraySegment <byte> seg) && seg.Array != null && seg.Offset == 0 && seg.Count == seg.Array.Length)
                {
                    return(seg.Array);
                }
            }

            return(null);
        }
예제 #2
0
 public static void CopyTo(this IPythonBuffer buffer, Span <byte> dest)
 {
     if (buffer.IsCContiguous())
     {
         buffer.AsReadOnlySpan().CopyTo(dest);
     }
     else
     {
         int i = 0;
         foreach (byte b in buffer.EnumerateBytes())
         {
             dest[i++] = b;
         }
     }
 }
예제 #3
0
 public static byte[] ToArray(this IPythonBuffer buffer)
 {
     if (buffer.IsCContiguous())
     {
         return(buffer.AsReadOnlySpan().ToArray());
     }
     else
     {
         var bytes = new byte[buffer.NumBytes()];
         int i     = 0;
         foreach (byte b in buffer.EnumerateBytes())
         {
             bytes[i++] = b;
         }
         return(bytes);
     }
 }
예제 #4
0
        public MemoryHolder(IPythonBuffer buffer, int offset, int size)
        {
            if (buffer.IsReadOnly)
            {
                throw new ArgumentException("Buffer must be writable.");
            }
            if (!buffer.IsCContiguous())
            {
                throw new ArgumentException("Buffer must be c-contiguous.");
            }
            if (size < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(size), size, "Non-negative number required.");
            }
            if (offset < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(offset), offset, "Non-negative number required.");
            }

            int bufSize = buffer.NumBytes();
            ReadOnlySpan <byte> memblock = buffer.AsSpan();

            if (memblock.Length != bufSize)
            {
                new ArgumentException("Invalid buffer.");
            }
            if (size > bufSize - offset)
            {
                throw new ArgumentException("Requested memory block exceeds buffer boundaries.");
            }


            _buffer = buffer;
            _handle = buffer.Pin();
            unsafe { _data = (IntPtr)_handle.Pointer + offset; }
            _size = size;
        }