/// <summary> /// Creates new instance of <see cref="KeyBasedSerializer{TSerializationSink, TValue, TKey}"/>. /// </summary> /// <param name="serializers">The dictionary holding sub-serializers based on key.</param> /// <param name="extractKey">The callback to extract key from value.</param> public KeyBasedSerializer( IDictionary <TKey, SerializationFunctionality <TSerializationSink, TValue> > serializers, Func <TValue, TKey> extractKey ) { this._serializers = ArgumentValidator.ValidateNotNull("Serializers", serializers); this._extractKey = ArgumentValidator.ValidateNotNull("Extract key", extractKey); }
/// <summary> /// Creates a new instance of <see cref="InstanceUsage{TInstance}"/>. /// </summary> /// <param name="pool">The <see cref="LocklessInstancePoolForClasses{TInstance}"/>.</param> /// <param name="factory">The callback to create a new instance of <typeparamref name="TInstance"/>, if the pool currently does not have instances available.</param> /// <exception cref="ArgumentNullException">If either of <paramref name="pool"/> or <paramref name="factory"/> is <c>null</c>.</exception> /// <exception cref="ArgumentException">If <paramref name="factory"/> is used and it returns <c>null</c>.</exception> public InstanceUsage( LocklessInstancePoolForClasses <TInstance> pool, Func <TInstance> factory ) { this._pool = ArgumentValidator.ValidateNotNull(nameof(pool), pool); this.Instance = (pool.TakeInstance() ?? ArgumentValidator.ValidateNotNull(nameof(factory), factory)()) ?? throw new ArgumentException("instance"); }
/// <summary> /// Creates a new instance of <see cref="InstancePoolForContextlessCreation{TInstance}"/>. /// </summary> /// <param name="pool">The pool to wrap.</param> /// <param name="factory">The callback to use to create a new instance of type <typeparamref name="TInstance"/>.</param> /// <exception cref="ArgumentNullException">If either or <paramref name="pool"/> or <paramref name="factory"/> is <c>null</c>.</exception> public InstancePoolForContextlessCreation( LocklessInstancePoolForClasses <TInstance> pool, Func <TInstance> factory ) { this._pool = ArgumentValidator.ValidateNotNull(nameof(pool), pool); this._factory = ArgumentValidator.ValidateNotNull(nameof(factory), factory); }
/// <summary> /// Creates a new instance of <see cref="KeyBasedDeserializer{TDeserializationSource, TValue, TKey, TInnerDeserializationSource}"/> with given deserializer dictionary and key extraction callback. /// </summary> /// <param name="deserializers">The deserializer dictionary.</param> /// <param name="extractKey">The key extraction callback.</param> /// <exception cref="ArgumentNullException">If any of <paramref name="deserializers"/>, <paramref name="extractKey"/> is <c>null</c>.</exception> public KeyBasedDeserializer( IDictionary <TKey, DeserializationFunctionality <TInnerDeserializationSource, TValue> > deserializers, ExtractKeyCallback extractKey ) { this._deserializers = ArgumentValidator.ValidateNotNull("Serializers", deserializers); this._extractKey = ArgumentValidator.ValidateNotNull("Extract key", extractKey); }
/// <summary> /// Decodes given string into a byte array, starting at given offset in byte array, and reading up to given byte count. /// </summary> /// <param name="encoded">The encoded string.</param> /// <param name="bytes">The byte array to decode bytes to.</param> /// <param name="bytesStart">The offset in byte array to start decoding bytes to.</param> /// <param name="bytesCount">The maximum amount of bytes to decode.</param> /// <param name="unitSize">The amount of bits single character takes. This should be <c>6</c> for radix-64 encoding.</param> /// <param name="lookupTable">The lookup table for each byte. The integer value of characters in string is used as index to this array.</param> /// <returns>Amount of bytes read.</returns> public static Int32 DecodeBinary( this String encoded, Byte[] bytes, Int32 bytesStart, Int32 bytesCount, Int32 unitSize, Int32[] lookupTable ) { bytes.CheckArrayArguments(bytesStart, bytesCount); ArgumentValidator.ValidateNotNull("Encoded string", encoded); ArgumentValidator.ValidateNotNull("Lookup table", lookupTable); // Each iteration goes 1 character forward in string var sMax = encoded.Length; var byteMax = bytesStart + bytesCount; var bMax = byteMax * BYTE_SIZE; var bit = bytesStart * BYTE_SIZE; for (var strIdx = 0; strIdx < sMax && bit < bMax; ++strIdx, bit += unitSize) { var c = encoded[strIdx]; var value = lookupTable[(Int32)c]; if (value == -1) { throw new InvalidOperationException("Character \"" + c + "\" not found from lookup table."); } else { var startByte = bit / BYTE_SIZE; var endByte = (bit + unitSize - 1) / BYTE_SIZE; // How many MSB's to skip var skip = bit % BYTE_SIZE; if (startByte == endByte) { // Keep the MSB, shift value to left (in case e.g. unit size is 3 and MSB is 1) bytes[startByte] = (Byte)(bytes[startByte] | (value << (BYTE_SIZE - unitSize - skip))); } else { // Keep the existing MSB, and extract the MSB from the value // Amount of bits to use up in second byte skip = unitSize + skip - BYTE_SIZE; // Extract the MSB from value bytes[startByte] = (Byte)(bytes[startByte] | (value >> skip)); if (endByte < byteMax) { // Extract the LSB from the value bytes[endByte] = (Byte)(value << (BYTE_SIZE - skip)); } } } } return(bit / BYTE_SIZE); }
/// <summary> /// Creates new instance of <see cref="StreamCharacterWriterLogic"/> with given parameters. /// </summary> /// <param name="encoding">The <see cref="IEncodingInfo"/> that will be used to encode characters.</param> /// <param name="maxBufferSize">The maximum allowed buffer size that any <see cref="StreamWriterWithResizableBuffer"/> will be allowed to have.</param> public StreamCharacterWriterLogic( IEncodingInfo encoding, Int32 maxBufferSize ) { this._encoding = ArgumentValidator.ValidateNotNull(nameof(encoding), encoding); this._maxSingleCharSize = encoding.MaxCharByteCount; this._auxArray = new Char[2]; this._maxBufferSize = Math.Max(maxBufferSize, this._maxSingleCharSize); }
internal TransformablePotentiallyAsyncWriter( PotentiallyAsyncWriterLogic <TTransformed, TSink> writer, TSink sink, Func <TValue, TTransformed> transformer ) { this._writer = ArgumentValidator.ValidateNotNull(nameof(writer), writer); this._sink = sink; this._transformer = ArgumentValidator.ValidateNotNull(nameof(transformer), transformer); }
/// <summary> /// Encodes given byte array using given character array as a lookup array for each unit. /// </summary> /// <param name="bytes">The byte array to encode.</param> /// <param name="start">The index to start reading the array.</param> /// <param name="length">The amount of bytes to read from the array.</param> /// <param name="lookupTable">The mapping from encoding unit into its character representation. Should have (at least) one element.</param> /// <returns>String representing binary data encoded with <paramref name="lookupTable"/>.</returns> /// <exception cref="ArgumentException">If <paramref name="lookupTable"/> is <c>null</c> or empty, or if <paramref name="start"/> and <paramref name="length"/> would result in reading outside array bounds.</exception> /// <exception cref="ArgumentNullException">If <paramref name="bytes"/> or <paramref name="lookupTable"/> are <c>null</c>.</exception> /// <remarks> /// Currently no padding is used. /// The option to control emitting of padding is to be added in the future. /// The block size is based on the size of the lookup table, however up to 8 bits. /// So for example, in order to encode binary using radix-64 representation (e.g. base64), the lookup table should contain at least 64 and at most 127 elements. /// </remarks> public static String EncodeBinary( this Byte[] bytes, Int32 start, Int32 length, Char[] lookupTable ) { // <c>2^</c><paramref name="unitSize"/> elements.</param> // <param name="unitSize">The amount of bits of each encoding unit. For example, to encode in Base64, this should be set to <c>6</c>, as <c>2^6</c> is <c>64</c>.</param> // <exception cref="NotImplementedException">If <paramref name="unitSize"/> is more than <c>8</c>.</exception> bytes.CheckArrayArguments(start, length); ArgumentValidator.ValidateNotNull("Lookup table", lookupTable); var unitSize = CheckUnitSize(lookupTable.Length); // Compute amount of characters needed var chars = new Char[BinaryUtils.AmountOfPagesTaken((length - start) * BYTE_SIZE, unitSize)]; var bit = start * BYTE_SIZE; var max = start + length; for (var i = 0; i < chars.Length; ++i, bit += unitSize) { var startByte = bit / BYTE_SIZE; var endByte = (bit + unitSize - 1) / BYTE_SIZE; // How many MSB's to skip var msbSkip = bit % BYTE_SIZE; Int32 idx; if (startByte == endByte) { // Skip msbSkip MSB, extract next unitSize bits, and skip final 8 - unitsize - msbSkip bits var lsbSkip = BYTE_SIZE - unitSize - msbSkip; var mask = (ALL_ONES >> msbSkip) & (ALL_ONES << lsbSkip); idx = (bytes[startByte] & mask) >> lsbSkip; } else { // For first byte: skip msbSkip MSB, extract final bits // For next byte: extract unitsize - previous byte final bits size MSB var firstMask = ALL_ONES >> msbSkip; // Amount of bits in second byte var secondByteBits = (unitSize + msbSkip - BYTE_SIZE); idx = ((bytes[startByte] & firstMask) << secondByteBits); if (endByte < max) { var secondMask = (ALL_ONES << (BYTE_SIZE - secondByteBits)) & ALL_ONES; idx |= ((bytes[endByte] & secondMask) >> (BYTE_SIZE - secondByteBits)); } } chars[i] = lookupTable[idx]; } return(new String(chars)); }
public void RemoveAllAfter(UndoUnitNode node, Int32 newCount) { ArgumentValidator.ValidateNotNull("Node", node); // Remember that tail is head's prev. // Therefore we have to make 'node' as new tail // Don't perform other sanity checks as this is not a public api... this._head.Previous = node; node.Next = this._head; this._count = newCount; ++this._version; }
private static DeserializationDelegate CreateDelegate(ArrayDeserializationDelegate functionality) { ArgumentValidator.ValidateNotNull("Functionality", functionality); return((ArrayIndex <TArrayElement> source, out Int32 unitsProcessed, out Boolean success) => { var idx = source.Index; var originalIdx = idx; var retVal = functionality(source.Array, ref idx); unitsProcessed = idx - originalIdx; success = true; return retVal; }); }
/// <summary> /// This is helper method to generate lookup table for decoding strings, encoded with given look up table using various encoding methods (e.g. <see cref="EncodeBinary(Byte[], Int32, Int32, Char[])"/>, <see cref="EncodeBase64(Byte[], Boolean)"/>) in this class. /// </summary> /// <param name="encodeLookupTable">The table used to encode binary data.</param> /// <returns>The array with 256 elements, with character used as index giving the numerical value of it.</returns> /// <exception cref="IndexOutOfRangeException">If any character in <paramref name="encodeLookupTable"/> has its integer value 256 or greater.</exception> /// <exception cref="ArgumentNullException">If <paramref name="encodeLookupTable"/> is <c>null</c>.</exception> public static Int32[] CreateDecodeLookupTable(Char[] encodeLookupTable) { ArgumentValidator.ValidateNotNull("Encode lookup table", encodeLookupTable); var retVal = new Int32[Byte.MaxValue]; retVal.Fill(-1); for (var i = 0; i < encodeLookupTable.Length; ++i) { retVal[(Int32)encodeLookupTable[i]] = i; } return(retVal); }
/// <summary> /// Creates a new instance of <see cref="StringIndex"/> with given string and optional range. /// </summary> /// <param name="str">The string.</param> /// <param name="offset">The starting index.</param> /// <param name="count">The amount of characters to include to be indexed. Negative values are interpreted as "the rest starting from <paramref name="offset"/>.</param> /// <exception cref="ArgumentNullException">If <paramref name="str"/> is <c>null</c>.</exception> public StringIndex( String str, Int32 offset = 0, Int32 count = -1 ) { this.String = ArgumentValidator.ValidateNotNull(nameof(str), str); this._idx = Math.Max(offset, 0); if (count < 0) { count = str.Length - this._idx; } this._max = Math.Min(this._idx + count, str.Length); }
internal BoundMemorizingPotentiallyAsyncReader( PotentiallyAsyncReaderLogic <TValue, TSource> reader, TSource source, ResizableArray <TBufferItem> buffer, Func <TValue, TBufferItem> transform, Func <TBufferItem, TValue> transformBack ) { this.Reader = ArgumentValidator.ValidateNotNull(nameof(reader), reader); this.Source = source; this._buffer = buffer ?? new ResizableArray <TBufferItem>(); this._transform = ArgumentValidator.ValidateNotNull(nameof(transform), transform); this._transformBack = ArgumentValidator.ValidateNotNull(nameof(transformBack), transformBack); }
/// <summary> /// Creates a new instance of <see cref="ResizableArrayStream"/>. /// </summary> /// <param name="buffer">The <see cref="ResizableArray{T}"/> instance.</param> /// <param name="readable">Whether this stream is readable.</param> /// <param name="writeable">Whether this stream is writeable.</param> /// <param name="position">The initial position within <paramref name="buffer"/> to start reading/writing.</param> /// <param name="maxLength">The maximum amount of bytes that can be read or written to this stream.</param> /// <exception cref="ArgumentNullException">If <paramref name="buffer"/> is <c>null</c>.</exception> public ResizableArrayStream( ResizableArray <Byte> buffer, Boolean readable = true, Boolean writeable = true, Int32 position = 0, Int32 maxLength = 0 ) { this._buffer = ArgumentValidator.ValidateNotNull(nameof(buffer), buffer); this._readable = readable; this._writeable = writeable; this._position = this._origin = position; this._maxLength = maxLength; }
/// <summary> /// Tries to read next character from given <paramref name="stream"/>. /// </summary> /// <param name="stream">The <see cref="StreamReaderWithResizableBuffer"/> to read character from. The <see cref="StreamReaderWithResizableBuffer.TryReadMoreAsync(int)"/> method will be used.</param> /// <param name="charChecker">Optional callback to check character. If it is supplied, this method will keep reading characters until this callback returns <c>true</c>.</param> /// <returns>A task which will return character read, or <c>null</c> if no more characters could be read from <paramref name="stream"/>.</returns> /// <exception cref="ArgumentNullException">If <paramref name="stream"/> is <c>null</c>.</exception> /// <exception cref="InvalidOperationException">If this reader is currently busy with another read operation.</exception> public async ValueTask <Char?> TryReadNextCharacterAsync( StreamReaderWithResizableBuffer stream, Func <Char, Boolean> charChecker = null // If false -> will read next character ) { ArgumentValidator.ValidateNotNull(nameof(stream), stream); if (Interlocked.CompareExchange(ref this._state, BUSY, IDLE) == IDLE) { try { Boolean charReadSuccessful; var encoding = this.Encoding.Encoding; var auxArray = this._chars; var minChar = this._minChar; do { var arrayIndex = stream.ReadBytesCount; charReadSuccessful = await stream.TryReadMoreAsync(minChar); if (charReadSuccessful) { var charCount = 1; while (charCount == 1 && await stream.TryReadMoreAsync(minChar)) { charCount = encoding.GetCharCount(stream.Buffer, arrayIndex, stream.ReadBytesCount - arrayIndex); } if (charCount > 1) { // Unread peeked byte stream.UnreadBytes(minChar); } encoding.GetChars(stream.Buffer, arrayIndex, stream.ReadBytesCount - arrayIndex, auxArray, 0); } } while (charReadSuccessful && !(charChecker?.Invoke(auxArray[0]) ?? true)); return(charReadSuccessful ? auxArray[0] : (Char?)null); } finally { Interlocked.Exchange(ref this._state, IDLE); } } else { throw BusyException(); } }
/// <inheritdoc /> public IEncodingInfo WriteASCIIByte(Byte[] array, ref Int32 idx, Byte asciiByte) { // UTF8 ASCII bytes are just normal bytes ArgumentValidator.ValidateNotNull(nameof(array), array)[idx++] = asciiByte; return(this); }
/// <inheritdoc /> public Byte ReadASCIIByte(Byte[] array, ref Int32 idx) { // UTF8 ASCII bytes are just normal bytes return(ArgumentValidator.ValidateNotNull(nameof(array), array)[idx++]); }
public AwaiterByWrapper(Semaphore semaphore) { this._semaphore = ArgumentValidator.ValidateNotNull(nameof(semaphore), semaphore); }
internal UndoUnitEnumerable(UndoUnitBuffer <T> buffer, Boolean isUndo) { ArgumentValidator.ValidateNotNull("Buffer", buffer); this._buffer = buffer; this._isUndo = isUndo; }
internal UTF16EncodingInfo(UnicodeEncoding encoding) { this.Encoding = ArgumentValidator.ValidateNotNull(nameof(encoding), encoding); }
/// <summary> /// Creates a new instance of <see cref="ResizableArrayIndex{TElement}"/> with given <see cref="ResizableArray{T}"/> and index. /// </summary> /// <param name="array">The <see cref="ResizableArray{T}"/>.</param> /// <param name="index">The index within <see cref="ResizableArray{T}"/>.</param> /// <exception cref="ArgumentNullException">If <paramref name="array"/> is <c>null</c>.</exception> public ResizableArrayIndex(ResizableArray <TElement> array, Int32 index) { this.Array = ArgumentValidator.ValidateNotNull("Array", array); this.Index = index; }
internal ComparerWithFunction(Comparison <T> compareFunc) { ArgumentValidator.ValidateNotNull("Comparer function", compareFunc); this._compareFunc = compareFunc; }
/// <inheritdoc /> public ValueTask <Char?> TryReadNextAsync(StringIndex source) { ArgumentValidator.ValidateNotNull(nameof(source), source); return(new ValueTask <Char?>(source.TryGetNextIndex(out Int32 idx) ? source.String[idx] : (Char?)null)); }
/// <summary> /// Creates a new instance of <see cref="EqualityComparerWrapper{T}"/> with given comparer to delegate comparison to. /// </summary> /// <param name="comparer">The actual equality comparer.</param> /// <exception cref="ArgumentNullException">If <paramref name="comparer"/> is <c>null</c>.</exception> public EqualityComparerWrapper(IEqualityComparer <TValue> comparer) { ArgumentValidator.ValidateNotNull("Equality comparer", comparer); this._comparer = comparer; }
/// <summary> /// Creates a new instance of <see cref="ResizableArrayIndex{TElement}"/> with given array and index. /// </summary> /// <param name="array">The array.</param> /// <param name="index">The index within the array.</param> /// <exception cref="ArgumentNullException">If <paramref name="array"/> is <c>null</c>.</exception> public ArrayIndex(TElement[] array, Int32 index) { this.Array = ArgumentValidator.ValidateNotNull("Array", array); this.Index = index; }
/// <summary> /// Creates a new instance of <see cref="ComparerWrapper{T}"/> with given comparer to delegate comparison to. /// </summary> /// <param name="comparer">The actual comparer.</param> /// <exception cref="ArgumentNullException">If <paramref name="comparer"/> is <c>null</c>.</exception> public ComparerWrapper(IComparer <TValue> comparer) { ArgumentValidator.ValidateNotNull("Comparer", comparer); this._comparer = comparer; }
/// <summary> /// Tries to read next character from given <paramref name="stream"/>. /// </summary> /// <param name="stream">The <see cref="StreamReaderWithResizableBuffer"/> to read character from. The <see cref="StreamReaderWithResizableBuffer.TryReadMoreAsync(int)"/> method will be used.</param> /// <returns>A task which will return character read, or <c>null</c> if no more characters could be read from <paramref name="stream"/>.</returns> /// <exception cref="ArgumentNullException">If <paramref name="stream"/> is <c>null</c>.</exception> /// <exception cref="InvalidOperationException">If this reader is currently busy with another read operation.</exception> public async ValueTask <Char?> TryReadNextAsync( StreamReaderWithResizableBuffer stream ) { ArgumentValidator.ValidateNotNull(nameof(stream), stream); if (Interlocked.CompareExchange(ref this._state, BUSY, IDLE) == IDLE) { try { Char? retVal; Boolean charReadSuccessful; if (this._lowSurrogate != 0) { // We have read surrogate pair previously -> return low surrogate retVal = (Char)this._lowSurrogate; charReadSuccessful = true; Interlocked.Exchange(ref this._lowSurrogate, 0); } else { var decoder = this.Encoding.Encoding.GetDecoder(); var auxArray = this._chars; var minChar = this._minChar; var arrayIndex = stream.ReadBytesCount; charReadSuccessful = await stream.TryReadMoreAsync(minChar); if (charReadSuccessful) { Int32 charCount = 0; Boolean completed; do { decoder.Convert(stream.Buffer, arrayIndex, stream.ReadBytesCount - arrayIndex, auxArray, 0, 2, true, out Int32 bytesUsed, out charCount, out completed); } while ((charCount < 2 || !completed) && await stream.TryReadMoreAsync(minChar)); if (charCount > 1) { // Check for surrogate pair if (Char.IsHighSurrogate(auxArray[0])) { Interlocked.Exchange(ref this._lowSurrogate, (Int32)auxArray[1]); } else { // Unread peeked byte stream.UnreadBytes(minChar); } } } retVal = charReadSuccessful ? auxArray[0] : (Char?)null; } return(retVal); } finally { Interlocked.Exchange(ref this._state, IDLE); } } else { throw BusyException(); } }
/// <summary> /// Creates a new instance of <see cref="DeserializationFunctionalityWrapper{TDeserializationSource, TValue}"/> with given callback which should perform the deserialization. /// </summary> /// <param name="functionality">The callback to perform deserialization.</param> /// <exception cref="ArgumentNullException">If <paramref name="functionality"/> is <c>null</c>.</exception> public DeserializationFunctionalityWrapper(DeserializationDelegate functionality) { this._delegate = ArgumentValidator.ValidateNotNull("Functionality delegate", functionality); }
internal ComparerWithFunctionAndNullStrategy(Comparison <T> compareFunc, NullSorting nullSorting) { ArgumentValidator.ValidateNotNull("Comparer function", compareFunc); this._compareFunc = compareFunc; this._nullSorting = nullSorting; }
/// <summary> /// Creates a new instance of <see cref="LazyDisposable{T}"/> with given <see cref="Lazy{T}"/> containing the lazily initialized <see cref="IDisposable"/> resource. /// </summary> /// <param name="lazy">The <see cref="Lazy{T}"/> containing the lazily initialized <see cref="IDisposable"/> resource.</param> /// <exception cref="ArgumentNullException">If <paramref name="lazy"/> is <c>null</c>.</exception> public LazyDisposable(Lazy <T> lazy) { this._lazy = ArgumentValidator.ValidateNotNull(nameof(lazy), lazy); }