Slice
Namespace: System · struct
Implements: IEquatable<Slice>, IEquatable<ArraySegment<byte>>, IEquatable<byte[]>, IComparable<Slice>, ISliceSerializable, ISpanFormattable, IFormattable, ISpanEncodable, IComparisonOperators<Slice, Slice, bool>, IEqualityOperators<Slice, Slice, bool>, IEquatable<ReadOnlySpan<byte>>, IEquatable<Span<byte>>, IEquatable<ReadOnlyMemory<byte>>, IComparable<ReadOnlySpan<byte>>, IComparable<Span<byte>>, IComparable<ReadOnlyMemory<byte>>, IEquatable<ReadOnlySpan<char>>, IEquatable<ReadOnlyMemory<char>>
Delimits a read-only section of a byte array
Remarks
A Slice is the logical equivalent to a ReadOnlyMemory
Properties
HasValue
bool HasValue { get; }
Returns true is the slice is not null
An empty slice is NOT considered null
IsEmpty
bool IsEmpty { get; }
Return true if the slice is not null but contains 0 bytes
A null slice is NOT empty
IsNull
bool IsNull { get; }
Returns true if the slice is null
An empty slice is NOT considered null
IsNullOrEmpty
bool IsNullOrEmpty { get; }
Returns true if the slice is null or empty, or false if it contains at least one byte
IsPresent
bool IsPresent { get; }
Returns true if the slice contains at least one byte, or false if it is null or empty
Item
byte Item { get; }
Slice Item { get; }
byte Item { get; }
Slice Item { get; }
Memory
ReadOnlyMemory<byte> Memory { get; }
Returns a ReadOnlyMemory<byte> that wraps the content of this slice
Span
ReadOnlySpan<byte> Span { get; }
Returns a ReadOnlySpan<byte> that wraps the content of this slice
Methods
CompareTo
int CompareTo(Slice other)
Lexicographically compare this slice with another one, and return an indication of their relative sort order
other— Slice to compare with this instance
Returns: Returns a NEGATIVE value if the current slice is LESS THAN other, ZERO if it is EQUAL TO other, and a POSITIVE value if it is GREATER THAN other.
If both this instance and are Nil or Empty, the comparison will return ZERO. If only is Nil or Empty, it will return a NEGATIVE value. If only this instance is Nil or Empty, it will return a POSITIVE value.
int CompareTo(ReadOnlySpan<byte> other)
Lexicographically compare this slice with another span, and return an indication of their relative sort order
other— Span of memory to compare with this instance
Returns: Returns a NEGATIVE value if the current slice is LESS THAN other, ZERO if it is EQUAL TO other, and a POSITIVE value if it is GREATER THAN other.
int CompareTo(Span<byte> other)
Lexicographically compare this slice with another span, and return an indication of their relative sort order
other— Span of memory to compare with this instance
Returns: Returns a NEGATIVE value if the current slice is LESS THAN other, ZERO if it is EQUAL TO other, and a POSITIVE value if it is GREATER THAN other.
int CompareTo(ReadOnlyMemory<byte> other)
Lexicographically compare this slice with another span, and return an indication of their relative sort order
other— Span of memory to compare with this instance
Returns: Returns a NEGATIVE value if the current slice is LESS THAN other, ZERO if it is EQUAL TO other, and a POSITIVE value if it is GREATER THAN other.
ComputeSize
static long ComputeSize(ReadOnlySpan<Slice> slices)
Computes the sum of the length of a list of slices
slices— List of slices to process
Returns: Total size of all the slices
This method can be used to pre-allocate a buffer large enough to fit all the slices
static long ComputeSize(Slice[] slices)
Computes the sum of the length of a list of slices
slices— List of slices to process
Returns: Total size of all the slices
This method can be used to pre-allocate a buffer large enough to fit all the slices
static long ComputeSize(IEnumerable<Slice> slices)
Computes the sum of the length of a list of slices
slices— List of slices to process
Returns: Total size of all the slices
This method can be used to pre-allocate a buffer large enough to fit all the slices
static long ComputeSize(ReadOnlySpan<KeyValuePair<Slice, Slice>> slices)
Computes the sum of the length of the keys and values
slices— List of pairs of slices to process
Returns: Total size of all the keys and values
This method can be used to pre-allocate a buffer large enough to fit all the slices
static long ComputeSize(KeyValuePair<Slice, Slice>[] slices)
Computes the sum of the length of the keys and values
slices— List of pairs of slices to process
Returns: Total size of all the keys and values
This method can be used to pre-allocate a buffer large enough to fit all the slices
static long ComputeSize(IEnumerable<KeyValuePair<Slice, Slice>> slices)
Computes the sum of the length of the keys and values
slices— List of pairs of slices to process
Returns: Total size of all the keys and values
This method can be used to pre-allocate a buffer large enough to fit all the slices
Concat
Slice Concat(Slice tail)
Append/Merge a slice at the end of the current slice
tail— Slice that must be appended
Returns: Merged slice if both slices are contiguous, or a new slice containing the content of the current slice, followed by the tail slice. Or Empty if both parts are nil or empty
Slice Concat(ReadOnlySpan<byte> tail)
Append/Merge a slice at the end of the current slice
tail— Slice that must be appended
Returns: Merged slice if both slices are contiguous, or a new slice containing the content of the current slice, followed by the tail slice. Or Empty if both parts are nil or empty
static Slice Concat(params Slice[] args)
Concatenate an array of slices into a single slice
static Slice Concat(ReadOnlySpan<Slice> args)
Concatenate a sequence of slices into a single slice
static Slice Concat(IEnumerable<Slice> args)
Concatenate a sequence of slices into a single slice
static Slice Concat(Slice a, Slice b)
Concatenate two slices together
static Slice Concat(ReadOnlySpan<byte> a, ReadOnlySpan<byte> b)
Concatenate two spans together
static SliceOwner Concat(ArrayPool<byte> pool, ReadOnlySpan<Slice> args)
Concatenate a sequence of slices into a single slice, allocated using a pool
pool— Pool used to allocate the buffer for the resultargs— List of spans to concatenate
Returns: SliceOwner containing all the slices added one after the other
The caller MUST dispose the result; otherwise, the buffer will not be returned to the pool
static SliceOwner Concat(ArrayPool<byte> pool, IEnumerable<Slice> args)
Concatenate a sequence of slices into a single slice, allocated using a pool
static Slice Concat(Slice a, Slice b, Slice c)
Concatenate three slices together
static Slice Concat(ReadOnlySpan<byte> a, ReadOnlySpan<byte> b, ReadOnlySpan<byte> c)
Concatenate three spans together
static Slice Concat(Slice a, Slice b, Slice c, Slice d)
Concatenate four slices together
static Slice Concat(ReadOnlySpan<byte> a, ReadOnlySpan<byte> b, ReadOnlySpan<byte> c, ReadOnlySpan<byte> d)
Concatenate four spans together
ConcatRange
Slice[] ConcatRange(Slice[] slices)
Append an array of slice at the end of the current slice, all sharing the same buffer
slices— Slices that must be appended
Returns: Array of slices (for all keys) that share the same underlying buffer
Slice[] ConcatRange(ReadOnlySpan<Slice> slices)
Append an array of slice at the end of the current slice, all sharing the same buffer
slices— Slices that must be appended
Returns: Array of slices (for all keys) that share the same underlying buffer
Slice[] ConcatRange(IEnumerable<Slice> slices)
Append a sequence of slice at the end of the current slice, all sharing the same buffer
slices— Slices that must be appended
Returns: Array of slices (for all keys) that share the same underlying buffer
static Slice[] ConcatRange(Slice prefix, IEnumerable<Slice> slices)
Adds a prefix to a list of slices
prefix— Prefix to add to all the slicesslices— List of slices to process
Returns: Array of slice that all start with prefix and followed by the corresponding entry in slices
This method is optimized to reduce the amount of memory allocated
ContainsAny
bool ContainsAny(SearchValues<byte> values)
Searches for the first index of any one of the specified values similar to calling IndexOf several times with the logical OR operator.
Returns: The first index of the occurrence of one any of the values in the span. If not found, returns -1.
ContainsAnyExcept
bool ContainsAnyExcept(SearchValues<byte> values)
Searches for the first index of any byte other than the specified values.
values— The values to avoid.
Returns: The index in the slice of the first occurrence of any byte other than those in values. If all the bytes are in values, returns -1.
Copy
Slice Copy()
Returns a new slice that contains an isolated copy of the buffer
Returns: Slice that is equivalent, but is isolated from any changes to the buffer
static Slice Copy(byte[] source)
Creates a new slice with a copy of the array
static Slice Copy(ReadOnlySpan<byte> source)
Creates a new slice with a copy of the span
static Slice Copy(Span<byte> source)
Creates a new slice with a copy of the span
static Slice Copy(ReadOnlySpan<byte> source, ref byte[] buffer)
Creates a new slice with a copy of the span, using a scratch buffer
static Slice Copy(byte[] source, int offset, int count)
Creates a new slice with a copy of the array segment
CopyTo
void CopyTo(Span<byte> destination)
Copy this slice into another buffer
void CopyTo(Span<byte> destination, out int bytesWritten)
Copy this slice into another buffer
void CopyTo(byte[] buffer, int offset)
Copy this slice into another buffer
buffer— Buffer where to copy this sliceoffset— Offset into the destination buffer
Create
static Slice Create<TState>(int length, TState state, SpanAction<byte, TState> action)
Creates a new Slice with a specific length and initializes it after creation by using the specified callback.
length— The length of the slice to create.state— The element to pass toaction.action— A callback to initialize the slice.
Returns: The created slice.
DangerousGetPinnableReference
byte DangerousGetPinnableReference()
Returns a reference to the first byte in the slice. If the slice is empty, returns a reference to the location where the first character would have been stored. Such a reference can be used for pinning but must never be de-referenced.
Dump
static string Dump(Slice value, int maxSize = 1024)
Returns a printable representation of a key
This may not be efficient, so it should only be use for testing/logging/troubleshooting
static string Dump(ReadOnlySpan<byte> value, int maxSize = 1024)
Returns a printable representation of a key
This may not be efficient, so it should only be use for testing/logging/troubleshooting
static bool Dump(Span<char> destination, out int charsWritten, ReadOnlySpan<byte> value, int maxSize = 1024)
EndsWith
bool EndsWith(byte value)
Determines whether this slice instance ends with the specified byte.
value— The byte to compare.
Returns: true if value matches the end of this slice; otherwise, false
bool EndsWith(int value)
Determines whether this slice instance ends with the specified byte.
value— The value to compare, interpreted as a byte (between 0 and 255).
Returns: true if value matches the end of this slice; otherwise, false
bool EndsWith(char value)
Determines whether this slice instance ends with the specified byte.
value— The value to compare, interpreted as a byte (between 0 and 255).
Returns: true if value matches the end of this slice; otherwise, false
This is a convenience method, where value is expected to be an ASCII character, allowing for easy checks like.
if (data.StartsWith('{') && data.EndsWith('}')) { /* probably JSON */ }
bool EndsWith(Slice value)
Determines whether the end of this slice instance matches a specified slice.
value— The slice to compare to the substring at the end of this instance.
Returns: true if value matches the end of this slice; otherwise, false
bool EndsWith(ReadOnlySpan<byte> value)
Determines whether the end of this slice instance matches a specified slice.
value— The span to compare.
Returns: true if value matches the end of this slice; otherwise, false
bool EndsWith(ReadOnlySpan<char> asciiString)
Determines whether the end of this slice instance matches a specified ASCII keyword
asciiString— String of ASCII chars. Any character with a code pointer greater or equal to 128 will not work as intended
Returns: true if asciiString, when interpreted as bytes, matches the end of this slice; otherwise, false
This method is only intended to test the presence of specific keywords or header signatures when parsing protocols, NOT for matching natural text!
EnsureSliceIsValid
void EnsureSliceIsValid()
Verifies that the Offset and Count fields represent a valid location in Array
This method is inlined for best performance
Equals
bool Equals(ReadOnlySpan<char> asciiString)
Determines whether the slice is equal to the specified ASCII keyword
asciiString— String of ASCII chars. Any character with a code pointer greater or equal to 128 will not work as intended
Returns: true if asciiString, when interpreted as bytes, represents the same bytes as this slice; otherwise, false
This method is only intended to test the presence of specific keywords or header signatures when parsing protocols, NOT for matching natural text!
bool Equals(ReadOnlyMemory<char> asciiString)
Determines whether the slice is equal to the specified ASCII keyword
asciiString— String of ASCII chars. Any character with a code pointer greater or equal to 128 will not work as intended
Returns: true if asciiString, when interpreted as bytes, represents the same bytes as this slice; otherwise, false
This method is only intended to test the presence of specific keywords or header signatures when parsing protocols, NOT for matching natural text!
bool Equals(object obj)
Checks if an object is equal to the current slice
obj— Object that can be either another slice, a byte array, or a byte array segment.
Returns: true if the object represents a sequence of bytes that has the same size and same content as the current slice.
bool Equals(Slice other)
Checks if another slice is equal to the current slice.
other— Slice compared with the current instance
Returns: true if both slices have the same size and contain the same sequence of bytes; otherwise, false.
bool Equals(ReadOnlySpan<byte> other)
Checks if the content of a span is equal to the current slice.
other— Span of memory compared with the current instance
Returns: true if both locations have the same size and contain the same sequence of bytes; otherwise, false.
bool Equals(ReadOnlyMemory<byte> other)
Checks if the content of a span is equal to the current slice.
other— Span of memory compared with the current instance
Returns: true if both locations have the same size and contain the same sequence of bytes; otherwise, false.
bool Equals(Span<byte> other)
Checks if the content of a span is equal to the current slice.
other— Span of memory compared with the current instance
Returns: true if both locations have the same size and contain the same sequence of bytes; otherwise, false.
bool Equals(ArraySegment<byte> other)
Checks if the content of a byte array segment matches the current slice.
other— Byte array segment compared with the current instance
Returns: true if both segment and slice have the same size and contain the same sequence of bytes; otherwise, false.
bool Equals(byte[] other)
Checks if the content of a byte array matches the current slice.
other— Byte array compared with the current instance
Returns: true if the both array and slice have the same size and contain the same sequence of bytes; otherwise, false.
Find
static int Find(Slice source, Slice value)
Reports the zero-based index of the first occurrence of the specified slice in this source.
source— The slice Input slicevalue— The slice to seek
Returns: Offset of the match if positive, or no occurrence was found if negative
static int Find(Slice source, byte value)
Reports the zero-based index of the first occurrence of the specified byte in this source.
source— The slice Input slicevalue— The byte to find
Returns: Offset of the match if positive, or the byte was not found if negative
FromBase64
static Slice FromBase64(string base64String)
Decode a Base64 encoded string into a slice
FromByte
static Slice FromByte(byte value)
Encode an unsigned 8-bit integer into a slice
static Slice FromByte(int value)
Encode an unsigned 8-bit integer into a slice
FromByteString
static Slice FromByteString(string value)
Create a slice from a byte string, where all the characters map directly into bytes (0..255), without performing any validation
This method does not make any effort to detect characters above 255, which will be truncated to their lower 8 bits, introducing corruption when the string will be decoded. Please MAKE SURE to not call this with untrusted data.
Slices encoded by this method are ONLY compatible with UTF-8 encoding if all characters are between 0 and 127. If this is not the case, then decoding it as a UTF-8 sequence may introduce corruption.
For example, Slice.FromByteString("\xff") will return a Slice with the first byte set to 0xFF, as expected. But Slice.FromByteString("\u1234") will have the first byte equal to 0x34 (truncated).
static Slice FromByteString(ReadOnlySpan<char> value)
Create a slice from a byte string, where all the characters map directly into bytes (0..255), without performing any validation
This method does not make any effort to detect characters above 255, which will be truncated to their lower 8 bits, introducing corruption when the string will be decoded. Please MAKE SURE to not call this with untrusted data.
Slices encoded by this method are ONLY compatible with UTF-8 encoding if all characters are between 0 and 127. If this is not the case, then decoding it as a UTF-8 sequence may introduce corruption.
For example, Slice.FromByteString("\xff") will return a Slice with the first byte set to 0xFF, as expected. But Slice.FromByteString("\u1234") will have the first byte equal to 0x34 (truncated).
static Slice FromByteString(ReadOnlySpan<char> value, ref byte[] buffer)
Create a slice from a byte string, where all the characters map directly into bytes (0..255), without performing any validation
This method does not make any effort to detect characters above 255, which will be truncated to their lower 8 bits, introducing corruption when the string will be decoded. Please MAKE SURE to not call this with untrusted data.
Slices encoded by this method are ONLY compatible with UTF-8 encoding if all characters are between 0 and 127. If this is not the case, then decoding it as a UTF-8 sequence may introduce corruption.
For example, Slice.FromByteString("\xff") will return a Slice with the first byte set to 0xFF, as expected. But Slice.FromByteString("\u1234") will have the first byte equal to 0x34 (truncated).
FromBytes
static Slice FromBytes(byte[] source)
Creates a new slice by copying the contents of an array of bytes
source— Array of bytes to copy
Returns: Slice that points to a copy of the bytes in source, or Nil if source is null
Returns the singleton if is empty
Slice.FromBytes((byte[]) null) // => Slice.Nil
Slice.FromBytes(new byte[0]) // => Slice.Empty
Slice.FromBytes(new byte[] { 0x12, 0x34 }) // => [ 0x12, 0x34 ]
Slice.FromBytes("Hello"u8.ToArray()) // => [ 0x48, 0x65, 0x6c, 0x6c, 0x6f ]
static Slice FromBytes(ReadOnlySpan<byte> source)
Creates a new slice by copying the contents of a span of bytes
source— Span of bytes to copy
Returns: Slice that points to a copy of the bytes in source
Returns the Empty singleton if source is empty.
Please be careful when using UTF-8 string literals: the value "\xff..."u8 will be encoded as UTF-8, meaning that it will start with bytes [ 0xC3, 0xBF, ...] and NOT[ 0xFF, .... ] as you could expect! Only '\x00' is safe to use in this way.
Slice.FromBytes([]) // => Slice.Empty
Slice.FromBytes([ 0x12, 0x34 ]) // => [ 0x12, 0x34 ]
Slice.FromBytes("Hello"u8) // => [ 0x48, 0x65, 0x6c, 0x6c, 0x6f ]
Slice.FromBytes("\x00"u8) // => [ 0x00 ]
Slice.FromBytes("\xff"u8) // => [ 0xC3, 0xBF ] !!!
static Slice FromBytes(Span<byte> source)
Creates a new slice by copying the contents of a span of bytes
source— Span of bytes to copy
Returns: Slice that points to a copy of the bytes in source
Returns the Empty singleton if source is empty.
Please be careful when using UTF-8 string literals: the value "\xff..."u8 will be encoded as UTF-8, meaning that it will start with bytes [ 0xC3, 0xBF, ...] and NOT[ 0xFF, .... ] as you could expect! Only '\x00' is safe to use in this way.
Slice.FromBytes([]) // => Slice.Empty
Slice.FromBytes([ 0x12, 0x34 ]) // => [ 0x12, 0x34 ]
Slice.FromBytes("Hello"u8) // => [ 0x48, 0x65, 0x6c, 0x6c, 0x6f ]
Slice.FromBytes("\x00"u8) // => [ 0x00 ]
Slice.FromBytes("\xff"u8) // => [ 0xC3, 0xBF ] !!!
static Slice FromBytes(ReadOnlySpan<byte> source, ref byte[] buffer)
Creates a new Slice by copying the contents of a span of bytes, using a provided scratch buffer
source— Span of bytes to copybuffer— Buffer that should be used to store the bytes. Ifnullor too small, it will be replaced by a newly allocated buffer (with length rounded to the next power of two)
Returns: Slice that points to a copy of the bytes in source, and uses the buffer as its backing store
Returns the Empty singleton if source is empty.
Please be careful when using UTF-8 string literals: the value "\xff..."u8 will be encoded as UTF-8, meaning that it will start with bytes [ 0xC3, 0xBF, ...] and NOT[ 0xFF, .... ] as you could expect! Only '\x00' is safe to use in this way.
// no initial buffer
byte[]? buffer = null;
Slice.FromBytes([ 0x12, 0x34 ], ref buffer) // => allocates a buffer of length 2
Slice.FromBytes([ 0x56, 0x78 ], ref buffer) // => reuses the same buffer
Slice.FromBytes("Hello World"u8, ref buffer) // => allocates a new larger buffer of length 16
// with initial buffer
byte[] buffer = new byte[8];
Slice.FromBytes([ 0x12, 0x34 ], ref buffer) // => uses the initial buffer
Slice.FromBytes([ 0x56, 0x78 ], ref buffer) // => uses the initial buffer
Slice.FromBytes("Hello World"u8, ref buffer) // => allocates a new larger buffer of length 16
static SliceOwner FromBytes(ReadOnlySpan<byte> source, ArrayPool<byte> pool)
Creates a new SliceOwner that wraps a copy the contents of a span of bytes, using a provided ArrayPool
source— Span of bytes to copypool— Pool used to allocate the backing array
Returns: SliceOwner that points to a copy of the bytes in source, using an array rented from the pool as its backing store.
The return value must be disposed for the buffer to return to the pool.
Please be careful when using UTF-8 string literals: the value "\xff..."u8 will be encoded as UTF-8, meaning that it will start with bytes [ 0xC3, 0xBF, ...] and NOT[ 0xFF, .... ] as you could expect! Only '\x00' is safe to use in this way.
Span<byte> data = /* .... */;
using(var buffer = Slice.FromBytes(data, ArrayPool<byte>.Shared))
{
// use buffer.Data or buffer.Memory or buffer.Span
}
FromChar
static Slice FromChar(char value)
Create a slice that holds the UTF-8 encoded representation of value
Returns: The returned slice is only guaranteed to hold 1 byte for ASCII chars (0..127). For non-ASCII chars, the size can be from 1 to 6 bytes. If you need to use ASCII chars, you should use Slice.FromByte() instead
static Slice FromChar(char value, ref byte[] buffer)
Create a slice that holds the UTF-8 encoded representation of value
Returns: The returned slice is only guaranteed to hold 1 byte for ASCII chars (0..127). For non-ASCII chars, the size can be from 1 to 6 bytes. If you need to use ASCII chars, you should use Slice.FromByte() instead
FromDecimal
static Slice FromDecimal(decimal value)
Encodes a 128-bit decimal into an 16-byte slice
FromDouble
static Slice FromDouble(double value)
Encodes a 64-bit decimal into an 8-byte slice
FromDoubleBE
static Slice FromDoubleBE(double value)
Encodes a 64-bit decimal into an 8-byte slice (in network order)
FromFixed128
static Slice FromFixed128(Int128 value)
Encode a signed 128-bit integer into a 16-byte slice in little-endian
static Slice FromFixed128(ulong upper, ulong lower)
Encode a signed 128-bit integer into a 16-byte slice in little-endian
upper— Upper 64-bit of the valuelower— Lower 64-bit of the value
This method is equivalent to calling FromFixed128(new Int128(upper, lower))
static Slice FromFixed128(long upper, ulong lower)
Encode a signed 128-bit integer into a 16-byte slice in little-endian
upper— Upper 64-bit of the valuelower— Lower 64-bit of the value
This method is equivalent to calling FromFixed128(new Int128((ulong) upper, lower))
FromFixed128BE
static Slice FromFixed128BE(Int128 value)
Encode a signed 128-bit integer into a 16-byte slice in big-endian
static Slice FromFixed128BE(ulong upper, ulong lower)
Encode a signed 128-bit integer into a 16-byte slice in big-endian
static Slice FromFixed128BE(long upper, ulong lower)
Encode a signed 128-bit integer into a 16-byte slice in big-endian
FromFixed16
static Slice FromFixed16(short value)
Encode a signed 16-bit integer into a 2-byte slice in little-endian
FromFixed16BE
static Slice FromFixed16BE(short value)
Encode a signed 16-bit integer into a 2-byte slice in little-endian
FromFixed32
static Slice FromFixed32(int value)
Encode a signed 32-bit integer into a 4-byte slice in little-endian
FromFixed32BE
static Slice FromFixed32BE(int value)
Encode a signed 32-bit integer into a 4-byte slice in big-endian
FromFixed64
static Slice FromFixed64(long value)
Encode a signed 64-bit integer into an 8-byte slice in little-endian
FromFixed64BE
static Slice FromFixed64BE(long value)
Encode a signed 64-bit integer into an 8-byte slice in big-endian
FromFixedU128
static Slice FromFixedU128(UInt128 value)
Encode an unsigned 128-bit integer into a 16-byte slice in little-endian
FromFixedU128BE
static Slice FromFixedU128BE(UInt128 value)
Encode an unsigned 128-bit integer into a 16-byte slice in big-endian
FromFixedU16
static Slice FromFixedU16(ushort value)
Encode an unsigned 16-bit integer into a 2-byte slice in little-endian
0x1122 => 11 22
FromFixedU16BE
static Slice FromFixedU16BE(ushort value)
Encode an unsigned 16-bit integer into a 2-byte slice in big-endian
0x1122 => 22 11
FromFixedU32
static Slice FromFixedU32(uint value)
Encode an unsigned 32-bit integer into a 4-byte slice in little-endian
0x11223344 => 11 22 33 44
FromFixedU32BE
static Slice FromFixedU32BE(uint value)
Encode an unsigned 32-bit integer into a 4-byte slice in big-endian
0x11223344 => 44 33 22 11
FromFixedU64
static Slice FromFixedU64(ulong value)
Encode an unsigned 64-bit integer into an 8-byte slice in little-endian
0x1122334455667788 => 11 22 33 44 55 66 77 88
FromFixedU64BE
static Slice FromFixedU64BE(ulong value)
Encode an unsigned 64-bit integer into an 8-byte slice in big-endian
0x1122334455667788 => 88 77 66 55 44 33 22 11
FromGuid
static Slice FromGuid(Guid value)
Create a 16-byte slice containing a System.Guid encoding according to RFC 4122 (Big Endian)
WARNING: Slice.FromGuid(guid).GetBytes() will not produce the same result as guid.ToByteArray() ! If you need to produce Microsoft compatible byte arrays, use Slice.Create(guid.ToByteArray()) but then you should NEVER use Slice.ToGuid() to decode such a value !
FromHalf
static Slice FromHalf(Half value)
Encodes a 64-bit decimal into an 8-byte slice
FromHalfBE
static Slice FromHalfBE(Half value)
Encodes a 64-bit decimal into an 8-byte slice (in network order)
FromHexString
static Slice FromHexString(string hexString)
Convert a hexadecimal encoded string ("1234AA7F") into a slice
hexString— String contains a sequence of pairs of hexadecimal digits with no separating spaces.
Returns: Slice containing the decoded byte array, or an exception if the string is empty or has an odd length
static Slice FromHexString(ReadOnlySpan<char> hexString)
Convert a hexadecimal encoded string ("1234AA7F") into a slice
hexString— String contains a sequence of pairs of hexadecimal digits with no separating spaces.
Returns: Slice containing the decoded byte array, or an exception if the string is empty or has an odd length
static Slice FromHexString(string hexString, char separator)
Convert a hexadecimal encoded string ("1234AA7F") into a slice
hexString— String contains a sequence of pairs of hexadecimal digits with no separating spaces.separator— Allowed separator character between hex pairs, or'\0'for no separator allowed. Note strings with no separators are always allowed
Returns: Slice containing the decoded byte array, or an exception if the string is empty or has an odd length
FromHexa
static Slice FromHexa(string hexString, char separator = ' ')
Convert a hexadecimal encoded string ("1234AA7F") into a slice, ignoring any spaces characters.
hexString— String contains a sequence of pairs of hexadecimal digits, and optional separating white-spaces.separator— Allowed separator character between hex pairs, or'\0'for no separator allowed. Note strings with no separators are always allowed
Returns: Slice containing the decoded byte array, or an exception if the string is empty or has an odd length
If the string is known to not have any spaces or separators, it is faster to call .
static Slice FromHexa(ReadOnlySpan<char> hexString, char separator = ' ')
Convert a hexadecimal encoded string ("1234AA7F") into a slice
hexString— String contains a sequence of pairs of hexadecimal digits with no separating spaces.separator— Allowed separator character between hex pairs, or'\0'for no separator allowed. Note strings with no separators are always allowed
Returns: Slice containing the decoded byte array, or an exception if the string is empty or has an odd length
If the string is known to not have any spaces or separators, it is faster to call .
FromInt128
static Slice FromInt128(Int128 value)
Encode a signed 64-bit integer into an 8-byte slice in little-endian
FromInt16
static Slice FromInt16(short value)
Encode a signed 16-bit integer into a variable size slice (1 or 2 bytes) in little-endian
FromInt16BE
static Slice FromInt16BE(short value)
Encode a signed 16-bit integer into a variable size slice (1 or 2 bytes) in little-endian
FromInt32
static Slice FromInt32(int value)
Encode a signed 32-bit integer into a variable size slice (1 to 4 bytes) in little-endian
FromInt32BE
static Slice FromInt32BE(int value)
Encode a signed 32-bit integer into a variable size slice (1 to 4 bytes) in big-endian
FromInt64
static Slice FromInt64(long value)
Encode a signed 64-bit integer into a variable size slice (1 to 8 bytes) in little-endian
FromInt64BE
static Slice FromInt64BE(long value)
Encode a signed 64-bit integer into a variable size slice (1 to 8 bytes) in big-endian
FromSingle
static Slice FromSingle(float value)
Encode a 32-bit decimal into an 4-byte slice
FromSingleBE
static Slice FromSingleBE(float value)
Encode a 32-bit decimal into an 4-byte slice (in network order)
FromStream
static Slice FromStream(Stream data)
Read the content of a stream into a slice
data— Source stream, that must be in a readable state
Returns: Slice containing the stream content (or Nil if the stream is Null)
FromStreamAsync
static Task<Slice> FromStreamAsync(Stream data, CancellationToken ct)
Asynchronously read the content of a stream into a slice
data— Source stream, that must be in a readable statect— Optional cancellation token for this operation
Returns: Slice containing the stream content (or Nil if the stream is Null)
FromString
static Slice FromString(string value)
Create a slice containing the UTF-8 bytes of the string value.
This method is optimized for strings that usually contain only ASCII characters.
DO NOT call this method to encode special strings that contain binary prefixes, like "\xFF/some/system/path" or "\xFE\x01\x02\x03", because they do not map to UTF-8 directly.
For these case, or when you know that the string only contains ASCII only (with 100% certainty), you should use FromByteString.
static Slice FromString(ReadOnlySpan<char> value)
Create a slice containing the UTF-8 bytes of the string value.
This method is optimized for strings that usually contain only ASCII characters.
DO NOT call this method to encode special strings that contain binary prefixes, like "\xFF/some/system/path" or "\xFE\x01\x02\x03", because they do not map to UTF-8 directly.
For these case, or when you know that the string only contains ASCII only (with 100% certainty), you should use FromByteString.
static Slice FromString(ReadOnlySpan<char> value, ref byte[] buffer)
Create a slice containing the UTF-8 bytes of the string value.
This method is optimized for strings that usually contain only ASCII characters.
DO NOT call this method to encode special strings that contain binary prefixes, like "\xFF/some/system/path" or "\xFE\x01\x02\x03", because they do not map to UTF-8 directly.
For these case, or when you know that the string only contains ASCII only (with 100% certainty), you should use FromByteString.
FromStringAnsi
static Slice FromStringAnsi(string text)
Dangerously create a slice containing string converted to the local ANSI code page. All non-ANSI characters may be corrupted or converted to '?', and this slice may not decode properly on a different system.
WARNING: if you put a string that contains non-ANSI chars, it will be silently corrupted! This should only be used to store keywords or 'safe' strings, and when the decoding will only happen on the same system, or systems using the same codepage.
Slices encoded by this method are not guaranteed to be decoded without loss. YOU'VE BEEN WARNED!
static Slice FromStringAnsi(ReadOnlySpan<char> text)
Dangerously create a slice containing string converted to the local ANSI code page. All non-ANSI characters may be corrupted or converted to '?', and this slice may not decode properly on a different system.
WARNING: if you put a string that contains non-ANSI chars, it will be silently corrupted! This should only be used to store keywords or 'safe' strings, and when the decoding will only happen on the same system, or systems using the same codepage.
Slices encoded by this method are not guaranteed to be decoded without loss. YOU'VE BEEN WARNED!
FromStringAscii
static Slice FromStringAscii(string value)
Create a slice from an ASCII string, where all the characters map directory into bytes (0..255). The string will be checked before being encoded.
This method will check each character and fail if at least one is greater than 255.
Slices encoded by this method are only guaranteed to roundtrip if decoded with ToByteString. If the original string only contained ASCII characters (0..127) then it can also be decoded by ToUnicode.
The only difference between this method and FromByteString is that the later will truncate non-ASCII characters to their lowest 8 bits, while the former will throw an exception.
For example, Slice.FromStringAscii("\xff") will return a Slice with the first byte set to 0xFF, as expected. But Slice.FromStringAscii("\u1234") will throw an exception.
static Slice FromStringAscii(ReadOnlySpan<char> value)
Create a slice from an ASCII string, where all the characters map directory into bytes (0..255). The string will be checked before being encoded.
This method will check each character and fail if at least one is greater than 255.
Slices encoded by this method are only guaranteed to roundtrip if decoded with ToByteString. If the original string only contained ASCII characters (0..127) then it can also be decoded by ToUnicode.
The only difference between this method and FromByteString is that the later will truncate non-ASCII characters to their lowest 8 bits, while the former will throw an exception.
For example, Slice.FromStringAscii("\xff") will return a Slice with the first byte set to 0xFF, as expected. But Slice.FromStringAscii("\u1234") will throw an exception.
static Slice FromStringAscii(ReadOnlySpan<char> value, ref byte[] buffer)
Create a slice from an ASCII string, where all the characters map directory into bytes (0..255). The string will be checked before being encoded.
This method will check each character and fail if at least one is greater than 255.
Slices encoded by this method are only guaranteed to roundtrip if decoded with ToByteString. If the original string only contained ASCII characters (0..127) then it can also be decoded by ToUnicode.
The only difference between this method and FromByteString is that the later will truncate non-ASCII characters to their lowest 8 bits, while the former will throw an exception.
For example, Slice.FromStringAscii("\xff") will return a Slice with the first byte set to 0xFF, as expected. But Slice.FromStringAscii("\u1234") will throw an exception.
FromStringUtf8
static Slice FromStringUtf8(string value)
Create a slice containing the UTF-8 bytes of the string value.
The slice will NOT include the UTF-8 BOM.
This method will not try to identify ASCII-only strings: If the string provided can ONLY contain ASCII, you should use FromStringAscii. If it is more frequent for the string to be ASCII-only than having UNICODE characters, consider using FromString.
DO NOT call this method to encode special strings that contain binary prefixes, like "\xFF/some/system/path" or "\xFE\x01\x02\x03", because they do not map to UTF-8 directly. For these case, or when you know that the string only contains ASCII only (with 100% certainty), you should use FromByteString.
static Slice FromStringUtf8(ReadOnlySpan<char> value)
Create a Slice containing the UTF-8 bytes of subsection of the string value.
The slice will NOT include the UTF-8 BOM.
This method will not try to identify ASCII-only strings: If the string provided can ONLY contain ASCII, you should use FromStringAscii. If it is more frequent for the string to be ASCII-only than having UNICODE characters, consider using FromString.
DO NOT call this method to encode special strings that contain binary prefixes, like "\xFF/some/system/path" or "\xFE\x01\x02\x03", because they do not map to UTF-8 directly. For these case, or when you know that the string only contains ASCII only (with 100% certainty), you should use FromByteString.
static SliceOwner FromStringUtf8(ReadOnlySpan<char> value, ArrayPool<byte> pool)
Creates a SliceOwner containing the UTF-8 bytes of subsection of the string value.
The slice will NOT include the UTF-8 BOM.
This method will not try to identify ASCII-only strings: If the string provided can ONLY contain ASCII, you should use FromStringAscii. If it is more frequent for the string to be ASCII-only than having UNICODE characters, consider using FromString.
DO NOT call this method to encode special strings that contain binary prefixes, like "\xFF/some/system/path" or "\xFE\x01\x02\x03", because they do not map to UTF-8 directly. For these case, or when you know that the string only contains ASCII only (with 100% certainty), you should use FromByteString.
static Slice FromStringUtf8(ReadOnlySpan<char> value, ref byte[] buffer, out bool asciiOnly)
Create a slice containing the UTF-8 bytes of subsection of the string value.
The slice will NOT include the UTF-8 BOM.
This method will not try to identify ASCII-only strings: If the string provided can ONLY contain ASCII, you should use FromStringAscii. If it is more frequent for the string to be ASCII-only than having UNICODE characters, consider using FromString.
DO NOT call this method to encode special strings that contain binary prefixes, like "\xFF/some/system/path" or "\xFE\x01\x02\x03", because they do not map to UTF-8 directly. For these case, or when you know that the string only contains ASCII only (with 100% certainty), you should use FromByteString.
FromStringUtf8WithBom
static Slice FromStringUtf8WithBom(string value)
Create a slice containing the UTF-8 bytes of the string value, prefixed by the UTF-8 BOM.
If the string is null, the Nil slice is returned.
If the string is empty, the UTF-8 BOM is returned.
DO NOT call this method to encode special strings that contain binary prefixes, like "\xFF/some/system/path" or "\xFE\x01\x02\x03", because they do not map to UTF-8 directly. For these case, or when you know that the string only contains ASCII only (with 100% certainty), you should use FromByteString.
static Slice FromStringUtf8WithBom(ReadOnlySpan<char> value)
Create a slice containing the UTF-8 bytes of the string value, prefixed by the UTF-8 BOM.
If the string is null, an empty slice is returned. If the string is empty, the UTF-8 BOM is returned. DO NOT call this method to encode special strings that contain binary prefixes, like "\xFF/some/system/path" or "\xFE\x01\x02\x03", because they do not map to UTF-8 directly. For these case, or when you know that the string only contains ASCII only (with 100% certainty), you should use .
static Slice FromStringUtf8WithBom(ReadOnlySpan<char> value, ref byte[] buffer, out bool asciiOnly)
Create a slice containing the UTF-8 bytes of the string value, prefixed by the UTF-8 BOM.
If the string is null, an empty slice is returned. If the string is empty, the UTF-8 BOM is returned. DO NOT call this method to encode special strings that contain binary prefixes, like "\xFF/some/system/path" or "\xFE\x01\x02\x03", because they do not map to UTF-8 directly. For these case, or when you know that the string only contains ASCII only (with 100% certainty), you should use .
FromUInt128
static Slice FromUInt128(UInt128 value)
Encode a signed 64-bit integer into an 8-byte slice in little-endian
FromUInt16
static Slice FromUInt16(ushort value)
Encode an unsigned 16-bit integer into a variable size slice (1 or 2 bytes) in little-endian
FromUInt16BE
static Slice FromUInt16BE(ushort value)
Encode an unsigned 16-bit integer into a variable size slice (1 or 2 bytes) in little-endian
FromUInt32
static Slice FromUInt32(uint value)
Encode an unsigned 32-bit integer into a variable size slice (1 to 4 bytes) in little-endian
FromUInt32BE
static Slice FromUInt32BE(uint value)
Encode an unsigned 32-bit integer into a variable size slice (1 to 4 bytes) in big-endian
FromUInt64
static Slice FromUInt64(ulong value)
Encode an unsigned 64-bit integer into a variable size slice (1 to 8 bytes) in little-endian
FromUInt64BE
static Slice FromUInt64BE(ulong value)
Encode an unsigned 64-bit integer into a variable size slice (1 to 8 bytes) in big-endian
FromUuid128
static Slice FromUuid128(Uuid128 value)
Create a 16-byte slice containing an RFC 4122 compliant 128-bit UUID
You should never call this method on a slice created from the result of calling System.Guid.ToByteArray() !
FromUuid64
static Slice FromUuid64(Uuid64 value)
Create an 8-byte slice containing a 64-bit UUID
FromUuid80
static Slice FromUuid80(Uuid80 value)
Create a 10-byte slice containing an 80-bit UUID
FromUuid96
static Slice FromUuid96(Uuid96 value)
Create a 12-byte slice containing a 96-bit UUID
FromVarint16
static Slice FromVarint16(ushort value)
Encode an unsigned 16-bit integer into 7-bit encoded unsigned int (aka 'Varint16')
FromVarint32
static Slice FromVarint32(uint value)
Encode an unsigned 32-bit integer into 7-bit encoded unsigned int (aka 'Varint32')
FromVarint64
static Slice FromVarint64(ulong value)
Encode an unsigned 64-bit integer into 7-bit encoded unsigned int (aka 'Varint64')
GetBytes
byte[] GetBytes()
Copies the contents of this slice into a new array.
Returns: An array containing the data in the current slice.
This will return an empty array for both Nil and Empty.
If you need to distinguish between both, you can use GetBytes which will return null for Nil.
byte[] GetBytes(int offset, int count)
Return a byte array containing a subset of the bytes of the slice, or null if the slice is null
Returns: Byte array with a copy of a subset of the slice, or null
GetHashCode
int GetHashCode()
Gets the hash code for this slice
Returns: A 32-bit signed hash code calculated from all the bytes in the slice.
GetPinnableReference
byte GetPinnableReference()
Returns a reference to the 0th element of the Span. If the Span is empty, returns null reference. It can be used for pinning and is required to support the use of span within a fixed statement.
GetTotalSize
static int GetTotalSize(int prefix, Slice[] slices)
Return the sum of the size of all the slices with an additional prefix
prefix— Size of a prefix that would be added before each sliceslices— Array of slices
Returns: Combined total size of all the slices and the prefixes
static int GetTotalSize(int prefix, Slice?[] slices)
Return the sum of the size of all the slices with an additional prefix
prefix— Size of a prefix that would be added before each sliceslices— Array of slices
Returns: Combined total size of all the slices and the prefixes
static int GetTotalSize(int prefix, List<Slice> slices)
Return the sum of the size of all the slices with an additional prefix
prefix— Size of a prefix that would be added before each sliceslices— Array of slices
Returns: Combined total size of all the slices and the prefixes
static int GetTotalSize(int prefix, List<Slice?> slices)
Return the sum of the size of all the slices with an additional prefix
prefix— Size of a prefix that would be added before each sliceslices— Array of slices
Returns: Combined total size of all the slices and the prefixes
GetTotalSizeAndCommonStore
static int GetTotalSizeAndCommonStore(int prefix, Slice[] slices, out byte[] commonStore)
Return the sum of the size of all the slices with an additional prefix, and test if they all share the same buffer
prefix— Size of a prefix that would be added before each sliceslices— Array of slicescommonStore— Receives null if at least two slices are stored in a different buffer. If not null, return the common buffer for all the keys
Returns: Combined total size of all the slices and the prefixes
static int GetTotalSizeAndCommonStore(int prefix, List<Slice> slices, out byte[] commonStore)
Return the sum of the size of all the slices with an additional prefix, and test if they all share the same buffer
prefix— Size of a prefix that would be added before each sliceslices— Array of slicescommonStore— Receives null if at least two slices are stored in a different buffer. If not null, return the common buffer for all the keys
Returns: Combined total size of all the slices and the prefixes
Increment
static Slice Increment(Slice slice)
Returns the first key lexicographically that does not have the passed in slice as a prefix
slice— Slice to increment
Returns: New slice that is guaranteed to be the first key lexicographically higher than slice which does not have slice as a prefix
If the last byte is already equal to 0xFF, it will rollover to 0x00 and the next byte will be incremented.
Slice.Increment(Slice.FromString("ABC")) => "ABD" Slice.Increment(Slice.FromHexa("01 FF")) => { 02 }
IndexOf
int IndexOf(Slice value)
Reports the zero-based index of the first occurrence of the specified slice in this instance.
value— The slice to seek
Returns: The zero-based index of value if that slice is found, or -1 if it is not. If value is Empty, then the return value is -1.
int IndexOf(ReadOnlySpan<byte> value)
Reports the zero-based index of the first occurrence of the specified slice in this instance.
value— The slice to seek
Returns: The zero-based index of value if that slice is found, or -1 if it is not. If value is Empty, then the return value is -1.
int IndexOf(byte value)
Searches for the specified value and returns the index of its first occurrence.
value— The byte to search for
Returns: The index of the occurrence of the value in the span. If not found, returns -1.
int IndexOf(Slice value, int startIndex)
Reports the zero-based index of the first occurrence of the specified slice in this instance. The search starts at a specified position.
value— The slice to seekstartIndex— The search starting position
Returns: The zero-based index of value if that slice is found, or -1 if it is not. If value is Empty, then the return value is startIndex
int IndexOf(ReadOnlySpan<byte> value, int startIndex)
Reports the zero-based index of the first occurrence of the specified slice in this instance. The search starts at a specified position.
value— The slice to seekstartIndex— The search starting position
Returns: The zero-based index of value if that slice is found, or -1 if it is not. If value is Empty, then the return value is startIndex
int IndexOf(byte value, int startIndex)
Reports the zero-based index of the first occurrence of the specified byte in this instance. The search starts at a specified position.
value— The byte to seekstartIndex— The search starting position
Returns: The zero-based index of value if that byte is found, or -1 if it is not.
IndexOfAny
int IndexOfAny(ReadOnlySpan<byte> values)
Searches for the first index of any one of the specified values similar to calling IndexOf several times with the logical OR operator.
Returns: The first index of the occurrence of any one of the values in the span. If not found, returns -1.
int IndexOfAny(SearchValues<byte> values)
Searches for the first index of any one of the specified values similar to calling IndexOf several times with the logical OR operator.
Returns: The first index of the occurrence of any one of the values in the span. If not found, returns -1.
int IndexOfAny(byte value0, byte value1)
Searches for the first index of any one of the specified values similar to calling IndexOf several times with the logical OR operator.
Returns: The first index of the occurrence of any one of the values in the span. If not found, returns -1.
int IndexOfAny(byte value0, byte value1, byte value2)
Searches for the first index of any one of the specified values similar to calling IndexOf several times with the logical OR operator.
Returns: The first index of the occurrence of any one of the values in the span. If not found, returns -1.
IndexOfAnyExcept
int IndexOfAnyExcept(ReadOnlySpan<byte> values)
Searches for the first index of any byte other than the specified values.
values— The values to avoid.
Returns: The index in the slice of the first occurrence of any byte other than those in values. If all the bytes are in values, returns -1.
int IndexOfAnyExcept(SearchValues<byte> values)
Searches for the first index of any byte other than the specified values.
values— The values to avoid.
Returns: The index in the slice of the first occurrence of any byte other than those in values. If all the bytes are in values, returns -1.
ItemRef
byte ItemRef(int index)
Returns a reference to a specific position in the slice
Join
static Slice Join(Slice separator, Slice[] values)
Concatenates all the elements of a slice array, using the specified separator between each element.
separator— The slice to use as a separator. Can be empty.values— An array that contains the elements to concatenate.
Returns: A slice that consists of the elements in a value delimited by the separator slice. If values is an empty array, the method returns Empty.
static Slice Join(Slice separator, ReadOnlySpan<Slice> values)
Concatenates all the elements of a slice array, using the specified separator between each element.
separator— The slice to use as a separator. Can be empty.values— An array that contains the elements to concatenate.
Returns: A slice that consists of the elements in a value delimited by the separator slice. If values is an empty array, the method returns Empty.
static Slice Join(Slice separator, IEnumerable<Slice> values)
Concatenates the specified elements of a slice sequence, using the specified separator between each element.
separator— The slice to use as a separator. Can be empty.values— A sequence will return the elements to concatenate.
Returns: A slice that consists of the slices in values delimited by the separator slice. -or- Empty if values has no elements, or separator and all the elements of values are Empty.
static Slice Join(Slice separator, Slice[] values, int startIndex, int count)
Concatenates the specified elements of a slice array, using the specified separator between each element.
separator— The slice to use as a separator. Can be empty.values— An array that contains the elements to concatenate.startIndex— The first element invaluesto use.count— The number of elements ofvaluesto use.
Returns: A slice that consists of the slices in values delimited by the separator slice. -or- Empty if count is zero, values has no elements, or separator and all the elements of values are Empty.
JoinBytes
static byte[] JoinBytes(Slice separator, IEnumerable<Slice> values)
Concatenates the specified elements of a slice sequence, using the specified separator between each element.
separator— The slice to use as a separator. Can be empty.values— A sequence will return the elements to concatenate.
Returns: A byte array that consists of the slices in values delimited by the separator slice. -or- an empty array if values has no elements, or separator and all the elements of values are Empty.
static byte[] JoinBytes(Slice separator, Slice[] values, int startIndex, int count)
Concatenates the specified elements of a slice array, using the specified separator between each element.
separator— The slice to use as a separator. Can be empty.values— An array that contains the elements to concatenate.startIndex— The first element invaluesto use.count— The number of elements ofvaluesto use.
Returns: A byte array that consists of the slices in values delimited by the separator slice. -or- an empty array if count is zero, values has no elements, or separator and all the elements of values are Empty.
MalformedSlice
static Exception MalformedSlice(Slice slice)
Reject an invalid slice by throw an error with the appropriate diagnostic message.
slice— Slice that is being naughty
Max
static Slice Max(params Slice[] values)
Returns the highest element in an array of keys
static Slice Max(ReadOnlySpan<Slice> values)
Returns the highest element in a span of keys
static Slice Max(Slice a, Slice b)
Returns the highest of two keys
a— First keyb— Second key
Returns: The key that is AFTER the other, using lexicographical order
If both keys are equal, then is returned
static Slice Max(Slice a, Slice b, Slice c)
Returns the highest of three keys
a— First keyb— Second keyc— Second key
Returns: The key that is AFTER the other two, using lexicographical order
Merge
static Slice[] Merge(Slice prefix, Slice[] keys)
Merge an array of keys with a same prefix, all sharing the same buffer
prefix— Prefix shared by all keyskeys— Array of keys to pack
Returns: Array of slices (for all keys) that share the same underlying buffer
static Slice[] Merge(Slice prefix, ReadOnlySpan<Slice> keys)
Merge an array of keys with a same prefix, all sharing the same buffer
prefix— Prefix shared by all keyskeys— Array of keys to pack
Returns: Array of slices (for all keys) that share the same underlying buffer
static Slice[] Merge(Slice prefix, IEnumerable<Slice> keys)
Merge a sequence of keys with a same prefix, all sharing the same buffer
prefix— Prefix shared by all keyskeys— Sequence of keys to pack
Returns: Array of slices (for all keys) that share the same underlying buffer
Min
static Slice Min(params Slice[] values)
Returns the lowest element in an array of keys
static Slice Min(ReadOnlySpan<Slice> values)
Returns the lowest element in a span of keys
static Slice Min(Slice a, Slice b)
Returns the lowest of two keys
a— First keyb— Second key
Returns: The key that is BEFORE the other, using lexicographical order
If both keys are equal, then is returned
static Slice Min(Slice a, Slice b, Slice c)
Returns the lowest of three keys
a— First keyb— Second keyc— Second key
Returns: The key that is BEFORE the other two, using lexicographical order
OrEmpty
Slice OrEmpty()
Returns: The same slice if it is not Nil; otherwise, Empty
PrefixedBy
bool PrefixedBy(Slice parent)
Equivalent of StartsWith, but the returns false if both slices are identical
PrettyPrint
string PrettyPrint()
Helper method that dumps the slice as a string (if it contains only printable ascii chars) or a hex array if it contains non-printable chars. It should only be used for logging and troubleshooting !
Returns: Returns either "'abc'", "<00 42 7F>", or "". Returns "''" for Slice.Empty, and "" for Nil
string PrettyPrint(int maxLen)
Helper method that dumps the slice as a string (if it contains only printable ascii chars) or a hex array if it contains non-printable chars. It should only be used for logging and troubleshooting !
maxLen— Truncate the slice if it exceeds this size
Returns: Returns either "'abc'", "<00 42 7F>", or "". Returns "''" for Slice.Empty, and "" for Nil
Random
static Slice Random(Random prng, int count)
Create a new slice filled with random bytes taken from a random number generator
prng— Pseudo random generator to use (needs locking if instance is shared)count— Number of random bytes to generate
Returns: Slice of count bytes taken from prng
Warning: is not thread-safe ! If the instance is shared between threads, then it needs to be locked before calling this method.
static Slice Random(RandomNumberGenerator rng, int count, bool nonZeroBytes = false)
Create a new slice filled with random bytes taken from a cryptographic random number generator
rng— Random generator to use (needs locking if instance is shared)count— Number of random bytes to generatenonZeroBytes— If true, produce a sequence of non-zero bytes.
Returns: Slice of count bytes taken from rng
Warning: All RNG implementations may not be thread-safe ! If the instance is shared between threads, then it may need to be locked before calling this method.
ReadUInt128
UInt128 ReadUInt128(int offset, int bytes)
Read a variable-length, little-endian encoded, unsigned integer from a specific location in the slice
offset— Relative offset of the first bytebytes— Number of bytes to read (up to 16)
Returns: Decoded unsigned integer.
ReadUInt128BE
UInt128 ReadUInt128BE(int offset, int bytes)
Read a variable-length, big-endian encoded, unsigned integer from a specific location in the slice
offset— Relative offset of the first bytebytes— Number of bytes to read (up to 16)
Returns: Decoded unsigned integer.
ReadUInt16
ushort ReadUInt16(int offset, int bytes)
Read a variable-length, little-endian encoded, unsigned integer from a specific location in the slice
offset— Relative offset of the first bytebytes— Number of bytes to read (up to 2)
Returns: Decoded unsigned short.
ReadUInt16BE
ushort ReadUInt16BE(int offset, int bytes)
Read a variable-length, big-endian encoded, unsigned integer from a specific location in the slice
offset— Relative offset of the first bytebytes— Number of bytes to read (up to 2)
Returns: Decoded unsigned short.
ReadUInt24
uint ReadUInt24(int offset, int bytes)
Read a variable-length, little-endian encoded, unsigned integer from a specific location in the slice
offset— Relative offset of the first bytebytes— Number of bytes to read (up to 2)
Returns: Decoded unsigned short.
ReadUInt24BE
ushort ReadUInt24BE(int offset, int bytes)
Read a variable-length, big-endian encoded, unsigned integer from a specific location in the slice
offset— Relative offset of the first bytebytes— Number of bytes to read (up to 2)
Returns: Decoded unsigned short.
ReadUInt32
uint ReadUInt32(int offset, int bytes)
Read a variable-length, little-endian encoded, unsigned integer from a specific location in the slice
offset— Relative offset of the first bytebytes— Number of bytes to read (up to 4)
Returns: Decoded unsigned integer.
ReadUInt32BE
uint ReadUInt32BE(int offset, int bytes)
Read a variable-length, big-endian encoded, unsigned integer from a specific location in the slice
offset— Relative offset of the first bytebytes— Number of bytes to read (up to 4)
Returns: Decoded unsigned integer.
ReadUInt64
ulong ReadUInt64(int offset, int bytes)
Read a variable-length, little-endian encoded, unsigned integer from a specific location in the slice
offset— Relative offset of the first bytebytes— Number of bytes to read (up to 8)
Returns: Decoded unsigned integer.
ReadUInt64BE
ulong ReadUInt64BE(int offset, int bytes)
Read a variable-length, big-endian encoded, unsigned integer from a specific location in the slice
offset— Relative offset of the first bytebytes— Number of bytes to read (up to 8)
Returns: Decoded unsigned integer.
Repeat
static Slice Repeat(byte value, int count)
Creates a new slice that contains the same byte repeated
value— Byte that will fill the slicecount— Number of bytes
Returns: New slice that contains count times the byte value.
static Slice Repeat(char value, int count)
Creates a new slice that contains the same byte repeated
value— ASCII character (between 0 and 255) that will fill the slice. Ifvalueis greater than 0xFF, only the 8 lowest bits will be usedcount— Number of bytes
Returns: New slice that contains count times the byte value.
Split
Slice[] Split(int stride)
Returns a slice array that contains the sub-slices in instance by cutting fixed-length chunks or size stride.
stride— Size of each chunk that will be cut from this instance. Must be greater or equal to 1.
Returns: An array whose elements contain the sub-slices, each of size stride, except the last slice that may be smaller if the length of this instance is not a multiple of stride. If this instance is Nil then the array will be empty. If it is Empty then the array will we of length 1 and contain the empty slice.
To reduce memory usage, the sub-slices returned in the array will all share the same underlying buffer of the input slice.
Slice[] Split(Slice separator, StringSplitOptions options = 0)
Returns a slice array that contains the sub-slices in this instance that are delimited by the specified separator
separator— The slice that delimits the sub-slices in this instance.options—RemoveEmptyEntriesto omit empty array elements from the array returned; orNoneto include empty array elements in the array returned.
Returns: An array whose elements contains the sub-slices in this instance that are delimited by the value of separator.
static Slice[] Split(Slice input, int stride)
Returns a slice array that contains the sub-slices in input by cutting fixed-length chunks or size stride.
input— Input slice that must be split into sub-slicesstride— Size of each chunk that will be cut frominput. Must be greater or equal to 1.
Returns: An array whose elements contain the sub-slices, each of size stride, except the last slice that may be smaller if the length of input is not a multiple of stride. If input is Nil then the array will be empty. If it is Empty then the array will we of length 1 and contain the empty slice.
To reduce memory usage, the sub-slices returned in the array will all share the same underlying buffer of the input slice.
static Slice[] Split(Slice input, Slice separator, StringSplitOptions options = 0)
Returns a slice array that contains the sub-slices in input that are delimited by separator. A parameter specifies whether to return empty array elements.
input— Input slice that must be split into sub-slicesseparator— Separator that delimits the sub-slices ininput. Cannot be empty or niloptions—RemoveEmptyEntriesto omit empty array elements from the array returned; orNoneto include empty array elements in the array returned.
Returns: An array whose elements contain the sub-slices that are delimited by separator.
If does not contain the delimiter, the returned array consists of a single element that repeats the input, or an empty array if input is itself empty. To reduce memory usage, the sub-slices returned in the array will all share the same underlying buffer of the input slice.
SplitIntoSegments
static Slice[] SplitIntoSegments(byte[] buffer, int start, List<int> endOffsets)
Split a buffer containing multiple contiguous segments into an array of segments
buffer— Buffer containing all the segmentsstart— Offset of the start of the first segmentendOffsets— Array containing, for each segment, the offset of the following segment
Returns: Array of segments
SplitIntoSegments("HelloWorld", 0, [5, 10]) => [{"Hello"}, {"World"}]
StartsWith
bool StartsWith(byte value)
Determines whether this slice instance starts with the specified byte.
value— The byte to compare.
Returns: true if value matches the beginning of this slice; otherwise, false
bool StartsWith(int value)
Determines whether this slice instance starts with the specified byte.
value— The value to compare, interpreted as a byte (between 0 and 255).
Returns: true if value matches the beginning of this slice; otherwise, false
bool StartsWith(char value)
Determines whether this slice instance starts with the specified byte.
value— The value to compare, interpreted as a byte (between 0 and 255).
Returns: true if value matches the beginning of this slice; otherwise, false
This is a convenience method, where value is expected to be an ASCII character, allowing for easy checks like.
if (data.StartsWith('{') && data.EndsWith('}')) { /* probably JSON */ }
bool StartsWith(Slice value)
Determines whether the beginning of this slice instance matches a specified slice.
value— The slice to compare. Nil is not allowed.
Returns: true if value matches the beginning of this slice; otherwise, false
bool StartsWith(ReadOnlySpan<byte> value)
Determines whether the beginning of this slice instance matches a specified slice.
value— The span to compare.
Returns: true if value matches the beginning of this slice; otherwise, false
bool StartsWith(ReadOnlySpan<char> asciiString)
Determines whether the beginning of this slice instance matches a specified ASCII keyword
asciiString— String of ASCII chars. Any character with a code pointer greater or equal to 128 will not work as intended
Returns: true if asciiString, when interpreted as bytes, matches the beginning of this slice; otherwise, false
This method is only intended to test the presence of specific keywords or header signatures when parsing protocols, NOT for matching natural text!
Substring
Slice Substring(int offset)
Retrieves a substring from this instance. The substring starts at a specified character position.
offset— The starting position of the substring. Positive values means from the start, negative values means from the end
Returns: A slice that is equivalent to the substring that begins at offset (from the start or the end depending on the sign) in this instance, or Empty if offset is equal to the length of the slice.
The substring does not copy the original data, and refers to the same buffer as the original slice. Any change to the parent slice's buffer will be seen by the substring. You must call Memoize() on the resulting substring if you want a copy
{"ABCDE"}.Substring(0) => {"ABC"} {"ABCDE"}.Substring(1) => {"BCDE"} {"ABCDE"}.Substring(-2) => {"DE"} {"ABCDE"}.Substring(5) => Slice.Empty Slice.Empty.Substring(0) => Slice.Empty Slice.Nil.Substring(0) => Slice.Empty
Slice Substring(Range range)
Retrieves a substring from this instance. The substring starts at a specified character position and has a specified length.
range— The range to return
Returns: A slice that is equivalent to the substring that starts from range.Start and ends before range.End in this instance, or Slice.Empty if range is empty.
The substring does not copy the original data, and refers to the same buffer as the original slice. Any change to the parent slice's buffer will be seen by the substring. You must call Memoize() on the resulting substring if you want a copy
{"ABCDE"}.Substring(0, 3) => {"ABC"} {"ABCDE"}.Substring(1..4) => {"BCD"} {"ABCDE"}.Substring(^2..) => {"DE"} Slice.Empty.Substring(0..0) => Slice.Empty Slice.Nil.Substring(0..0) => Slice.Empty
Slice Substring(int offset, int count)
Retrieves a substring from this instance. The substring starts at a specified character position and has a specified length.
offset— The starting position of the substring. Positive values means from the start, negative values means from the endcount— Number of bytes in the substring
Returns: A slice that is equivalent to the substring of length count that begins at offset (from the start or the end depending on the sign) in this instance, or Slice.Empty if count is zero.
The substring does not copy the original data, and refers to the same buffer as the original slice. Any change to the parent slice's buffer will be seen by the substring. You must call Memoize() on the resulting substring if you want a copy
{"ABCDE"}.Substring(0, 3) => {"ABC"} {"ABCDE"}.Substring(1, 3) => {"BCD"} {"ABCDE"}.Substring(-2, 2) => {"DE"} Slice.Empty.Substring(0, 0) => Slice.Empty Slice.Nil.Substring(0, 0) => Slice.Empty
SuffixedBy
bool SuffixedBy(Slice parent)
Equivalent of EndsWith, but will return false if both slices are identical
ThrowIfNull
static void ThrowIfNull(Slice argument, string message = null, string paramName = null)
Throws an exception if the slice is equal to Nil
ThrowIfNullOrEmpty
static void ThrowIfNullOrEmpty(Slice argument, string message = null, string paramName = null)
Throws an exception if the slice is equal to Nil or Empty
ToArray
byte[] ToArray()
Copies the contents of this slice into a new array.
Returns: An array containing the data in the current slice.
This will return an empty array for both Nil and Empty.
If you need to distinguish between both, you can use GetBytes which will return null for Nil.
ToBase64
string ToBase64()
Converts a slice using Base64 encoding
ToBool
bool ToBool()
Converts a slice into a boolean.
Returns: False if the slice is empty, or is equal to the byte 0; otherwise, true.
ToByte
byte ToByte()
Converts a slice into a byte
Returns: Value of the first and only byte of the slice, or 0 if the slice is null or empty.
ToByteString
string ToByteString()
Stringify a slice containing only ASCII chars
Returns: ASCII string, or null if the slice is null
ToDecimal
decimal ToDecimal()
Converts a slice into a 128-bit IEEE floating point.
Returns: 0 of the slice is null or empty, a floating point number, or an error if the slice has more than 8 bytes
ToDouble
double ToDouble()
Converts a slice into a 64-bit IEEE floating point.
Returns: 0 of the slice is null or empty, a floating point number, or an error if the slice has more than 8 bytes
ToDoubleBE
double ToDoubleBE()
Converts a slice into a 64-bit IEEE floating point (in network order).
Returns: 0 of the slice is null or empty, a floating point number, or an error if the slice has more than 8 bytes
ToGuid
Guid ToGuid()
Converts a slice into a Guid.
Returns: Native Guid decoded from the Slice.
The slice can either be a 16-byte RFC4122 GUID, or an ASCII string of 36 chars
ToHalf
Half ToHalf()
Converts a slice into a 16-bit IEEE floating point.
Returns: 0 of the slice is null or empty, a floating point number, or an error if the slice has more than 8 bytes
ToHalfBE
Half ToHalfBE()
Converts a slice into a 16-bit IEEE floating point (in network order).
Returns: 0 of the slice is null or empty, a floating point number, or an error if the slice has more than 8 bytes
ToHexString
string ToHexString()
Converts a slice into a string with each byte encoded into uppercase hexadecimal (0-9A-F)
Returns: ex: "0123456789ABCDEF"
The result is identical to the "N" format when calling or
string ToHexString(char sep)
Converts a slice into a string with each byte encoded into uppercase hexadecimal (0-9A-F), separated by a character
sep— Character used to separate the hexadecimal pairs (ex:' ')
Returns: "01 23 45 67 89 AB CD EF"
When is ' ', the result is identical to the "X" format when calling or
ToHexStringLower
string ToHexStringLower()
Converts a slice into a string with each byte encoded into lowercase hexadecimal (0-9a-f)
Returns: ex: "0123456789abcdef"
The result is identical to the "n" format when calling or
string ToHexStringLower(char sep)
Converts a slice into a string with each byte encoded into lowercase hexadecimal (0-9a-f), separated by a character
sep— Character used to separate the hexadecimal pairs (ex:' ')
Returns: "01 23 45 67 89 ab cd ef"
When is ' ', the result is identical to the "n" format when calling or
ToInt128
Int128 ToInt128()
Converts a slice into a little-endian encoded, signed 128-bit integer.
Returns: 0 of the slice is null or empty, a signed integer, or an error if the slice has more than 8 bytes
ToInt128BE
Int128 ToInt128BE()
Converts a slice into a big-endian encoded, signed 128-bit integer.
Returns: 0 of the slice is null or empty, a signed integer, or an error if the slice has more than 8 bytes
ToInt16
short ToInt16()
Converts a slice into a little-endian encoded, signed 16-bit integer.
Returns: 0 of the slice is null or empty, a signed integer, or an error if the slice has more than 2 bytes
ToInt16BE
short ToInt16BE()
Converts a slice into a big-endian encoded, signed 16-bit integer.
Returns: 0 of the slice is null or empty, a signed integer, or an error if the slice has more than 2 bytes
ToInt24
int ToInt24()
Converts a slice into a little-endian encoded, signed 24-bit integer.
Returns: 0 of the slice is null or empty, a signed integer, or an error if the slice has more than 3 bytes
ToInt24BE
int ToInt24BE()
Converts a slice into a big-endian encoded, signed 24-bit integer.
Returns: 0 of the slice is null or empty, a signed integer, or an error if the slice has more than 3 bytes
ToInt32
int ToInt32()
Converts a slice into a little-endian encoded, signed 32-bit integer.
Returns: 0 of the slice is null or empty, a signed integer, or an error if the slice has more than 4 bytes
ToInt32BE
int ToInt32BE()
Converts a slice into a big-endian encoded, signed 32-bit integer.
Returns: 0 of the slice is null or empty, a signed integer, or an error if the slice has more than 4 bytes
ToInt64
long ToInt64()
Converts a slice into a little-endian encoded, signed 64-bit integer.
Returns: 0 of the slice is null or empty, a signed integer, or an error if the slice has more than 8 bytes
ToInt64BE
long ToInt64BE()
Converts a slice into a big-endian encoded, signed 64-bit integer.
Returns: 0 of the slice is null or empty, a signed integer, or an error if the slice has more than 8 bytes
ToSByte
sbyte ToSByte()
Converts a slice into a signed byte (-128...+127)
Returns: Value of the first and only byte of the slice, or 0 if the slice is null or empty.
ToSingle
float ToSingle()
Converts a slice into a 32-bit IEEE floating point.
Returns: 0 of the slice is null or empty, a floating point number, or an error if the slice has more than 4 bytes
ToSingleBE
float ToSingleBE()
Converts a slice into a 32-bit IEEE floating point (in network order).
Returns: 0 of the slice is null or empty, a floating point number, or an error if the slice has more than 4 bytes
ToSliceReader
SliceReader ToSliceReader()
Return a SliceReader that can decode this slice into smaller fields
ToString
string ToString()
Returns a printable representation of the key
You can roundtrip the result of calling slice.ToString() by passing it to (string) and get back the original slice.
string ToString(string format)
Returns a printable representation of the key
You can roundtrip the result of calling slice.ToString() by passing it to (string) and get back the original slice.
string ToString(string format, IFormatProvider provider)
Formats the slice using the specified encoding
format— A single format specifier that indicates how to format the value of this Slice. Theformatparameter can be "N", "D", "X", or "P". If format is null or an empty string (""), "D" is used. A lower case character will usually produce lowercased hexadecimal letters.provider— This parameter is not used
The format D is the default, and produce a roundtrip-able version of the slice, using
ToStringAnsi
string ToStringAnsi()
Stringify a slice containing characters in the operating system's current ANSI codepage
Returns: Decoded string, or null if the slice is Nil
Calling this method on a slice that is not ANSI, or was generated with different codepage than the current process, will return a corrupted string! This method should ONLY be used to interop with the Win32 API or unmanaged libraries that require the ANSI codepage! You SHOULD NOT use this to expose data to other systems or locale (via sockets, files, ...) If you are decoding natural text, you should probably change the encoding at the source to be UTF-8! If you are decoding identifiers or keywords that are known to be ASCII only, you should use instead (safe). If these identifiers can contain 'special' bytes (like \xFF or \xFE), you should use instead (unsafe).
ToStringAscii
string ToStringAscii()
Stringify a slice containing 7-bit ASCII characters only
Returns: Decoded string, or null if the slice is null
This method should ONLY be used to decoded data that is GUARANTEED to be in the range 0..127. This method will THROW if any byte in the slice has bit 7 set to 1 (ie: >= 0x80) If you are decoding identifiers or keywords with 'special' bytes (like \xFF or \xFE), you should use instead. If you are decoding natural text, or text from unknown origin, you should use or instead. If you are attempting to decode a string obtain from a Win32 or unmanaged library call, you should use instead.
ToStringUtf8
string ToStringUtf8()
Decode a slice that is known to contain a UTF-8 encoded string with an optional UTF-8 BOM
Returns: Decoded string, or null if the slice is null
This method will THROW if the slice does not contain valid UTF-8 sequences. This method will remove any UTF-8 BOM if present. If you need to keep the BOM as the first character of the string, use
ToStringUtf8Lenient
string ToStringUtf8Lenient()
Decode a slice as a UTF-8 string for DISPLAY purposes, replacing any invalid byte with the Unicode replacement character (U+FFFD) instead of throwing.
Returns: Decoded string, or null if the slice is Nil. Any UTF-8 BOM is removed, matching ToStringUtf8.
Unlike ToStringUtf8, this method NEVER throws on invalid UTF-8: it exists for diagnostic dumps and logging of arbitrary output bytes whose encoding is not guaranteed.
Do NOT use it to decode data that must round-trip: a genuine parse should use the strict ToStringUtf8 and fail on invalid bytes.
ToUInt128
UInt128 ToUInt128()
Converts a slice into a little-endian encoded, unsigned 128-bit integer.
Returns: 0 of the slice is null or empty, an unsigned integer, or an error if the slice has more than 16 bytes
ToUInt128BE
UInt128 ToUInt128BE()
Converts a slice into a little-endian encoded, unsigned 128-bit integer.
Returns: 0 of the slice is null or empty, an unsigned integer, or an error if the slice has more than 16 bytes
ToUInt16
ushort ToUInt16()
Converts a slice into a little-endian encoded, unsigned 16-bit integer.
Returns: 0 of the slice is null or empty, an unsigned integer, or an error if the slice has more than 2 bytes
ToUInt16BE
ushort ToUInt16BE()
Converts a slice into a little-endian encoded, unsigned 16-bit integer.
Returns: 0 of the slice is null or empty, an unsigned integer, or an error if the slice has more than 2 bytes
ToUInt24
uint ToUInt24()
Converts a slice into a little-endian encoded, unsigned 24-bit integer.
Returns: 0 of the slice is null or empty, an unsigned integer, or an error if the slice has more than 3 bytes
ToUInt24BE
uint ToUInt24BE()
Converts a slice into a little-endian encoded, unsigned 24-bit integer.
Returns: 0 of the slice is null or empty, an unsigned integer, or an error if the slice has more than 3 bytes
ToUInt32
uint ToUInt32()
Converts a slice into a little-endian encoded, unsigned 32-bit integer.
Returns: 0 of the slice is null or empty, an unsigned integer, or an error if the slice has more than 4 bytes
ToUInt32BE
uint ToUInt32BE()
Converts a slice into a big-endian encoded, unsigned 32-bit integer.
Returns: 0 of the slice is null or empty, an unsigned integer, or an error if the slice has more than 4 bytes
ToUInt64
ulong ToUInt64()
Converts a slice into a little-endian encoded, unsigned 64-bit integer.
Returns: 0 of the slice is null or empty, an unsigned integer, or an error if the slice has more than 8 bytes
ToUInt64BE
ulong ToUInt64BE()
Converts a slice into a little-endian encoded, unsigned 64-bit integer.
Returns: 0 of the slice is null or empty, an unsigned integer, or an error if the slice has more than 8 bytes
ToUnicode
string ToUnicode()
Stringify a slice containing either 7-bit ASCII, or UTF-8 characters
Returns: Decoded string, or null if the slice is null. The encoding will be automatically detected
This should only be used for slices produced by any of the , , , or methods. This is NOT compatible with slices produced by or encoded with any specific encoding or code page. This method will NOT automatically remove the UTF-8 BOM if present (use if you need this)
ToUuid128
Uuid128 ToUuid128()
Converts this slice into a 128-bit UUID.
Returns: Uuid decoded from the Slice.
The slice can either be a 16-byte RFC4122 GUID, or an ASCII string of 36 chars
ToUuid48
Uuid48 ToUuid48()
Converts this slice into a 64-bit UUID.
Returns: Uuid decoded from the Slice.
The slice can either be an 10-byte array, or an ASCII string of 20, 22 or 24 chars
ToUuid64
Uuid64 ToUuid64()
Converts this slice into a 64-bit UUID.
Returns: Uuid decoded from the Slice.
The slice can either be an 8-byte array, or an ASCII string of 16, 17 or 19 chars
ToUuid80
Uuid80 ToUuid80()
Converts this slice into a 64-bit UUID.
Returns: Uuid decoded from the Slice.
The slice can either be an 10-byte array, or an ASCII string of 20, 22 or 24 chars
ToUuid96
Uuid96 ToUuid96()
Converts this slice into a 64-bit UUID.
Returns: Uuid decoded from the Slice.
The slice can either be an 12-byte array, or an ASCII string of 24, 26 or 28 chars
Truncate
Slice Truncate(int maxSize)
Truncate the slice if its size exceeds the specified length.
maxSize— Maximum size.
Returns: Slice of at most the specified size, or smaller if the original slice does not exceed the size.
- Smaller than maxSize is unmodified {"Hello, World!"}.Truncate(20) => {"Hello, World!"}
- Larger than maxSize is truncated {"Hello, World!"}.Truncate(5) => {"Hello"}
- Truncating to 0 returns Empty (or Nil) {"Hello, World!"}.Truncate(0) == Slice.Empty
TryConvertToDoubleBigEndian
bool TryConvertToDoubleBigEndian(out double value)
Converts a slice into a 64-bit IEEE floating point (in network order).
Returns: 0 of the slice is null or empty, a floating point number, or an error if the slice has more than 8 bytes
TryConvertToDoubleLittleEndian
bool TryConvertToDoubleLittleEndian(out double value)
Converts a slice into a 64-bit IEEE floating point.
Returns: 0 of the slice is null or empty, a floating point number, or an error if the slice has more than 8 bytes
TryConvertToGuid
bool TryConvertToGuid(out Guid value)
Converts a slice into a Guid.
Returns: Native Guid decoded from the Slice.
The slice can either be a 16-byte RFC4122 GUID, or an ASCII string of 36 chars
TryConvertToInt128
bool TryConvertToInt128(out Int128 value)
Converts a slice into a little-endian encoded, signed 128-bit integer.
Returns: 0 of the slice is null or empty, a signed integer, or an error if the slice has more than 8 bytes
TryConvertToInt32BigEndian
bool TryConvertToInt32BigEndian(out int value)
Converts a slice into a big-endian encoded, signed 32-bit integer.
Returns: 0 of the slice is null or empty, a signed integer, or an error if the slice has more than 4 bytes
TryConvertToInt32LittleEndian
bool TryConvertToInt32LittleEndian(out int value)
Converts a slice into a little-endian encoded, signed 32-bit integer.
Returns: 0 of the slice is null or empty, a signed integer, or an error if the slice has more than 4 bytes
TryConvertToInt64BigEndian
bool TryConvertToInt64BigEndian(out long value)
Converts a slice into a big-endian encoded, signed 64-bit integer.
Returns: 0 of the slice is null or empty, a signed integer, or an error if the slice has more than 8 bytes
TryConvertToInt64LittleEndian
bool TryConvertToInt64LittleEndian(out long value)
Converts a slice into a little-endian encoded, signed 64-bit integer.
Returns: 0 of the slice is null or empty, a signed integer, or an error if the slice has more than 8 bytes
TryConvertToSingleBigEndian
bool TryConvertToSingleBigEndian(out float value)
Converts a slice into a 32-bit IEEE floating point (in network order).
Returns: 0 of the slice is null or empty, a floating point number, or an error if the slice has more than 4 bytes
TryConvertToSingleLittleEndian
bool TryConvertToSingleLittleEndian(out float value)
Converts a slice into a 32-bit IEEE floating point.
Returns: 0 of the slice is null or empty, a floating point number, or an error if the slice has more than 4 bytes
TryConvertToUInt128LittleEndian
bool TryConvertToUInt128LittleEndian(out UInt128 value)
Converts a slice into a little-endian encoded, unsigned 128-bit integer.
Returns: 0 of the slice is null or empty, an unsigned integer, or an error if the slice has more than 16 bytes
TryConvertToUInt32BigEndian
bool TryConvertToUInt32BigEndian(out uint value)
Converts a slice into a big-endian encoded, unsigned 32-bit integer.
Returns: 0 of the slice is null or empty, an unsigned integer, or an error if the slice has more than 4 bytes
TryConvertToUInt32LittleEndian
bool TryConvertToUInt32LittleEndian(out uint value)
Converts a slice into a little-endian encoded, unsigned 32-bit integer.
Returns: 0 of the slice is null or empty, an unsigned integer, or an error if the slice has more than 4 bytes
TryConvertToUInt64BigEndian
bool TryConvertToUInt64BigEndian(out ulong value)
Converts a slice into a little-endian encoded, unsigned 64-bit integer.
Returns: 0 of the slice is null or empty, an unsigned integer, or an error if the slice has more than 8 bytes
TryConvertToUInt64LittleEndian
bool TryConvertToUInt64LittleEndian(out ulong value)
Converts a slice into a little-endian encoded, unsigned 64-bit integer.
Returns: 0 of the slice is null or empty, an unsigned integer, or an error if the slice has more than 8 bytes
TryConvertToUuid128
bool TryConvertToUuid128(out Uuid128 value)
Converts this slice into a 128-bit UUID.
Returns: Uuid decoded from the Slice.
The slice can either be a 16-byte RFC4122 GUID, or an ASCII string of 36 chars
TryConvertToUuid48
bool TryConvertToUuid48(out Uuid48 value)
Converts this slice into a 64-bit UUID.
Returns: Uuid decoded from the Slice.
The slice can either be an 10-byte array, or an ASCII string of 20, 22 or 24 chars
TryConvertToUuid64
bool TryConvertToUuid64(out Uuid64 value)
Converts this slice into a 64-bit UUID.
Returns: Uuid decoded from the Slice.
The slice can either be an 8-byte array, or an ASCII string of 16, 17 or 19 chars
TryConvertToUuid80
bool TryConvertToUuid80(out Uuid80 value)
Converts this slice into a 64-bit UUID.
Returns: Uuid decoded from the Slice.
The slice can either be an 10-byte array, or an ASCII string of 20, 22 or 24 chars
TryConvertToUuid96
bool TryConvertToUuid96(out Uuid96 value)
Converts this slice into a 64-bit UUID.
Returns: Uuid decoded from the Slice.
The slice can either be an 12-byte array, or an ASCII string of 24, 26 or 28 chars
TryCopyTo
bool TryCopyTo(Span<byte> destination)
Copy this slice into another buffer, if it is large enough.
bool TryCopyTo(Span<byte> destination, out int bytesWritten)
Copy this slice into another buffer, if it is large enough.
bool TryCopyTo(byte[] buffer, int offset)
Copy this slice into another buffer
buffer— Buffer where to copy this sliceoffset— Offset into the destination buffer
TryFormat
bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = null, IFormatProvider provider = null)
Tries to format the value of the current instance into the provided span of characters.
destination— The span in which to write this instance's value formatted as a span of characters.charsWritten— When this method returns, contains the number of characters that were written indestination.format— A span containing the characters that represent a standard or custom format string that defines the acceptable format fordestination.provider— An optional object that supplies culture-specific formatting information fordestination.
Returns: true if the formatting was successful; otherwise, false.
Unescape
static Slice Unescape(string value)
Decode the string that was generated by slice.ToString() or Slice.Dump(), back into the original slice
This may not be efficient, so it should only be use for testing/logging/troubleshooting
static Slice Unescape(ReadOnlySpan<char> value)
Decode the string that was generated by slice.ToString() or Slice.Dump(), back into the original slice
This may not be efficient, so it should only be use for testing/logging/troubleshooting
WriteTo
Span<byte> WriteTo(Span<byte> buffer)
Copy this slice into another buffer, and move the cursor
buffer— Buffer where to copy this slice
void WriteTo(ref SliceWriter writer)
Serializes the current instance to the specified output buffer
void WriteTo(byte[] buffer, ref int cursor)
Copy this slice into another buffer, and move the cursor
buffer— Buffer where to copy this slicecursor— Offset into the destination buffer
Zero
static Slice Zero(int count)
Create a slice filled with zeroes
count— Number of zeroes
Fields
Array
readonly byte[] Array
Pointer to the buffer (or null for Nil)
Count
readonly int Count
Number of bytes in the slice
Empty
static readonly Slice Empty
Empty slice ("segment of 0 bytes")
Nil
static readonly Slice Nil
Null slice ("no segment")
Offset
readonly int Offset
Offset of the first byte of the slice in the parent buffer