/// <summary> /// Copies the data of the specified managed <see cref="Object"/> into the unmanaged memory /// block at the specified offset.</summary> /// <param name="structure"> /// The <see cref="Object"/> containing the data to store at <paramref name="offset"/>. /// </param> /// <param name="offset"> /// The offset from the unmanaged memory handle, in bytes, at which copying begins.</param> /// <param name="delete"> /// <c>true</c> to have the <see cref="Marshal.DestroyStructure"/> method called on the /// unmanaged memory at <paramref name="offset"/> before copying begins. Note that passing /// <c>false</c> can lead to a memory leak.</param> /// <exception cref="ArgumentNullException"> /// <paramref name="structure"/> is a null reference.</exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="offset"/> is less than zero.</exception> /// <exception cref="PropertyValueException"> /// <see cref="SafeHandle.IsInvalid"/> is <c>true</c>.</exception> /// <remarks><para> /// <b>SetMemory</b> calls <see cref="Marshal.StructureToPtr"/> to copy the data of the /// specified <paramref name="structure"/>, which must be an instance of a formatted class, /// into the unmanaged memory block at the specified <paramref name="offset"/>. /// </para><note type="caution"> /// The specified <paramref name="offset"/> is <b>not</b> checked against the (unknown) size /// of the unmanaged memory block. Buffer overruns are possible!</note></remarks> public unsafe void SetMemory(object structure, int offset, bool delete) { if (IsInvalid) { ThrowHelper.ThrowPropertyValueException("IsInvalid", Strings.PropertyTrue); } if (structure == null) { ThrowHelper.ThrowArgumentNullException("structure"); } if (offset < 0) { ThrowHelper.ThrowArgumentOutOfRangeException( "offset", offset, Strings.ArgumentNegative); } Marshal.StructureToPtr(structure, (IntPtr)((byte *)handle + offset), delete); }
public override unsafe int GetChars(byte *bytes, int byteCount, char *chars, int charCount) { // Validate Parameters if (bytes is null || chars is null) { ThrowHelper.ThrowArgumentNullException( argument: (bytes is null) ? ExceptionArgument.bytes : ExceptionArgument.chars, resource: ExceptionResource.ArgumentNull_Array); } if ((byteCount | charCount) < 0) { ThrowHelper.ThrowArgumentOutOfRangeException( argument: (byteCount < 0) ? ExceptionArgument.byteCount : ExceptionArgument.charCount, resource: ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } return(GetCharsCommon(bytes, byteCount, chars, charCount)); }
public void QueueWriteStream(byte[] array, int offset, int count, Action <StreamHandle, Exception> completion) { if (array is null || 0u >= (uint)array.Length) { return; } if ((uint)count > SharedConstants.TooBigOrNegative) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count); } if ((uint)(offset + count) > (uint)array.Length) { ThrowHelper.ThrowArgumentException_InvalidOffLen(); } IByteBuffer buffer = Unpooled.WrappedBuffer(array, offset, count); _pipeline.QueueWrite(buffer, completion); }
public static void WriteMachineEndian <T>(Span <byte> buffer, ref T value) where T : struct { #if netstandard if (SpanHelpers.IsReferenceOrContainsReferences <T>()) { ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T)); } #else if (RuntimeHelpers.IsReferenceOrContainsReferences <T>()) { ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T)); } #endif if ((uint)Unsafe.SizeOf <T>() > (uint)buffer.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length); } Unsafe.WriteUnaligned <T>(ref buffer.DangerousGetPinnableReference(), value); }
public static T ReadMachineEndian <T>(ReadOnlySpan <byte> buffer) where T : struct { #if netstandard if (SpanHelpers.IsReferenceOrContainsReferences <T>()) { ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T)); } #else if (RuntimeHelpers.IsReferenceOrContainsReferences <T>()) { ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T)); } #endif if (Unsafe.SizeOf <T>() > buffer.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length); } return(Unsafe.ReadUnaligned <T>(ref MemoryMarshal.GetReference(buffer))); }
/// <summary> /// Copies the unmanaged memory block at the specified offset to a managed <see /// cref="Object"/> of the specified type.</summary> /// <param name="offset"> /// The offset from the unmanaged memory handle, in bytes, at which copying begins.</param> /// <param name="type"> /// The <see cref="Type"/> of the newly allocated <see cref="Object"/> that receives the /// data at <paramref name="offset"/>.</param> /// <returns> /// A new <see cref="Object"/> of the specified <paramref name="type"/> containing the data /// at <paramref name="offset"/>.</returns> /// <exception cref="ArgumentNullException"> /// <paramref name="type"/> is a null reference.</exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="offset"/> is less than zero.</exception> /// <exception cref="PropertyValueException"> /// <see cref="SafeHandle.IsInvalid"/> is <c>true</c>.</exception> /// <remarks><para> /// <b>GetMemory</b> calls <see cref="Marshal.PtrToStructure"/> to copy the data at the /// specified <paramref name="offset"/> within the unmanaged memory block into a new /// instance the specified <paramref name="type"/> which must represent a formatted class. /// </para><note type="caution"> /// The specified <paramref name="offset"/> is <b>not</b> checked against the (unknown) size /// of the unmanaged memory block. Buffer overruns are possible!</note></remarks> public unsafe object GetMemory(int offset, Type type) { if (IsInvalid) { ThrowHelper.ThrowPropertyValueException("IsInvalid", Strings.PropertyTrue); } if (offset < 0) { ThrowHelper.ThrowArgumentOutOfRangeException( "offset", offset, Strings.ArgumentNegative); } if (type == null) { ThrowHelper.ThrowArgumentNullException("type"); } return(Marshal.PtrToStructure((IntPtr)((byte *)handle + offset), type)); }
/// <summary> /// Initializes a new instance of the <see cref="SocketOpenResponseMessage"/> class. /// </summary> /// <param name="senderId">The sender id.</param> /// <param name="targetId">The target id.</param> /// <param name="senderPort">The sender port.</param> /// <param name="targetPort">The target port.</param> /// <param name="senderSocketId">The sender socket id.</param> /// <param name="targetSocketId">The target socket id.</param> public SocketOpenResponseMessage(string senderId, string targetId, int senderPort, int targetPort, long senderSocketId, long targetSocketId) : base(senderId, targetId, MessageCodeEnum.SocketOpenResponse, MessageTypeEnum.Tcp, senderPort, targetPort, senderSocketId, targetSocketId) { if (string.IsNullOrEmpty(targetId)) { ThrowHelper.ThrowArgumentNullException("targetId"); } if (senderPort != -1) { AddressEndPoint.ValidateTcpPort(senderPort); } AddressEndPoint.ValidateTcpPort(targetPort); if (senderSocketId < 1 && senderSocketId != -1) { ThrowHelper.ThrowArgumentOutOfRangeException("senderSocketId"); } if (targetSocketId < 1) { ThrowHelper.ThrowArgumentOutOfRangeException("targetSocketId"); } }
// Sorts the elements in a section of this list. The sort compares the // elements to each other using the given IComparer interface. If // comparer is null, the elements are compared to each other using // the IComparable interface, which in that case must be implemented by all // elements of the list. // // This method uses the Array.Sort method to sort the elements. // public void Sort(int index, int count, IComparer <T> comparer) { if (index < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (_size - index < count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_InvalidOffLen); } Contract.EndContractBlock(); Array.Sort <T>(_items, index, count, comparer); _version++; }
public MappingItem <TSelectedItem> this[int index] { #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif get { return(items[index]); } set { if (items.IsReadOnly) { throw new NotSupportedException("Insert is not supported for readonly source."); } if (index < 0 || index >= items.Count) { ThrowHelper.ThrowArgumentOutOfRangeException(); } SetItem(index, value); } }
public Dictionary(int capacity, IEqualityComparer <TKey> comparer) { if (capacity < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity); } if (capacity > 0) { Initialize(capacity); } if (comparer != EqualityComparer <TKey> .Default) { _comparer = comparer; } if (typeof(TKey) == typeof(string) && _comparer == null) { // To start, move off default comparer for string which is randomised _comparer = (IEqualityComparer <TKey>)NonRandomizedStringEqualityComparer.Default; } }
internal LagStepImpl(TCursor cursor, int width = 1, int step = 1, bool allowIncomplete = false) : this() { if (width <= 0) { ThrowHelper.ThrowArgumentOutOfRangeException(nameof(width)); } if (step <= 0) { ThrowHelper.ThrowArgumentOutOfRangeException(nameof(step)); } if (allowIncomplete && _step > 1) { ThrowHelper.ThrowNotImplementedException("TODO incomplete with step is not implemented"); } _cursor = cursor; _width = width; _step = step; _allowIncomplete = allowIncomplete; }
public static unsafe IntPtr StringToHGlobalAnsi(string?s) { if (s is null) { return(IntPtr.Zero); } long lnb = (s.Length + 1) * (long)SystemMaxDBCSCharSize; int nb = (int)lnb; // Overflow checking if (nb != lnb) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.s); } IntPtr ptr = AllocHGlobal((IntPtr)nb); StringToAnsiString(s, (byte *)ptr, nb); return(ptr); }
private void AddRange(int index, IEnumerable <TItem> c) { if (index < 0 || index > size) { ThrowHelper.ThrowArgumentOutOfRangeException(string.Format("Index: {0}, Size: {1}", index.ToString(), size.ToString())); } int cSize = 0; CheckForComodification(); IEnumerator <TItem> e = c.GetEnumerator(); while (e.MoveNext()) { list.Insert(offset + index + cSize, e.Current); cSize++; } expectedModCount = list.Version; size += cSize; this.mVersion++; }
/// <summary>Sets the length of this stream to the given value.</summary> /// <param name="value">The new length of the stream.</param> public override void SetLength(long value) { if (value < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (_strategy.IsClosed) { ThrowHelper.ThrowObjectDisposedException_FileClosed(); } if (!CanSeek) { ThrowHelper.ThrowNotSupportedException_UnseekableStream(); } if (!CanWrite) { ThrowHelper.ThrowNotSupportedException_UnwritableStream(); } _strategy.SetLength(value); }
/// <summary> /// Gets or sets the <see cref="byte" /> at the specified index. /// </summary> /// <param name="index">The index.</param> /// <returns><see cref="byte" />.</returns> public byte this[int index] { get { if (index < 0 || index >= Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } return(Bytes[Offset + index]); } set { if (index < 0 || index >= Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } Bytes[Offset + index] = value; } }
/// <summary> /// Initializes a new instance of the <see cref="ChangeTurn"/> class with the specified /// initial turn index and caption text.</summary> /// <param name="turn"> /// The initial value for the <see cref="Turn"/> property. This is also the maximum turn /// index that will be accepted.</param> /// <param name="caption"> /// The text to display in the title bar of the dialog.</param> /// <exception cref="ArgumentNullOrEmptyException"> /// <paramref name="caption"/> is a null reference or an empty string.</exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="turn"/> is less than zero.</exception> public ChangeTurn(int turn, string caption) { if (turn < 0) { ThrowHelper.ThrowArgumentOutOfRangeException( "turn", turn, Tektosyne.Strings.ArgumentNegative); } if (String.IsNullOrEmpty(caption)) { ThrowHelper.ThrowArgumentNullOrEmptyException("caption"); } InitializeComponent(); Title = caption; // set focus on turn index TurnUpDown.Maximum = turn + 1; TurnUpDown.Value = turn + 1; TurnUpDown.Select(); }
public override int GetCharCount(byte[] bytes, int index, int count) { // Validate input parameters if (bytes is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.bytes, ExceptionResource.ArgumentNull_Array); } if ((index | count) < 0) { ThrowHelper.ThrowArgumentOutOfRangeException((index < 0) ? ExceptionArgument.index : ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (bytes.Length - index < count) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.bytes, ExceptionResource.ArgumentOutOfRange_IndexCountBuffer); } return(count); }
/// <summary> /// Finds all <see cref="Graph"/> nodes that the specified agent can reach from the /// specified node with the specified maximum path cost.</summary> /// <param name="agent"> /// The <see cref="IGraphAgent{T}"/> that performs the movement.</param> /// <param name="source"> /// The source node within <see cref="Graph"/> where the movement starts.</param> /// <param name="maxCost"> /// The maximum total cost of the best path from the specified <paramref name="source"/> to /// any reachable <see cref="Graph"/> node.</param> /// <returns> /// <c>true</c> if one or more <see cref="Graph"/> nodes could be reached from the specified /// <paramref name="source"/>; otherwise, <c>false</c>.</returns> /// <exception cref="ArgumentNullException"> /// <paramref name="agent"/> or <paramref name="source"/> is a null reference.</exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="maxCost"/> is zero or negative.</exception> /// <remarks><para> /// <b>FindReachable</b> returns <c>false</c> if the specified <paramref name="source"/> /// node is invalid, or if there are no reachable nodes whose total path cost is equal to or /// less than the specified <paramref name="maxCost"/>. /// </para><para> /// Otherwise, <b>FindReachable</b> returns <c>true</c> and sets the <see cref="Nodes"/> /// property to the result of the path search. This collection contains only those reachable /// nodes for which <see cref="IGraphAgent{T}.CanOccupy"/> has succeeded. /// </para><para> /// If <see cref="IGraphAgent{T}.RelaxedRange"/> is <c>true</c> for the specified <paramref /// name="agent"/>, the <b>Nodes</b> collection includes those nodes whose total path cost /// exceeds <paramref name="maxCost"/>, but which can be reached from a neighbor whose total /// path cost is less than (but not equal to) <paramref name="maxCost"/>. These nodes are /// considered reachable regardless of their actual step costs.</para></remarks> public bool FindReachable(IGraphAgent <T> agent, T source, double maxCost) { if (agent == null) { ThrowHelper.ThrowArgumentNullException("agent"); } if (source == null) { ThrowHelper.ThrowArgumentNullException("source"); } if (maxCost <= 0) { ThrowHelper.ThrowArgumentOutOfRangeException( "maxCost", maxCost, Strings.ArgumentNotPositive); } _agent = agent; _maxCost = maxCost; // clear previous results _nodes.Clear(); // fail if source node is invalid if (!Graph.Contains(source)) { return(false); } // mark source node as visited _pathCosts.Add(source, -1); // expand coverage to maxCost ExpandArea(source, 0); // clear intermediate data _pathCosts.Clear(); // succeed if any nodes reached return(_nodes.Count > 0); }
private static int FindLastIndex <TSource>([NotNull] this ICollection <TSource> source, int startIndex, int count, Func <TSource, bool> predicate) { if (predicate == null) { ThrowHelper.ThrowArgumentNullException(nameof(predicate)); } if (source.Count == 0) { if (startIndex != -1) { ThrowHelper.ThrowArgumentOutOfRangeException(nameof(startIndex)); } } else { if ((uint)startIndex >= (uint)source.Count) { ThrowHelper.ThrowArgumentOutOfRangeException(nameof(startIndex)); } } if (count < 0 || startIndex - source.Count + 1 < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(nameof(count)); } var endIndex = startIndex - count; for (var i = startIndex; i > endIndex; i--) { if (predicate(source.ElementAt(i))) { return(i); } } return(-1); }
// Returns the number of characters produced by decoding a range of bytes // in a byte array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetCharCount(byte[] bytes, int index, int count) { if (bytes is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.bytes, ExceptionResource.ArgumentNull_Array); } if ((index | count) < 0) { ThrowHelper.ThrowArgumentOutOfRangeException((index < 0) ? ExceptionArgument.index : ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (bytes.Length - index < count) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.bytes, ExceptionResource.ArgumentOutOfRange_IndexCountBuffer); } fixed(byte *pBytes = bytes) { return(GetCharCountCommon(pBytes + index, count)); } }
public T this[int index] { get { if ((uint)index >= (uint)this.m_size) { ThrowHelper.ThrowArgumentOutOfRangeException(); } return(this.m_items[index]); } set { if ((uint)index >= (uint)this.m_size) { ThrowHelper.ThrowArgumentOutOfRangeException(); } this.m_items[index] = value; ++this.m_version; } }
public static unsafe IntPtr StringToCoTaskMemUni(string?s) { if (s is null) { return(IntPtr.Zero); } int nb = (s.Length + 1) * 2; // Overflow checking if (nb < s.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.s); } IntPtr ptr = AllocCoTaskMem(nb); s.AsSpan().CopyTo(new Span <char>((char *)ptr, s.Length)); ((char *)ptr)[s.Length] = '\0'; return(ptr); }
public override unsafe int GetByteCount(char[] chars, int index, int count) { if (chars is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.chars, ExceptionResource.ArgumentNull_Array); } if ((index | count) < 0) { ThrowHelper.ThrowArgumentOutOfRangeException((index < 0) ? ExceptionArgument.index : ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (chars.Length - index < count) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.chars, ExceptionResource.ArgumentOutOfRange_IndexCountBuffer); } fixed(char *pChars = chars) { return(GetByteCountCommon(pChars + index, count)); } }
//--------------------------------------------------------------------- // internal for tests internal int GetDecodedLength(int encodedLength) { if ((uint)encodedLength >= int.MaxValue) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.encodedLength); } int decodedLength; // Shortcut for Guid and other 16 byte data (arranged for the branch predictor / fallthrough) if (encodedLength != 22) { if (!TryGetNumBase64PaddingCharsToAddForDecode(encodedLength, out int numPaddingChars)) { ThrowHelper.ThrowMalformedInputException(encodedLength); } int base64LenTmp = encodedLength + numPaddingChars; if (base64LenTmp >= 0) { Debug.Assert(base64LenTmp % 4 == 0, "Invariant: Array length must be a multiple of 4."); decodedLength = (base64LenTmp >> 2) * 3 - numPaddingChars; } else { // overflow ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.encodedLength); throw null; } } else { decodedLength = 16; } return(decodedLength); }
internal unsafe void TryWrite(byte[] array, int offset, int count) { if (array is null || 0u >= (uint)array.Length) { return; } if ((uint)count > SharedConstants.TooBigOrNegative) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count); } if ((uint)array.Length < (uint)(offset + count)) { ThrowHelper.ThrowArgumentException_InvalidOffLen(); } Validate(); try { fixed(byte *memory = array) { var buf = new uv_buf_t((IntPtr)memory + offset, count); NativeMethods.TryWriteStream(InternalHandle, ref buf); } } #if DEBUG catch (Exception exception) { if (Log.DebugEnabled) { Log.Debug($"{HandleType} Trying to write data failed.", exception); } #else catch (Exception) { #endif throw; } }
/// <summary> /// Create a texture from memory /// </summary> /// <param name="data">The data that contains the texture in memory</param> /// <param name="type">The type of the texture to create, or <see cref="TexType.RuntimeDetect"/> to automatically detect</param> /// <param name="loaderFlags">The flags passed to the texture loader</param> /// <param name="maxMipMapSize">The maximum permitted size of a mipmap, or 0 to indicate the maximum size permitted by hardware</param> /// <returns>A texture description</returns> public static TextureDescription CreateTexture( Memory <byte> data, TexType type = TexType.RuntimeDetect, LoaderFlags loaderFlags = LoaderFlags.None, uint maxMipMapSize = 0 ) { if (type == TexType.RuntimeDetect && !TryResolveTexture(data, out type)) { ThrowHelper.ThrowArgumentException("Could not recognise texture format"); } switch (type) { case TexType.RuntimeDetect: ThrowHelper.NeverReached(); break; case TexType.DirectDrawSurface: return(CreateDdsTexture(data, maxMipMapSize, loaderFlags)); case TexType.Bitmap: ThrowHelper.Todo(); break; case TexType.TruevisionGraphicsAdapter: return(CreateTgaTexture(data, loaderFlags)); case TexType.PortableNetworkGraphics: ThrowHelper.Todo(); break; default: ThrowHelper.ThrowArgumentOutOfRangeException(nameof(type), type); return(default); } return(default);
public static int FindIndex <TSource>(this IEnumerable <TSource> source, int startIndex, int count, Func <TSource, bool> predicate) { if (source == null) { ThrowHelper.ThrowArgumentNullException(nameof(source)); } if (predicate == null) { ThrowHelper.ThrowArgumentNullException(nameof(predicate)); } var collection = source as ICollection <TSource> ?? source.ToList(); if ((uint)startIndex > (uint)collection.Count) { ThrowHelper.ThrowArgumentOutOfRangeException(nameof(startIndex)); } if (count < 0 || startIndex > collection.Count - count) { ThrowHelper.ThrowArgumentOutOfRangeException(nameof(count)); } var idx = startIndex; foreach (var item in collection.Skip(startIndex).TakeWhile((item, index) => index < count)) { if (predicate(item)) { return(idx); } idx++; } return(-1); }
/// <summary> /// Writes a field-header, indicating the format of the next data we plan to write. /// </summary> public void WriteFieldHeader(int fieldNumber, WireType wireType) { var writer = _writer; if (writer.WireType != WireType.None) { FailPendingField(writer, fieldNumber, wireType); } if (fieldNumber < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(nameof(fieldNumber)); } writer._needFlush = true; if (writer.packedFieldNumber == 0) { writer.fieldNumber = fieldNumber; writer.WireType = wireType; WriteHeaderCore(fieldNumber, wireType); } else { WritePackedField(writer, fieldNumber, wireType); }
public int IndexOf(char c, int start, int count) { var offset = Offset + start; if (!HasValue || start < 0 || (uint)offset > (uint)Buffer.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); } if (count < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count); } var index = Buffer.IndexOf(c, offset, count); if (index != -1) { index -= Offset; } return(index); }
/// <summary> /// Sets the keep alive values. /// </summary> /// <param name="socket">The socket.</param> /// <param name="state">if set to <c>true</c> [state].</param> /// <param name="keepAliveTime">The keep alive time. Specifies the connection idle time in milliseconds before TCP will begin sending keepalives, if keepalives are enabled on a connection.</param> /// <param name="keepAliveInterval">The keep alive interval. Specifies the time in milliseconds between retransmissions of keepalives, once the KeepAliveTime has expired. Once KeepAliveTime has expired, keepalives are sent every KeepAliveInterval milliseconds until a response is received, up to a maximum of MaxDataRetries before the connection is terminated.</param> /// <returns>value</returns> public static int SetKeepAliveValues(Socket socket, bool state, int keepAliveTime, int keepAliveInterval) { if (socket == null) { ThrowHelper.ThrowArgumentNullException("socket"); } if (keepAliveTime < 1000) { ThrowHelper.ThrowArgumentOutOfRangeException("keepAliveTime"); } if (keepAliveInterval < 1000) { ThrowHelper.ThrowArgumentOutOfRangeException("keepAliveInterval"); } TcpKeepAlive keepAlive = new TcpKeepAlive(); keepAlive.State = Convert.ToUInt32(state); keepAlive.KeepAliveTime = Convert.ToUInt32(keepAliveTime); keepAlive.KeepAliveInterval = Convert.ToUInt32(keepAliveInterval); return(socket.IOControl(IOControlCode.KeepAliveValues, keepAlive.ToArray(), null)); }