/// <summary> /// Creates TransformedReadOnlyListWrapper from the current list /// </summary> /// <typeparam name="TOut">Type of the elements of the newly created TransformedReadOnlyListWrapper</typeparam> /// <param name="selector">Element conversion delegate</param> /// <returns>Created TransformedReadOnlyListWrapper</returns> public TransformedReadOnlyListWrapper <T, TOut> AsTransformedReadOnlyList <TOut>(Func <T, TOut> selector) { TurboContract.Requires(selector != null, conditionString: "selector != null"); TurboContract.Ensures(TurboContract.Result <TransformedReadOnlyListWrapper <T, TOut> >() != null); return(new TransformedReadOnlyListWrapper <T, TOut>(_list, selector)); }
/// <summary> /// Produces full description for the Exception (almost equivalent to ToString results) /// </summary> /// <param name="ex">Source exception</param> /// <returns>Full description for the exception</returns> public static string GetFullDescription(this Exception ex) { TurboContract.Requires(ex != null, conditionString: "ex != null"); TurboContract.Ensures(TurboContract.Result <string>() != null); if (ex == null) { throw new ArgumentNullException(nameof(ex)); } StringBuilder builder = new StringBuilder(1000); builder.Append(ex.GetType().Name).Append(": ").Append(ex.Message).AppendLine(); builder.Append("Source: ").Append(ex.Source).AppendLine(); builder.Append("StackTrace: ").Append(ex.StackTrace).AppendLine(); Exception cur = ex.InnerException; while (cur != null) { builder.Append("--> ").Append(cur.GetType().Name).Append(": ").Append(cur.Message).AppendLine(); builder.Append(" Source: ").Append(cur.Source).AppendLine(); builder.Append(" StackTrace: ").Append(cur.StackTrace).AppendLine(); cur = cur.InnerException; } return(builder.ToString()); }
public bool TryResolve(T key, out object val) { TurboContract.Requires(key != null, conditionString: "key != null"); TurboContract.Ensures(TurboContract.Result <bool>() == true || (TurboContract.Result <bool>() == false && TurboContract.ValueAtReturn <object>(out val) == null)); throw new NotImplementedException(); }
/// <summary> /// Wraps existed ICollection with ReadOnlyCollectionWrapper /// </summary> /// <typeparam name="T">The type of elements in the collection</typeparam> /// <param name="col">Source collection</param> /// <returns>ReadOnlyCollectionWrapper that wraps specified ICollection instance</returns> public static ReadOnlyCollectionWrapper <T> AsReadOnlyCollectionWrapper <T>(this ICollection <T> col) { TurboContract.Requires(col != null, conditionString: "col != null"); TurboContract.Ensures(TurboContract.Result <ReadOnlyCollectionWrapper <T> >() != null); return(new ReadOnlyCollectionWrapper <T>(col)); }
/// <summary> /// Wraps existed Set instance with ReadOnlyHashSet /// </summary> /// <typeparam name="T">The type of elements in the set</typeparam> /// <param name="set">Source HashSet</param> /// <returns>ReadOnlyHashSet that wraps specified HashSet instance</returns> public static ReadOnlyHashSet <T> AsReadOnlyHashSet <T>(this HashSet <T> set) { TurboContract.Requires(set != null, conditionString: "set != null"); TurboContract.Ensures(TurboContract.Result <ReadOnlyHashSet <T> >() != null); return(new ReadOnlyHashSet <T>(set)); }
/// <summary> /// Wraps existed Dictionary instance with ReadOnlyDictionary /// </summary> /// <typeparam name="TKey">The type of keys in the dictionary</typeparam> /// <typeparam name="TValue">The type of values in the dictionary</typeparam> /// <param name="dict">Source dictionary</param> /// <returns>ReadOnlyDictionary that wraps specified Dictionary instance</returns> public static ReadOnlyDictionary <TKey, TValue> AsReadOnlyDictionary <TKey, TValue>(this Dictionary <TKey, TValue> dict) { TurboContract.Requires(dict != null, conditionString: "dict != null"); TurboContract.Ensures(TurboContract.Result <ReadOnlyDictionary <TKey, TValue> >() != null); return(new ReadOnlyDictionary <TKey, TValue>(dict)); }
/// <summary> /// Wraps existed IList collection with ReadOnlyListWrapper /// </summary> /// <typeparam name="T">The type of elements in the list</typeparam> /// <param name="list">Source list of items</param> /// <returns>ReadOnlyListWrapper that wraps specified IList instance</returns> public static ReadOnlyListWrapper <T> AsReadOnlyListWrapper <T>(this IList <T> list) { TurboContract.Requires(list != null, conditionString: "list != null"); TurboContract.Ensures(TurboContract.Result <ReadOnlyListWrapper <T> >() != null); return(new ReadOnlyListWrapper <T>(list)); }
public object CreateInstance(IInjectionResolver resolver) { TurboContract.Requires(resolver != null, conditionString: "resolver != null"); TurboContract.Ensures(TurboContract.Result <object>() != null); throw new NotImplementedException(); }
// ===================== /// <summary> /// Попробовать выполнить похищение элемента из соседних локальных очередей /// </summary> /// <param name="localQueue">Локальная очередь текущего потока</param> /// <param name="otherLocalQueues">Разреженный массив локальных очередей других потоков</param> /// <param name="item">Выбранный элемент</param> /// <returns>Удалось ли сделать выборку</returns> private bool TryTakeFromOtherLocalQueues(ThreadPoolLocalQueue localQueue, ThreadPoolLocalQueue[] otherLocalQueues, out ThreadPoolWorkItem item) { TurboContract.Requires(otherLocalQueues != null, conditionString: "otherLocalQueues != null"); TurboContract.Ensures(TurboContract.Result <bool>() == false || TurboContract.ValueAtReturn(out item) != null); bool result = false; item = null; try { } finally { int length = otherLocalQueues.Length; int index = Interlocked.Increment(ref _stealIndex) & int.MaxValue; for (int i = 0; i < length; i++, index++) { var otherQueue = Volatile.Read(ref otherLocalQueues[index % length]); if (otherQueue != null && otherQueue != localQueue && otherQueue.TrySteal(out item)) { result = true; break; } } } return(result); }
/// <summary>Code contracts</summary> public bool TryGetAssociation(T key, out LifetimeBase val) { TurboContract.Ensures((TurboContract.Result <bool>() == true && TurboContract.ValueAtReturn <LifetimeBase>(out val) != null) || (TurboContract.Result <bool>() == false && TurboContract.ValueAtReturn <LifetimeBase>(out val) == null)); throw new NotImplementedException(); }
/// <summary> /// Выборка элемента из головы (может вызываться из любого потока) /// </summary> /// <param name="item">Выбранный элемент</param> /// <returns>Удалось ли сделать выборку</returns> public bool TrySteal(out ThreadPoolWorkItem item) { TurboContract.Ensures(TurboContract.Result <bool>() == false || TurboContract.ValueAtReturn(out item) != null); if (HasElements(_head, _tail)) { lock (_syncObj) { int head = _head; if (HasElements(head, _tail)) { item = Interlocked.Exchange(ref _data[head % QueueSize], null); if (item != null) { //RemoveElementFromHead(); _head = head + 1; return(true); } } } } item = null; return(false); }
protected override int MapPriority(TPriority prior) { TurboContract.Ensures(TurboContract.Result <int>() >= 0); TurboContract.Ensures(TurboContract.Result <int>() < this.PriorityLevelsCount); throw new NotImplementedException(); }
/// <summary> /// Захватить лучший элемент из доступных /// </summary> /// <param name="element">Захваченный элемент</param> /// <returns>Удалось ли захватить</returns> private bool TryTakeBest(out PoolElementWrapper <T> element) { TurboContract.Ensures((TurboContract.Result <bool>() == false && TurboContract.ValueAtReturn(out element) == null) || (TurboContract.Result <bool>() == true && TurboContract.ValueAtReturn(out element) != null && TurboContract.ValueAtReturn(out element).IsBusy)); PoolElementWrapper <T> b1, b2, b3; PoolElementWrapper <T> earlyStopResult = FindBest3WithStopping(out b1, out b2, out b3); if (earlyStopResult != null) { TurboContract.Assert(earlyStopResult.IsBusy, conditionString: "earlyStopResult.IsBusy"); element = earlyStopResult; return(true); } if (b1 != null && b1.TryMakeBusyAtomic() && !b1.IsRemoved) { element = b1; return(true); } if (b2 != null && b2.TryMakeBusyAtomic() && !b2.IsRemoved) { element = b2; return(true); } if (b3 != null && b3.TryMakeBusyAtomic() && !b3.IsRemoved) { element = b3; return(true); } element = null; return(false); }
protected override bool TryGetAssociationInner(T key, out LifetimeBase val) { TurboContract.Requires(key != null, conditionString: "key != null"); TurboContract.Ensures((TurboContract.Result <bool>() == true && TurboContract.ValueAtReturn <LifetimeBase>(out val) != null) || (TurboContract.Result <bool>() == false && TurboContract.ValueAtReturn <LifetimeBase>(out val) == null)); throw new NotImplementedException(); }
public override object GetInstance(IInjectionResolver resolver) { TurboContract.Requires(resolver != null, conditionString: "resolver != null"); TurboContract.Ensures((TurboContract.Result <object>() != null && TurboContract.Result <object>().GetType() == this.OutputType) || (TurboContract.Result <object>() == null && this.OutputType.IsAssignableFromNull())); throw new NotImplementedException(); }
public override LifetimeBase Create(Type objType, IInjectionResolver injection, object extInfo) { TurboContract.Requires(objType != null, conditionString: "objType != null"); TurboContract.Requires(injection != null, conditionString: "injection != null"); TurboContract.Ensures(TurboContract.Result <LifetimeBase>() != null); TurboContract.Ensures(TurboContract.Result <LifetimeBase>().OutputType == objType); throw new NotImplementedException(); }
protected override LifetimeBase ProduceResolveInfo(T key, Type objType, Lifetime.Factories.LifetimeFactory val) { TurboContract.Requires(key != null, conditionString: "key != null"); TurboContract.Requires(objType != null, conditionString: "objType != null"); TurboContract.Requires(val != null, conditionString: "val != null"); TurboContract.Ensures(TurboContract.Result <LifetimeBase>() != null); throw new NotImplementedException(); }
/// <summary> /// Copies the priority queue elements to a new array /// </summary> /// <returns>A new array containing elements copied from the queue</returns> public TElem[] ToArray() { TurboContract.Ensures(TurboContract.Result <TElem[]>() != null); TurboContract.Ensures(TurboContract.Result <TElem[]>().Length == this.Count); TElem[] array = new TElem[this._count]; this.CopyTo(array, 0); return(array); }
/// <summary> /// Забрать элемент из очереди /// </summary> /// <returns>Полученный элемент</returns> public ThreadPoolWorkItem Take() { TurboContract.Ensures(TurboContract.Result <ThreadPoolWorkItem>() != null); ThreadPoolWorkItem result = null; bool success = TryTake(out result, Timeout.Infinite, new CancellationToken(), true); TurboContract.Assert(success, "Element was not taken from ThreadPoolGlobalQueue due to unknown reason"); return(result); }
public static int FindIndex <T>(this IEnumerable <T> collection, Predicate <T> predicate) { TurboContract.Ensures(TurboContract.Result <int>() >= -1); if (collection == null) { throw new ArgumentNullException(nameof(collection)); } if (predicate == null) { throw new ArgumentNullException(nameof(predicate)); } if (collection is IList <T> iList) { if (collection is List <T> list) { return(list.FindIndex(predicate)); } if (collection is T[] array) { return(Array.FindIndex(array, predicate)); } int count = iList.Count; for (int i = 0; i < count; i++) { if (predicate(iList[i])) { return(i); } } return(-1); } int index = 0; foreach (T elem in collection) { if (predicate(elem)) { return(index); } index++; } return(-1); }
public bool TryTakeItem(ThreadPoolThreadLocals local, bool doLocalSearch, bool doWorkSteal, out ThreadPoolWorkItem item, int timeout, CancellationToken token, bool throwOnCancellation) { TurboContract.Ensures(TurboContract.Result <bool>() == false || TurboContract.ValueAtReturn(out item) != null); TurboContract.Assert(!_isDisposed, conditionString: "!_isDisposed"); if (local != null) { return(_queues.TryTake(local.LocalQueue, doLocalSearch, doWorkSteal, out item, timeout, token, throwOnCancellation)); } else { return(_queues.TryTake(null, doLocalSearch, doWorkSteal, out item, timeout, token, throwOnCancellation)); } }
public bool TryTakeItem(ThreadPoolThreadLocals local, out ThreadPoolWorkItem item) { TurboContract.Ensures(TurboContract.Result <bool>() == false || TurboContract.ValueAtReturn(out item) != null); TurboContract.Assert(!_isDisposed, conditionString: "!_isDisposed"); if (local != null) { return(_queues.TryTake(local.LocalQueue, out item, 0, new CancellationToken(), true)); } else { return(_queues.TryTake(null, out item, 0, new CancellationToken(), true)); } }
public ThreadPoolWorkItem TakeItem(ThreadPoolThreadLocals local, CancellationToken token) { TurboContract.Ensures(TurboContract.Result <ThreadPoolWorkItem>() != null); TurboContract.Assert(!_isDisposed, conditionString: "!_isDisposed"); if (local != null) { return(_queues.Take(local.LocalQueue, token)); } else { return(_queues.Take(null, token)); } }
/// <summary> /// Attempts to add a new association to the container /// </summary> /// <param name="key">Key</param> /// <param name="val">Lifetime object container to add</param> /// <returns>True if AssociationContainer not contains lifetime container with the same key; overwise false</returns> protected bool TryAddAssociation(TKey key, LifetimeBase val) { TurboContract.Requires(key != null, conditionString: "key != null"); TurboContract.Requires(val != null, conditionString: "val != null"); TurboContract.Ensures(TurboContract.Result <bool>() == false || this.ContainsInner(key)); if (!IsGoodTypeForKey(key, val.OutputType)) { throw new AssociationBadKeyForTypeException(string.Format("Bad key ({0}) for the type ({1})", key, val.OutputType)); } CheckContainerState(true); return(TryAddAssociationInner(key, val)); }
/// <summary> /// Попробовать достать элемент из очереди /// </summary> /// <param name="item">Выбранный элемент</param> /// <returns>Удалось ли выбрать</returns> public bool TryTake(out ThreadPoolWorkItem item) { TurboContract.Ensures(TurboContract.Result <bool>() == false || TurboContract.ValueAtReturn(out item) != null); while (this.HasElements()) { Segment head = _head; if (head.TryTake(out item)) { return(true); } } item = null; return(false); }
/// <summary> /// Attempts to add a new association to the container /// </summary> /// <param name="key">Key</param> /// <param name="val">Object to add</param> /// <returns>True if the injection was added, that is InjectionContainer not contains lifetime container with the same key; overwise false</returns> /// <exception cref="ObjectDisposedException"></exception> /// <exception cref="ObjectFrozenException"></exception> public bool TryAddInjection(TKey key, object val) { TurboContract.Ensures(TurboContract.Result <bool>() == false || this.ContainsInner(key)); if (key == null) { throw new ArgumentNullException(nameof(key)); } if (!IsGoodInjectionForKey(key, val)) { throw new InjectionBadKeyForItemException(string.Format("Bad key ({0}) for the supplied object", key)); } CheckContainerState(true); return(TryAddInjectionInner(key, val)); }
/// <summary> /// Получить или создать данные для текущего потока. /// Предполагается, что вызывающий поток принадлежит пулу потоков /// </summary> /// <param name="createThreadLocalQueue">Создавать ли локальную очередь потока</param> /// <returns>Данные потока</returns> public ThreadPoolThreadLocals GetOrCreateThisThreadData(bool createThreadLocalQueue = true) { TurboContract.Ensures(TurboContract.Result <ThreadPoolThreadLocals>() != null); TurboContract.Assert(!_isDisposed, conditionString: "!_isDisposed"); ThreadPoolThreadLocals result = _perThreadData.Value; if (result == null) { result = new ThreadPoolThreadLocals(this, createThreadLocalQueue); _perThreadData.Value = result; if (createThreadLocalQueue) { _queues.AddLocalQueue(result.LocalQueue); } } return(result); }
/// <summary> /// Выборка элемента из хвоста (должно вызываться из потока-владельца) /// </summary> /// <param name="item">Выбранный элемент</param> /// <returns>Удалось ли сделать выборку</returns> public bool TryTakeLocal(out ThreadPoolWorkItem item) { TurboContract.Ensures(TurboContract.Result <bool>() == false || TurboContract.ValueAtReturn(out item) != null); int tail = _tail; if (HasElements(_head, tail)) { item = Interlocked.Exchange(ref _data[(tail - 1) % QueueSize], null); if (item != null) { //RemoveElementFromTail(); _tail = tail - 1; return(true); } } item = null; return(false); }
/// <summary> /// Попытаться выбрать элемент из сегмента /// </summary> /// <param name="item">Выбранный элемент</param> /// <returns>Удалось ли сделать выборку</returns> public bool TryTake(out ThreadPoolWorkItem item) { TurboContract.Ensures(TurboContract.Result <bool>() == false || TurboContract.ValueAtReturn(out item) != null); SpinWait sw = new SpinWait(); int head = _head; while (HasElements(head, _tail)) { if (Interlocked.CompareExchange(ref _head, head + 1, head) == head) { SpinWait itemSw = new SpinWait(); ThreadPoolWorkItem localItem = null; while ((localItem = Volatile.Read(ref _data[head])) == null) { itemSw.SpinOnce(); } item = localItem; Volatile.Write(ref _data[head], null); if (head + 1 >= SegmentSize) { SpinWait headSw = new SpinWait(); while (_next == null) { headSw.SpinOnce(); } _parent._head = _next; } return(true); } sw.SpinOnce(); head = _head; } item = null; return(false); }
/// <summary> /// Copies the list elements to a new array /// </summary> /// <returns>A new array containing elements copied from the list</returns> public T[] ToArray() { TurboContract.Ensures(TurboContract.Result <T[]>() != null); TurboContract.Ensures(TurboContract.Result <T[]>().Length == this.Count); T[] array = new T[_size]; if (_size == 0) { return(array); } if (_head < _tail) { Array.Copy(_elemArray, _head, array, 0, _size); } else { Array.Copy(_elemArray, _head, array, 0, _elemArray.Length - _head); Array.Copy(_elemArray, 0, array, _elemArray.Length - _head, _tail); } return(array); }