Here are the examples of the csharp api System.Diagnostics.Contracts.Contract.Requires(bool) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1195 Examples
19
Source : ServerCookieDecoder.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public ISet<ICookie> Decode(string header)
{
Contract.Requires(header != null);
int headerLen = header.Length;
if (headerLen == 0)
{
return ImmutableHashSet<ICookie>.Empty;
}
var cookies = new SortedSet<ICookie>();
int i = 0;
bool rfc2965Style = false;
if (CharUtil.RegionMatchesIgnoreCase(header, 0, RFC2965Version, 0, RFC2965Version.Count))
{
// RFC 2965 style cookie, move to after version value
i = header.IndexOf(';') + 1;
rfc2965Style = true;
}
// loop
for (;;)
{
// Skip spaces and separators.
for (;;)
{
if (i == headerLen)
{
goto loop;
}
char c = header[i];
if (c == '\t' || c == '\n' || c == 0x0b || c == '\f'
|| c == '\r' || c == ' ' || c == ',' || c == ';')
{
i++;
continue;
}
break;
}
int nameBegin = i;
int nameEnd;
int valueBegin;
int valueEnd;
for (;;)
{
char curChar = header[i];
if (curChar == ';')
{
// NAME; (no value till ';')
nameEnd = i;
valueBegin = valueEnd = -1;
break;
}
else if (curChar == '=')
{
// NAME=VALUE
nameEnd = i;
i++;
if (i == headerLen)
{
// NAME= (empty value, i.e. nothing after '=')
valueBegin = valueEnd = 0;
break;
}
valueBegin = i;
// NAME=VALUE;
int semiPos = header.IndexOf(';', i);
valueEnd = i = semiPos > 0 ? semiPos : headerLen;
break;
}
else
{
i++;
}
if (i == headerLen)
{
// NAME (no value till the end of string)
nameEnd = headerLen;
valueBegin = valueEnd = -1;
break;
}
}
if (rfc2965Style && (CharUtil.RegionMatches(header, nameBegin, RFC2965Path, 0, RFC2965Path.Count)
|| CharUtil.RegionMatches(header, nameBegin, RFC2965Domain, 0, RFC2965Domain.Count)
|| CharUtil.RegionMatches(header, nameBegin, RFC2965Port, 0, RFC2965Port.Count)))
{
// skip obsolete RFC2965 fields
continue;
}
DefaultCookie cookie = this.InitCookie(header, nameBegin, nameEnd, valueBegin, valueEnd);
if (cookie != null)
{
cookies.Add(cookie);
}
}
loop:
return cookies;
}
19
Source : ServerCookieEncoder.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public string Encode(ICookie cookie)
{
Contract.Requires(cookie != null);
string name = cookie.Name ?? nameof(cookie);
string value = cookie.Value ?? "";
this.ValidateCookie(name, value);
StringBuilder buf = StringBuilder();
if (cookie.Wrap)
{
AddQuoted(buf, name, value);
}
else
{
Add(buf, name, value);
}
if (cookie.MaxAge != long.MinValue)
{
Add(buf, (string)CookieHeaderNames.MaxAge, cookie.MaxAge);
DateTime expires = DateTime.UtcNow.AddMilliseconds(cookie.MaxAge * 1000);
buf.Append(CookieHeaderNames.Expires);
buf.Append((char)HttpConstants.EqualsSign);
DateFormatter.Append(expires, buf);
buf.Append((char)HttpConstants.Semicolon);
buf.Append((char)HttpConstants.HorizontalSpace);
}
if (cookie.Path != null)
{
Add(buf, (string)CookieHeaderNames.Path, cookie.Path);
}
if (cookie.Domain != null)
{
Add(buf, (string)CookieHeaderNames.Domain, cookie.Domain);
}
if (cookie.IsSecure)
{
Add(buf, (string)CookieHeaderNames.Secure);
}
if (cookie.IsHttpOnly)
{
Add(buf, (string)CookieHeaderNames.HttpOnly);
}
return StripTrailingSeparator(buf);
}
19
Source : ServerCookieEncoder.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public IList<string> Encode(ICollection<ICookie> cookies)
{
Contract.Requires(cookies != null);
if (cookies.Count == 0)
{
return ImmutableList<string>.Empty;
}
var encoded = new List<string>();
var nameToIndex = new Dictionary<string, int>();
bool hasDupdName = false;
int i = 0;
foreach (ICookie c in cookies)
{
encoded.Add(this.Encode(c));
if (nameToIndex.ContainsKey(c.Name))
{
nameToIndex[c.Name] = i;
hasDupdName = true;
}
else
{
nameToIndex.Add(c.Name, i);
}
i++;
}
return hasDupdName ? Dedup(encoded, nameToIndex) : encoded;
}
19
Source : CorsConfigBuilder.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public CorsConfigBuilder PreflightResponseHeader(AsciiString name, params object[] values)
{
Contract.Requires(values != null);
if (values.Length == 1)
{
this.preflightHeaders.Add(name, new ConstantValueGenerator(values[0]));
}
else
{
this.PreflightResponseHeader(name, new List<object>(values));
}
return this;
}
19
Source : AbstractDiskHttpData.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public override void SetContent(IByteBuffer buffer)
{
Contract.Requires(buffer != null);
try
{
this.Size = buffer.ReadableBytes;
this.CheckSize(this.Size);
if (this.DefinedSize > 0 && this.DefinedSize < this.Size)
{
throw new IOException($"Out of size: {this.Size} > {this.DefinedSize}");
}
if (this.fileStream == null)
{
this.fileStream = this.TempFile();
}
if (buffer.ReadableBytes == 0)
{
// empty file
return;
}
buffer.GetBytes(buffer.ReaderIndex, this.fileStream, buffer.ReadableBytes);
buffer.SetReaderIndex(buffer.ReaderIndex + buffer.ReadableBytes);
this.fileStream.Flush();
this.SetCompleted();
}
finally
{
// Release the buffer as it was retained before and we not need a reference to it at all
// See https://github.com/netty/netty/issues/1516
buffer.Release();
}
}
19
Source : AbstractDiskHttpData.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public override void SetContent(Stream source)
{
Contract.Requires(source != null);
if (this.fileStream != null)
{
this.Delete();
}
this.fileStream = this.TempFile();
int written = 0;
var bytes = new byte[4096 * 4];
while (true)
{
int read = source.Read(bytes, 0, bytes.Length);
if (read <= 0)
{
break;
}
written += read;
this.CheckSize(written);
this.fileStream.Write(bytes, 0, read);
}
this.fileStream.Flush();
// Reset the position to start for reads
this.fileStream.Position -= written;
this.Size = written;
if (this.DefinedSize > 0 && this.DefinedSize < this.Size)
{
try
{
Delete(this.fileStream);
}
catch (Exception error)
{
//Logger.Warn("Failed to delete: {} {}", this.fileStream, error);
}
this.fileStream = null;
throw new IOException($"Out of size: {this.Size} > {this.DefinedSize}");
}
//isRenamed = true;
this.SetCompleted();
}
19
Source : AbstractDiskHttpData.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public override bool RenameTo(FileStream destination)
{
Contract.Requires(destination != null);
if (this.fileStream == null)
{
throw new InvalidOperationException("No file defined so cannot be renamed");
}
// must copy
long chunkSize = 8196;
int position = 0;
while (position < this.Size)
{
if (chunkSize < this.Size - position)
{
chunkSize = this.Size - position;
}
var buffer = new byte[chunkSize];
int read = this.fileStream.Read(buffer, 0, (int)chunkSize);
if (read <= 0)
{
break;
}
destination.Write(buffer, 0, read);
position += read;
}
if (position == this.Size)
{
try
{
Delete(this.fileStream);
}
catch (IOException exception)
{
//Logger.Warn("Failed to delete file.", exception);
}
this.fileStream = destination;
return true;
}
else
{
try
{
Delete(destination);
}
catch (IOException exception)
{
//Logger.Warn("Failed to delete file.", exception);
}
return false;
}
}
19
Source : AbstractMemoryHttpData.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public override void SetContent(IByteBuffer buffer)
{
Contract.Requires(buffer != null);
long localsize = buffer.ReadableBytes;
this.CheckSize(localsize);
if (this.DefinedSize > 0 && this.DefinedSize < localsize)
{
throw new IOException($"Out of size: {localsize} > {this.DefinedSize}");
}
this.byteBuf?.Release();
this.byteBuf = buffer;
this.Size = localsize;
this.SetCompleted();
}
19
Source : AbstractMemoryHttpData.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public override void SetContent(Stream inputStream)
{
Contract.Requires(inputStream != null);
if (!inputStream.CanRead)
{
throw new ArgumentException($"{nameof(inputStream)} is not readable");
}
IByteBuffer buffer = Unpooled.Buffer();
var bytes = new byte[4096 * 4];
int written = 0;
while (true)
{
int read = inputStream.Read(bytes, 0, bytes.Length);
if (read <= 0)
{
break;
}
buffer.WriteBytes(bytes, 0, read);
written += read;
this.CheckSize(written);
}
this.Size = written;
if (this.DefinedSize > 0 && this.DefinedSize < this.Size)
{
throw new IOException($"Out of size: {this.Size} > {this.DefinedSize}");
}
this.byteBuf?.Release();
this.byteBuf = buffer;
this.SetCompleted();
}
19
Source : AbstractMemoryHttpData.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public override bool RenameTo(FileStream destination)
{
Contract.Requires(destination != null);
if (!destination.CanWrite)
{
throw new ArgumentException($"{nameof(destination)} is not writable");
}
if (this.byteBuf == null)
{
return true;
}
this.byteBuf.GetBytes(this.byteBuf.ReaderIndex, destination, this.byteBuf.ReadableBytes);
destination.Flush();
return true;
}
19
Source : WebSocketServerHandshaker.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public virtual Task CloseAsync(IChannel channel, CloseWebSocketFrame frame)
{
Contract.Requires(channel != null);
return channel.WriteAndFlushAsync(frame).ContinueWith((t, s) => ((IChannel)s).CloseAsync(),
channel, TaskContinuationOptions.ExecuteSynchronously);
}
19
Source : ProtobufDecoder.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
protected internal override void Decode(IChannelHandlerContext context, IByteBuffer message, List<object> output)
{
Contract.Requires(context != null);
Contract.Requires(message != null);
Contract.Requires(output != null);
int length = message.ReadableBytes;
if (length <= 0)
{
return;
}
Stream inputStream = null;
try
{
CodedInputStream codedInputStream;
if (message.IoBufferCount == 1)
{
ArraySegment<byte> bytes = message.GetIoBuffer(message.ReaderIndex, length);
codedInputStream = new CodedInputStream(bytes.Array, bytes.Offset, length);
}
else
{
inputStream = new ReadOnlyByteBufferStream(message, false);
codedInputStream = new CodedInputStream(inputStream);
}
//
// Note that we do not dispose the input stream because there is no input stream attached.
// Ideally, it should be disposed. BUT if it is disposed, a null reference exception is
// thrown because CodedInputStream flag leaveOpen is set to false for direct byte array reads,
// when it is disposed the input stream is null.
//
// In this case it is ok because the CodedInputStream does not own the byte data.
//
IMessage decoded = this.messageParser.ParseFrom(codedInputStream);
if (decoded != null)
{
output.Add(decoded);
}
}
catch (Exception exception)
{
throw new CodecException(exception);
}
finally
{
inputStream?.Dispose();
}
}
19
Source : ProtobufEncoder.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
protected internal override void Encode(IChannelHandlerContext context, IMessage message, List<object> output)
{
Contract.Requires(context != null);
Contract.Requires(message != null);
Contract.Requires(output != null);
IByteBuffer buffer = null;
try
{
int size = message.CalculateSize();
if (size == 0)
{
return;
}
//todo: Implement ByteBufferStream to avoid allocations.
buffer = Unpooled.WrappedBuffer(message.ToByteArray());
output.Add(buffer);
buffer = null;
}
catch (Exception exception)
{
throw new CodecException(exception);
}
finally
{
buffer?.Release();
}
}
19
Source : ByteToMessageDecoder.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public void Setreplacedulator(replacedulationFunc replacedulationFunc)
{
Contract.Requires(replacedulationFunc != null);
this.replacedulator = replacedulationFunc;
}
19
Source : MessageToByteEncoder.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
protected virtual IByteBuffer AllocateBuffer(IChannelHandlerContext context)
{
Contract.Requires(context != null);
return context.Allocator.Buffer();
}
19
Source : AbstractReferenceCounted.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public IReferenceCounted Retain(int increment)
{
Contract.Requires(increment > 0);
return this.RetainCore(increment);
}
19
Source : ArrayExtensions.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public static T[] Slice<T>(this T[] array, int length)
{
Contract.Requires(array != null);
if (length > array.Length)
{
throw new ArgumentOutOfRangeException(nameof(length), $"length({length}) cannot be longer than Array.length({array.Length})");
}
return Slice(array, 0, length);
}
19
Source : CharUtil.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public static int ParseInt(ICharSequence seq, int start, int end, int radix)
{
Contract.Requires(seq != null);
Contract.Requires(radix >= MinRadix && radix <= MaxRadix);
if (start == end)
{
throw new FormatException();
}
int i = start;
bool negative = seq[i] == '-';
if (negative && ++i == end)
{
throw new FormatException(seq.SubSequence(start, end).ToString());
}
return ParseInt(seq, i, end, radix, negative);
}
19
Source : CharUtil.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public static int ParseInt(ICharSequence seq, int start, int end, int radix, bool negative)
{
Contract.Requires(seq != null);
Contract.Requires(radix >= MinRadix && radix <= MaxRadix);
int max = int.MinValue / radix;
int result = 0;
int currOffset = start;
while (currOffset < end)
{
int digit = Digit((char)(seq[currOffset++] & 0xFF), radix);
if (digit == -1)
{
throw new FormatException(seq.SubSequence(start, end).ToString());
}
if (max > result)
{
throw new FormatException(seq.SubSequence(start, end).ToString());
}
int next = result * radix - digit;
if (next > result)
{
throw new FormatException(seq.SubSequence(start, end).ToString());
}
result = next;
}
if (!negative)
{
result = -result;
if (result < 0)
{
throw new FormatException(seq.SubSequence(start, end).ToString());
}
}
return result;
}
19
Source : CharUtil.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public static int CodePointAt(IReadOnlyList<char> seq, int index)
{
Contract.Requires(seq != null);
Contract.Requires(index >= 0 && index < seq.Count);
char high = seq[index++];
if (index >= seq.Count)
{
return high;
}
char low = seq[index];
return IsSurrogatePair(high, low) ? ToCodePoint(high, low) : high;
}
19
Source : DefaultAttributeMap.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public IAttribute<T> GetAttribute<T>(AttributeKey<T> key)
where T : clreplaced
{
Contract.Requires(key != null);
DefaultAttribute[] attrs = this.attributes;
if (attrs == null)
{
attrs = new DefaultAttribute[BucketSize];
// Not using ConcurrentHashMap due to high memory consumption.
attrs = Interlocked.CompareExchange(ref this.attributes, attrs, null) ?? attrs;
}
int i = Index(key);
DefaultAttribute head = Volatile.Read(ref attrs[i]);
if (head == null)
{
// No head exists yet which means we may be able to add the attribute without synchronization and just
// use compare and set. At worst we need to fallback to synchronization
head = new DefaultAttribute<T>(key);
if (Interlocked.CompareExchange(ref this.attributes[i], head, null) == null)
{
// we were able to add it so return the head right away
return (IAttribute<T>)head;
}
head = Volatile.Read(ref attrs[i]);
}
lock (head)
{
DefaultAttribute curr = head;
while (true)
{
if (!curr.Removed && curr.GetKey() == key)
{
return (IAttribute<T>)curr;
}
DefaultAttribute next = curr.Next;
if (next == null)
{
var attr = new DefaultAttribute<T>(head, key);
curr.Next = attr;
attr.Prev = curr;
return attr;
}
else
{
curr = next;
}
}
}
}
19
Source : DefaultAttributeMap.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public bool HasAttribute<T>(AttributeKey<T> key)
where T : clreplaced
{
Contract.Requires(key != null);
DefaultAttribute[] attrs = this.attributes;
if (attrs == null)
{
// no attribute exists
return false;
}
int i = Index(key);
DefaultAttribute head = Volatile.Read(ref attrs[i]);
if (head == null)
{
// No attribute exists which point to the bucket in which the head should be located
return false;
}
// check on the head can be done without synchronization
if (head.GetKey() == key && !head.Removed)
{
return true;
}
lock (head)
{
// we need to synchronize on the head
DefaultAttribute curr = head.Next;
while (curr != null)
{
if (!curr.Removed && curr.GetKey() == key)
{
return true;
}
curr = curr.Next;
}
return false;
}
}
19
Source : PriorityQueue.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public void Enqueue(T item)
{
Contract.Requires(item != null);
int oldCount = this.count;
if (oldCount == this.capacity)
{
this.GrowHeap();
}
this.count = oldCount + 1;
this.BubbleUp(oldCount, item);
}
19
Source : StringBuilderCharSequence.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public ICharSequence SubSequence(int start, int end)
{
Contract.Requires(start >= 0 && end >= start);
Contract.Requires(end <= this.Count);
return end == start
? new StringBuilderCharSequence()
: new StringBuilderCharSequence(this.builder, this.offset + start, end - start);
}
19
Source : StringBuilderCharSequence.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public string ToString(int start)
{
Contract.Requires(start >= 0 && start < this.Count);
return this.builder.ToString(this.offset + start, this.Count);
}
19
Source : StringUtil.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public static T ToHexString<T>(T dst, byte[] src, int offset, int length) where T : IAppendable
{
Contract.Requires(length >= 0);
if (length == 0)
{
return dst;
}
int end = offset + length;
int endMinusOne = end - 1;
int i;
// Skip preceding zeroes.
for (i = offset; i < endMinusOne; i++)
{
if (src[i] != 0)
{
break;
}
}
ByteToHexString(dst, src[i++]);
int remaining = end - i;
ToHexStringPadded(dst, src, i, remaining);
return dst;
}
19
Source : StringUtil.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public static ICharSequence EscapeCsv(ICharSequence value, bool trimWhiteSpace = false)
{
Contract.Requires(value != null);
int length = value.Count;
if (length == 0)
{
return value;
}
int start;
int last;
if (trimWhiteSpace)
{
start = IndexOfFirstNonOwsChar(value, length);
last = IndexOfLastNonOwsChar(value, start, length);
}
else
{
start = 0;
last = length - 1;
}
if (start > last)
{
return StringCharSequence.Empty;
}
int firstUnescapedSpecial = -1;
bool quoted = false;
if (IsDoubleQuote(value[start]))
{
quoted = IsDoubleQuote(value[last]) && last > start;
if (quoted)
{
start++;
last--;
}
else
{
firstUnescapedSpecial = start;
}
}
if (firstUnescapedSpecial < 0)
{
if (quoted)
{
for (int i = start; i <= last; i++)
{
if (IsDoubleQuote(value[i]))
{
if (i == last || !IsDoubleQuote(value[i + 1]))
{
firstUnescapedSpecial = i;
break;
}
i++;
}
}
}
else
{
for (int i = start; i <= last; i++)
{
char c = value[i];
if (c == LineFeed || c == CarriageReturn || c == Comma)
{
firstUnescapedSpecial = i;
break;
}
if (IsDoubleQuote(c))
{
if (i == last || !IsDoubleQuote(value[i + 1]))
{
firstUnescapedSpecial = i;
break;
}
i++;
}
}
}
if (firstUnescapedSpecial < 0)
{
// Special characters is not found or all of them already escaped.
// In the most cases returns a same string. New string will be instantiated (via StringBuilder)
// only if it really needed. It's important to prevent GC extra load.
return quoted ? value.SubSequence(start - 1, last + 2) : value.SubSequence(start, last + 1);
}
}
var result = new StringBuilderCharSequence(last - start + 1 + CsvNumberEscapeCharacters);
result.Append(DoubleQuote);
result.Append(value, start, firstUnescapedSpecial - start);
for (int i = firstUnescapedSpecial; i <= last; i++)
{
char c = value[i];
if (IsDoubleQuote(c))
{
result.Append(DoubleQuote);
if (i < last && IsDoubleQuote(value[i + 1]))
{
i++;
}
}
result.Append(c);
}
result.Append(DoubleQuote);
return result;
}
19
Source : ThreadDeathWatcher.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public static void Watch(Thread thread, Action task)
{
Contract.Requires(thread != null);
Contract.Requires(task != null);
Contract.Requires(thread.IsAlive);
Schedule(thread, task, true);
}
19
Source : TlsHandler.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
void Unwrap(IChannelHandlerContext ctx, IByteBuffer packet, int offset, int length, List<int> packetLengths, List<object> output)
{
Contract.Requires(packetLengths.Count > 0);
//bool notifyClosure = false; // todo: netty/issues/137
bool pending = false;
IByteBuffer outputBuffer = null;
try
{
ArraySegment<byte> inputIoBuffer = packet.GetIoBuffer(offset, length);
this.mediationStream.SetSource(inputIoBuffer.Array, inputIoBuffer.Offset);
int packetIndex = 0;
while (!this.EnsureAuthenticated())
{
this.mediationStream.ExpandSource(packetLengths[packetIndex]);
if (++packetIndex == packetLengths.Count)
{
return;
}
}
Task<int> currentReadFuture = this.pendingSslStreamReadFuture;
int outputBufferLength;
if (currentReadFuture != null)
{
// restoring context from previous read
Contract.replacedert(this.pendingSslStreamReadBuffer != null);
outputBuffer = this.pendingSslStreamReadBuffer;
outputBufferLength = outputBuffer.WritableBytes;
this.pendingSslStreamReadFuture = null;
this.pendingSslStreamReadBuffer = null;
}
else
{
outputBufferLength = 0;
}
// go through packets one by one (because SslStream does not consume more than 1 packet at a time)
for (; packetIndex < packetLengths.Count; packetIndex++)
{
int currentPacketLength = packetLengths[packetIndex];
this.mediationStream.ExpandSource(currentPacketLength);
if (currentReadFuture != null)
{
// there was a read pending already, so we make sure we completed that first
if (!currentReadFuture.IsCompleted)
{
// we did feed the whole current packet to SslStream yet it did not produce any result -> move to the next packet in input
continue;
}
int read = currentReadFuture.Result;
if (read == 0)
{
//Stream closed
return;
}
// Now output the result of previous read and decide whether to do an extra read on the same source or move forward
AddBufferToOutput(outputBuffer, read, output);
currentReadFuture = null;
outputBuffer = null;
if (this.mediationStream.SourceReadableBytes == 0)
{
// we just made a frame available for reading but there was already pending read so SslStream read it out to make further progress there
if (read < outputBufferLength)
{
// SslStream returned non-full buffer and there's no more input to go through ->
// typically it means SslStream is done reading current frame so we skip
continue;
}
// we've read out `read` bytes out of current packet to fulfil previously outstanding read
outputBufferLength = currentPacketLength - read;
if (outputBufferLength <= 0)
{
// after feeding to SslStream current frame it read out more bytes than current packet size
outputBufferLength = FallbackReadBufferSize;
}
}
else
{
// SslStream did not get to reading current frame so it completed previous read sync
// and the next read will likely read out the new frame
outputBufferLength = currentPacketLength;
}
}
else
{
// there was no pending read before so we estimate buffer of `currentPacketLength` bytes to be sufficient
outputBufferLength = currentPacketLength;
}
outputBuffer = ctx.Allocator.Buffer(outputBufferLength);
currentReadFuture = this.ReadFromSslStreamAsync(outputBuffer, outputBufferLength);
}
// read out the rest of SslStream's output (if any) at risk of going async
// using FallbackReadBufferSize - buffer size we're ok to have pinned with the SslStream until it's done reading
while (true)
{
if (currentReadFuture != null)
{
if (!currentReadFuture.IsCompleted)
{
break;
}
int read = currentReadFuture.Result;
AddBufferToOutput(outputBuffer, read, output);
}
outputBuffer = ctx.Allocator.Buffer(FallbackReadBufferSize);
currentReadFuture = this.ReadFromSslStreamAsync(outputBuffer, FallbackReadBufferSize);
}
pending = true;
this.pendingSslStreamReadBuffer = outputBuffer;
this.pendingSslStreamReadFuture = currentReadFuture;
}
catch (Exception ex)
{
this.HandleFailure(ex);
throw;
}
finally
{
this.mediationStream.ResetSource();
if (!pending && outputBuffer != null)
{
if (outputBuffer.IsReadable())
{
output.Add(outputBuffer);
}
else
{
outputBuffer.SafeRelease();
}
}
}
}
19
Source : AbstractBootstrap.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public virtual TBootstrap Group(IEventLoopGroup group)
{
Contract.Requires(group != null);
if (this.group != null)
{
throw new InvalidOperationException("group has already been set.");
}
this.group = group;
return (TBootstrap)this;
}
19
Source : AbstractBootstrap.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public TBootstrap ChannelFactory(Func<TChannel> channelFactory)
{
Contract.Requires(channelFactory != null);
this.channelFactory = channelFactory;
return (TBootstrap)this;
}
19
Source : AbstractBootstrap.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public TBootstrap Option<T>(ChannelOption<T> option, T value)
{
Contract.Requires(option != null);
if (value == null)
{
ChannelOptionValue removed;
this.options.TryRemove(option, out removed);
}
else
{
this.options[option] = new ChannelOptionValue<T>(option, value);
}
return (TBootstrap)this;
}
19
Source : AbstractBootstrap.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public TBootstrap Attribute<T>(AttributeKey<T> key, T value)
where T : clreplaced
{
Contract.Requires(key != null);
if (value == null)
{
AttributeValue removed;
this.attrs.TryRemove(key, out removed);
}
else
{
this.attrs[key] = new AttributeValue<T>(key, value);
}
return (TBootstrap)this;
}
19
Source : AbstractBootstrap.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public Task<IChannel> BindAsync(EndPoint localAddress)
{
this.Validate();
Contract.Requires(localAddress != null);
return this.DoBindAsync(localAddress);
}
19
Source : AbstractBootstrap.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public TBootstrap Handler(IChannelHandler handler)
{
Contract.Requires(handler != null);
this.handler = handler;
return (TBootstrap)this;
}
19
Source : AbstractChannelHandlerContext.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
internal static void InvokeExceptionCaught(AbstractChannelHandlerContext next, Exception cause)
{
Contract.Requires(cause != null);
IEventExecutor nextExecutor = next.Executor;
if (nextExecutor.InEventLoop)
{
next.InvokeExceptionCaught(cause);
}
else
{
try
{
nextExecutor.Execute((c, e) => ((AbstractChannelHandlerContext)c).InvokeExceptionCaught((Exception)e), next, cause);
}
catch (Exception t)
{
//if (DefaultChannelPipeline.//Logger.WarnEnabled)
//{
// DefaultChannelPipeline.//Logger.Warn("Failed to submit an ExceptionCaught() event.", t);
// DefaultChannelPipeline.//Logger.Warn("The ExceptionCaught() event that was failed to submit was:", cause);
//}
}
}
}
19
Source : AbstractChannelHandlerContext.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
internal static void InvokeUserEventTriggered(AbstractChannelHandlerContext next, object evt)
{
Contract.Requires(evt != null);
IEventExecutor nextExecutor = next.Executor;
if (nextExecutor.InEventLoop)
{
next.InvokeUserEventTriggered(evt);
}
else
{
nextExecutor.Execute(InvokeUserEventTriggeredAction, next, evt);
}
}
19
Source : AbstractChannelHandlerContext.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
internal static void InvokeChannelRead(AbstractChannelHandlerContext next, object msg)
{
Contract.Requires(msg != null);
object m = next.pipeline.Touch(msg, next);
IEventExecutor nextExecutor = next.Executor;
if (nextExecutor.InEventLoop)
{
next.InvokeChannelRead(m);
}
else
{
nextExecutor.Execute(InvokeChannelReadAction, next, msg);
}
}
19
Source : ChannelOutboundBuffer.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public void ForEachFlushedMessage(IMessageProcessor processor)
{
Contract.Requires(processor != null);
Entry entry = this.flushedEntry;
if (entry == null)
{
return;
}
do
{
if (!entry.Cancelled)
{
if (!processor.ProcessMessage(entry.Message))
{
return;
}
}
entry = entry.Next;
}
while (this.IsFlushedEntry(entry));
}
19
Source : DefaultChannelConfiguration.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public virtual T GetOption<T>(ChannelOption<T> option)
{
Contract.Requires(option != null);
if (ChannelOption.ConnectTimeout.Equals(option))
{
return (T)(object)this.ConnectTimeout; // no boxing will happen, compiler optimizes away such casts
}
if (ChannelOption.WriteSpinCount.Equals(option))
{
return (T)(object)this.WriteSpinCount;
}
if (ChannelOption.Allocator.Equals(option))
{
return (T)this.Allocator;
}
if (ChannelOption.RcvbufAllocator.Equals(option))
{
return (T)this.RecvByteBufAllocator;
}
if (ChannelOption.AutoRead.Equals(option))
{
return (T)(object)this.AutoRead;
}
if (ChannelOption.WriteBufferHighWaterMark.Equals(option))
{
return (T)(object)this.WriteBufferHighWaterMark;
}
if (ChannelOption.WriteBufferLowWaterMark.Equals(option))
{
return (T)(object)this.WriteBufferLowWaterMark;
}
if (ChannelOption.MessageSizeEstimator.Equals(option))
{
return (T)this.MessageSizeEstimator;
}
return default(T);
}
19
Source : DefaultChannelConfiguration.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
protected virtual void Validate<T>(ChannelOption<T> option, T value)
{
Contract.Requires(option != null);
option.Validate(value);
}
19
Source : HttpPostRequestEncoder.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public void SetBodyHttpDatas(List<IInterfaceHttpData> list)
{
Contract.Requires(list != null);
this.globalBodySize = 0;
this.bodyListDatas.Clear();
this.currentFileUpload = null;
this.duringMixedMode = false;
this.MultipartHttpDatas.Clear();
foreach (IInterfaceHttpData data in list)
{
this.AddBodyHttpData(data);
}
}
19
Source : HttpPostRequestEncoder.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public void AddBodyAttribute(string name, string value)
{
Contract.Requires(name != null);
IAttribute data = this.factory.CreateAttribute(this.request, name, value ?? StringUtil.EmptyString);
this.AddBodyHttpData(data);
}
19
Source : HttpPostRequestEncoder.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public void AddBodyFileUpload(string name, string fileName, FileStream fileStream, string contentType, bool isText)
{
Contract.Requires(name != null);
Contract.Requires(fileStream != null);
if (fileName == null)
{
fileName = StringUtil.EmptyString;
}
string scontentType = contentType;
string contentTransferEncoding = null;
if (contentType == null)
{
scontentType = isText
? HttpPostBodyUtil.DefaultTextContentType
: HttpPostBodyUtil.DefaultBinaryContentType;
}
if (!isText)
{
contentTransferEncoding = HttpPostBodyUtil.TransferEncodingMechanism.Binary.Value;
}
IFileUpload fileUpload = this.factory.CreateFileUpload(this.request, name, fileName, scontentType,
contentTransferEncoding, null, fileStream.Length);
try
{
fileUpload.SetContent(fileStream);
}
catch (IOException e)
{
throw new ErrorDataEncoderException(e);
}
this.AddBodyHttpData(fileUpload);
}
19
Source : HttpPostRequestEncoder.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public void AddBodyHttpData(IInterfaceHttpData data)
{
Contract.Requires(data != null);
if (this.headerFinalized)
{
throw new ErrorDataEncoderException("Cannot add value once finalized");
}
this.bodyListDatas.Add(data);
if (!this.isMultipart)
{
if (data is IAttribute dataAttribute)
{
try
{
// name=value& with encoded name and attribute
string key = this.EncodeAttribute(dataAttribute.Name, this.charset);
string value = this.EncodeAttribute(dataAttribute.Value, this.charset);
IAttribute newattribute = this.factory.CreateAttribute(this.request, key, value);
this.MultipartHttpDatas.Add(newattribute);
this.globalBodySize += newattribute.Name.Length + 1 + newattribute.Length + 1;
}
catch (IOException e)
{
throw new ErrorDataEncoderException(e);
}
}
else if (data is IFileUpload fileUpload)
{
// since not Multipart, only name=filename => Attribute
// name=filename& with encoded name and filename
string key = this.EncodeAttribute(fileUpload.Name, this.charset);
string value = this.EncodeAttribute(fileUpload.FileName, this.charset);
IAttribute newattribute = this.factory.CreateAttribute(this.request, key, value);
this.MultipartHttpDatas.Add(newattribute);
this.globalBodySize += newattribute.Name.Length + 1 + newattribute.Length + 1;
}
return;
}
// Logic:
// if not Attribute:
// add Data to body list
// if (duringMixedMode)
// add endmixedmultipart delimiter
// currentFileUpload = null
// duringMixedMode = false;
// add multipart delimiter, multipart body header and Data to multipart list
// reset currentFileUpload, duringMixedMode
// if FileUpload: take care of multiple file for one field => mixed mode
// if (duringMixedMode)
// if (currentFileUpload.name == data.name)
// add mixedmultipart delimiter, mixedmultipart body header and Data to multipart list
// else
// add endmixedmultipart delimiter, multipart body header and Data to multipart list
// currentFileUpload = data
// duringMixedMode = false;
// else
// if (currentFileUpload.name == data.name)
// change multipart body header of previous file into multipart list to
// mixedmultipart start, mixedmultipart body header
// add mixedmultipart delimiter, mixedmultipart body header and Data to multipart list
// duringMixedMode = true
// else
// add multipart delimiter, multipart body header and Data to multipart list
// currentFileUpload = data
// duringMixedMode = false;
// Do not add last delimiter! Could be:
// if duringmixedmode: endmixedmultipart + endmultipart
// else only endmultipart
//
if (data is IAttribute attribute)
{
InternalAttribute internalAttribute;
if (this.duringMixedMode)
{
internalAttribute = new InternalAttribute(this.charset);
internalAttribute.AddValue($"\r\n--{this.MultipartMixedBoundary}--");
this.MultipartHttpDatas.Add(internalAttribute);
this.MultipartMixedBoundary = null;
this.currentFileUpload = null;
this.duringMixedMode = false;
}
internalAttribute = new InternalAttribute(this.charset);
if (this.MultipartHttpDatas.Count > 0)
{
// previously a data field so CRLF
internalAttribute.AddValue("\r\n");
}
internalAttribute.AddValue($"--{this.MultipartDataBoundary}\r\n");
// content-disposition: form-data; name="field1"
internalAttribute.AddValue($"{HttpHeaderNames.ContentDisposition}: {HttpHeaderValues.FormData}; {HttpHeaderValues.Name}=\"{attribute.Name}\"\r\n");
// Add Content-Length: xxx
internalAttribute.AddValue($"{HttpHeaderNames.ContentLength}: {attribute.Length}\r\n");
Encoding localcharset = attribute.Charset;
if (localcharset != null)
{
// Content-Type: text/plain; charset=charset
internalAttribute.AddValue($"{HttpHeaderNames.ContentType}: {HttpPostBodyUtil.DefaultTextContentType}; {HttpHeaderValues.Charset}={localcharset.WebName}\r\n");
}
// CRLF between body header and data
internalAttribute.AddValue("\r\n");
this.MultipartHttpDatas.Add(internalAttribute);
this.MultipartHttpDatas.Add(data);
this.globalBodySize += attribute.Length + internalAttribute.Size;
}
else if (data is IFileUpload fileUpload)
{
var internalAttribute = new InternalAttribute(this.charset);
if (this.MultipartHttpDatas.Count > 0)
{
// previously a data field so CRLF
internalAttribute.AddValue("\r\n");
}
bool localMixed;
if (this.duringMixedMode)
{
if (this.currentFileUpload != null && this.currentFileUpload.Name.Equals(fileUpload.Name))
{
// continue a mixed mode
localMixed = true;
}
else
{
// end a mixed mode
// add endmixedmultipart delimiter, multipart body header
// and
// Data to multipart list
internalAttribute.AddValue($"--{this.MultipartMixedBoundary}--");
this.MultipartHttpDatas.Add(internalAttribute);
this.MultipartMixedBoundary = null;
// start a new one (could be replaced if mixed start again
// from here
internalAttribute = new InternalAttribute(this.charset);
internalAttribute.AddValue("\r\n");
localMixed = false;
// new currentFileUpload and no more in Mixed mode
this.currentFileUpload = fileUpload;
this.duringMixedMode = false;
}
}
else
{
if (this.encoderMode != EncoderMode.HTML5 && this.currentFileUpload != null
&& this.currentFileUpload.Name.Equals(fileUpload.Name))
{
// create a new mixed mode (from previous file)
// change multipart body header of previous file into
// multipart list to
// mixedmultipart start, mixedmultipart body header
// change Internal (size()-2 position in multipartHttpDatas)
// from (line starting with *)
// --AaB03x
// * Content-Disposition: form-data; name="files";
// filename="file1.txt"
// Content-Type: text/plain
// to (lines starting with *)
// --AaB03x
// * Content-Disposition: form-data; name="files"
// * Content-Type: multipart/mixed; boundary=BbC04y
// *
// * --BbC04y
// * Content-Disposition: attachment; filename="file1.txt"
// Content-Type: text/plain
this.InitMixedMultipart();
var pastAttribute = (InternalAttribute)this.MultipartHttpDatas[this.MultipartHttpDatas.Count - 2];
// remove past size
this.globalBodySize -= pastAttribute.Size;
StringBuilder replacement = new StringBuilder(
139 + this.MultipartDataBoundary.Length + this.MultipartMixedBoundary.Length * 2
+ fileUpload.FileName.Length + fileUpload.Name.Length)
.Append("--")
.Append(this.MultipartDataBoundary)
.Append("\r\n")
.Append(HttpHeaderNames.ContentDisposition)
.Append(": ")
.Append(HttpHeaderValues.FormData)
.Append("; ")
.Append(HttpHeaderValues.Name)
.Append("=\"")
.Append(fileUpload.Name)
.Append("\"\r\n")
.Append(HttpHeaderNames.ContentType)
.Append(": ")
.Append(HttpHeaderValues.MultipartMixed)
.Append("; ")
.Append(HttpHeaderValues.Boundary)
.Append('=')
.Append(this.MultipartMixedBoundary)
.Append("\r\n\r\n")
.Append("--")
.Append(this.MultipartMixedBoundary)
.Append("\r\n")
.Append(HttpHeaderNames.ContentDisposition)
.Append(": ")
.Append(HttpHeaderValues.Attachment);
if (fileUpload.FileName.Length > 0)
{
replacement.Append("; ")
.Append(HttpHeaderValues.FileName)
.Append("=\"")
.Append(fileUpload.FileName)
.Append('"');
}
replacement.Append("\r\n");
pastAttribute.SetValue(replacement.ToString(), 1);
pastAttribute.SetValue("", 2);
// update past size
this.globalBodySize += pastAttribute.Size;
// now continue
// add mixedmultipart delimiter, mixedmultipart body header
// and
// Data to multipart list
localMixed = true;
this.duringMixedMode = true;
}
else
{
// a simple new multipart
// add multipart delimiter, multipart body header and Data
// to multipart list
localMixed = false;
this.currentFileUpload = fileUpload;
this.duringMixedMode = false;
}
}
if (localMixed)
{
// add mixedmultipart delimiter, mixedmultipart body header and
// Data to multipart list
internalAttribute.AddValue($"--{this.MultipartMixedBoundary}\r\n");
if (fileUpload.FileName.Length == 0)
{
// Content-Disposition: attachment
internalAttribute.AddValue($"{HttpHeaderNames.ContentDisposition}: {HttpHeaderValues.Attachment}\r\n");
}
else
{
// Content-Disposition: attachment; filename="file1.txt"
internalAttribute.AddValue($"{HttpHeaderNames.ContentDisposition}: {HttpHeaderValues.Attachment}; {HttpHeaderValues.FileName}=\"{fileUpload.FileName}\"\r\n");
}
}
else
{
internalAttribute.AddValue($"--{this.MultipartDataBoundary}\r\n");
if (fileUpload.FileName.Length == 0)
{
// Content-Disposition: form-data; name="files";
internalAttribute.AddValue($"{HttpHeaderNames.ContentDisposition}: {HttpHeaderValues.FormData}; {HttpHeaderValues.Name}=\"{fileUpload.Name}\"\r\n");
}
else
{
// Content-Disposition: form-data; name="files";
// filename="file1.txt"
internalAttribute.AddValue($"{HttpHeaderNames.ContentDisposition}: {HttpHeaderValues.FormData}; {HttpHeaderValues.Name}=\"{fileUpload.Name}\"; {HttpHeaderValues.FileName}=\"{fileUpload.FileName}\"\r\n");
}
}
// Add Content-Length: xxx
internalAttribute.AddValue($"{HttpHeaderNames.ContentLength}: {fileUpload.Length}\r\n");
// Content-Type: image/gif
// Content-Type: text/plain; charset=ISO-8859-1
// Content-Transfer-Encoding: binary
internalAttribute.AddValue($"{HttpHeaderNames.ContentType}: {fileUpload.ContentType}");
string contentTransferEncoding = fileUpload.ContentTransferEncoding;
if (contentTransferEncoding != null
&& contentTransferEncoding.Equals(HttpPostBodyUtil.TransferEncodingMechanism.Binary.Value))
{
internalAttribute.AddValue($"\r\n{HttpHeaderNames.ContentTransferEncoding}: {HttpPostBodyUtil.TransferEncodingMechanism.Binary.Value}\r\n\r\n");
}
else if (fileUpload.Charset != null)
{
internalAttribute.AddValue($"; {HttpHeaderValues.Charset}={fileUpload.Charset.WebName}\r\n\r\n");
}
else
{
internalAttribute.AddValue("\r\n\r\n");
}
this.MultipartHttpDatas.Add(internalAttribute);
this.MultipartHttpDatas.Add(data);
this.globalBodySize += fileUpload.Length + internalAttribute.Size;
}
}
19
Source : InternalAttribute.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public void AddValue(string stringValue)
{
Contract.Requires(stringValue != null);
IByteBuffer buf = Unpooled.CopiedBuffer(this.charset.GetBytes(stringValue));
this.value.Add(buf);
this.size += buf.ReadableBytes;
}
19
Source : InternalAttribute.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public void AddValue(string stringValue, int rank)
{
Contract.Requires(stringValue != null);
IByteBuffer buf = Unpooled.CopiedBuffer(this.charset.GetBytes(stringValue));
this.value[rank] = buf;
this.size += buf.ReadableBytes;
}
19
Source : InternalAttribute.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public void SetValue(string stringValue, int rank)
{
Contract.Requires(stringValue != null);
IByteBuffer buf = Unpooled.CopiedBuffer(this.charset.GetBytes(stringValue));
IByteBuffer old = this.value[rank];
this.value[rank] = buf;
if (old != null)
{
this.size -= old.ReadableBytes;
old.Release();
}
this.size += buf.ReadableBytes;
}
19
Source : WebSocketClientHandshaker.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public Task CloseAsync(IChannel channel, CloseWebSocketFrame frame)
{
Contract.Requires(channel != null);
return channel.WriteAndFlushAsync(frame);
}
19
Source : DefaultHttpMessage.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public IHttpMessage SetProtocolVersion(HttpVersion value)
{
Contract.Requires(value != null);
this.version = value;
return this;
}
See More Examples