/// <summary> /// Writes a structure of type T into a slice of bytes. /// </summary> public static void Write <[Primitive] T>(this Span <byte> slice, T value) where T : struct { Contract.Requires(slice.Length >= PtrUtils.SizeOf <T>()); var cast = slice.Cast <byte, T>(); cast[0] = value; }
// Some handy byte manipulation helpers: /// <summary> /// Casts a Slice of one primitive type (T) to another primitive type (U). /// These types may not contain managed objects, in order to preserve type /// safety. This is checked statically by a Roslyn analyzer. /// </summary> /// <param name="slice">The source slice, of type T.</param> public static Span <U> Cast <[Primitive] T, [Primitive] U>(this Span <T> slice) where T : struct where U : struct { int countOfU = slice.Length * PtrUtils.SizeOf <T>() / PtrUtils.SizeOf <U>(); if (countOfU == 0) { return(default(Span <U>)); } return(new Span <U>(slice.Object, slice.Offset, countOfU)); }
/// <summary> /// Reads a structure of type T out of a slice of bytes. /// </summary> public static T Read <[Primitive] T>(this Span <byte> slice) where T : struct { Contract.Requires(slice.Length >= PtrUtils.SizeOf <T>()); return(slice.Cast <byte, T>()[0]); }