Requires.NotNull(source, nameof(source));
Requires.NotNull(keySelector, nameof(keySelector));
Requires.NotNull(elementSelector, nameof(elementSelector));
- Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null);
return ImmutableDictionary<TKey, TValue>.Empty.WithComparers(keyComparer, valueComparer)
.AddRange(source.Select(element => new KeyValuePair<TKey, TValue>(keySelector(element), elementSelector(element))));
public static ImmutableDictionary<TKey, TValue> ToImmutableDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> source, IEqualityComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer)
{
Requires.NotNull(source, nameof(source));
- Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null);
var existingDictionary = source as ImmutableDictionary<TKey, TValue>;
if (existingDictionary != null)
public ImmutableDictionary<TKey, TValue> Add(TKey key, TValue value)
{
Requires.NotNullAllowStructs(key, nameof(key));
- Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null);
var result = Add(key, value, KeyCollisionBehavior.ThrowIfValueDifferent, this.Origin);
return result.Finalize(this);
public ImmutableDictionary<TKey, TValue> AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs)
{
Requires.NotNull(pairs, nameof(pairs));
- Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null);
return this.AddRange(pairs, false);
}
public ImmutableDictionary<TKey, TValue> SetItem(TKey key, TValue value)
{
Requires.NotNullAllowStructs(key, nameof(key));
- Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null);
- Contract.Ensures(!Contract.Result<ImmutableDictionary<TKey, TValue>>().IsEmpty);
var result = Add(key, value, KeyCollisionBehavior.SetValue, this.Origin);
return result.Finalize(this);
public ImmutableDictionary<TKey, TValue> SetItems(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
Requires.NotNull(items, nameof(items));
- Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null);
var result = AddRange(items, this.Origin, KeyCollisionBehavior.SetValue);
return result.Finalize(this);
public ImmutableDictionary<TKey, TValue> Remove(TKey key)
{
Requires.NotNullAllowStructs(key, nameof(key));
- Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null);
var result = Remove(key, this.Origin);
return result.Finalize(this);
public ImmutableDictionary<TKey, TValue> RemoveRange(IEnumerable<TKey> keys)
{
Requires.NotNull(keys, nameof(keys));
- Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null);
int count = _count;
var root = _root;
private ImmutableDictionary<TKey, TValue> AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs, bool avoidToHashMap)
{
Requires.NotNull(pairs, nameof(pairs));
- Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null);
// Some optimizations may apply if we're an empty list.
if (this.IsEmpty && !avoidToHashMap)
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
-using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
-using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection;
internal static IOrderedCollection<T> AsOrderedCollection<T>(this IEnumerable<T> sequence)
{
Requires.NotNull(sequence, nameof(sequence));
- Contract.Ensures(Contract.Result<IOrderedCollection<T>>() != null);
var orderedCollection = sequence as IOrderedCollection<T>;
if (orderedCollection != null)
/// </summary>
public ImmutableHashSet<T> Clear()
{
- Contract.Ensures(Contract.Result<ImmutableHashSet<T>>() != null);
- Contract.Ensures(Contract.Result<ImmutableHashSet<T>>().IsEmpty);
return this.IsEmpty ? this : ImmutableHashSet<T>.Empty.WithComparer(_equalityComparer);
}
[Pure]
public ImmutableHashSet<T> Add(T item)
{
- Contract.Ensures(Contract.Result<ImmutableHashSet<T>>() != null);
-
var result = Add(item, this.Origin);
return result.Finalize(this);
}
/// </summary>
public ImmutableHashSet<T> Remove(T item)
{
- Contract.Ensures(Contract.Result<ImmutableHashSet<T>>() != null);
-
var result = Remove(item, this.Origin);
return result.Finalize(this);
}
public ImmutableHashSet<T> Union(IEnumerable<T> other)
{
Requires.NotNull(other, nameof(other));
- Contract.Ensures(Contract.Result<ImmutableHashSet<T>>() != null);
return this.Union(other, avoidWithComparer: false);
}
public ImmutableHashSet<T> Intersect(IEnumerable<T> other)
{
Requires.NotNull(other, nameof(other));
- Contract.Ensures(Contract.Result<ImmutableHashSet<T>>() != null);
var result = Intersect(other, this.Origin);
return result.Finalize(this);
public ImmutableHashSet<T> SymmetricExcept(IEnumerable<T> other)
{
Requires.NotNull(other, nameof(other));
- Contract.Ensures(Contract.Result<IImmutableSet<T>>() != null);
var result = SymmetricExcept(other, this.Origin);
return result.Finalize(this);
[Pure]
public ImmutableHashSet<T> WithComparer(IEqualityComparer<T> equalityComparer)
{
- Contract.Ensures(Contract.Result<ImmutableHashSet<T>>() != null);
if (equalityComparer == null)
{
equalityComparer = EqualityComparer<T>.Default;
{
var result = new ImmutableHashSet<T>(equalityComparer);
result = result.Union(this, avoidWithComparer: true);
+ Debug.Assert(result != null);
return result;
}
}
private ImmutableHashSet<T> Union(IEnumerable<T> items, bool avoidWithComparer)
{
Requires.NotNull(items, nameof(items));
- Contract.Ensures(Contract.Result<ImmutableHashSet<T>>() != null);
// Some optimizations may apply if we're an empty set.
if (this.IsEmpty && !avoidWithComparer)
using System.Collections.Generic;
using System.ComponentModel;
-using System.Diagnostics.Contracts;
namespace System.Collections.Immutable
{
/// </summary>
private void ThrowIfDisposed()
{
- Contract.Ensures(_root != null);
- Contract.EnsuresOnThrow<ObjectDisposedException>(_root == null);
-
// Since this is a struct, copies might not have been marked as disposed.
// But the stack we share across those copies would know.
// This trick only works when we have a non-null stack.
/// </summary>
private Node()
{
- Contract.Ensures(this.IsEmpty);
_frozen = true; // the empty node is *always* frozen.
+ Debug.Assert(this.IsEmpty);
}
/// <summary>
Requires.NotNull(left, nameof(left));
Requires.NotNull(right, nameof(right));
Debug.Assert(!frozen || (left._frozen && right._frozen));
- Contract.Ensures(!this.IsEmpty);
_key = key;
_left = left;
_height = ParentHeight(left, right);
_count = ParentCount(left, right);
_frozen = frozen;
+
+ Debug.Assert(!this.IsEmpty);
}
/// <summary>
{
get
{
- Contract.Ensures(Contract.Result<bool>() == (_left == null));
Debug.Assert(!(_left == null ^ _right == null));
return _left == null;
}
internal Node RemoveAll(Predicate<T> match)
{
Requires.NotNull(match, nameof(match));
- Contract.Ensures(Contract.Result<Node>() != null);
var result = this;
var enumerator = new Enumerator(result);
enumerator.Dispose();
}
+ Debug.Assert(result != null);
return result;
}
internal Node Sort(Comparison<T> comparison)
{
Requires.NotNull(comparison, nameof(comparison));
- Contract.Ensures(Contract.Result<Node>() != null);
// PERF: Eventually this might be reimplemented in a way that does not require allocating an array.
var array = new T[this.Count];
internal ImmutableList<T> FindAll(Predicate<T> match)
{
Requires.NotNull(match, nameof(match));
- Contract.Ensures(Contract.Result<ImmutableList<T>>() != null);
if (this.IsEmpty)
{
internal int FindIndex(Predicate<T> match)
{
Requires.NotNull(match, nameof(match));
- Contract.Ensures(Contract.Result<int>() >= -1);
return this.FindIndex(0, _count, match);
}
internal int FindLastIndex(Predicate<T> match)
{
Requires.NotNull(match, nameof(match));
- Contract.Ensures(Contract.Result<int>() >= -1);
return this.IsEmpty ? -1 : this.FindLastIndex(this.Count - 1, this.Count, match);
}
{
Debug.Assert(!this.IsEmpty);
Debug.Assert(!_right.IsEmpty);
- Contract.Ensures(Contract.Result<Node>() != null);
return _right.MutateLeft(this.MutateRight(_right._left));
}
{
Debug.Assert(!this.IsEmpty);
Debug.Assert(!_left.IsEmpty);
- Contract.Ensures(Contract.Result<Node>() != null);
return _left.MutateRight(this.MutateLeft(_left._right));
}
Debug.Assert(!this.IsEmpty);
Debug.Assert(!_right.IsEmpty);
Debug.Assert(!_right._left.IsEmpty);
- Contract.Ensures(Contract.Result<Node>() != null);
// The following is an optimized version of rotating the right child right, then rotating the parent left.
Node right = _right;
Debug.Assert(!this.IsEmpty);
Debug.Assert(!_left.IsEmpty);
Debug.Assert(!_left._right.IsEmpty);
- Contract.Ensures(Contract.Result<Node>() != null);
// The following is an optimized version of rotating the left child left, then rotating the parent right.
Node left = _left;
[Pure]
public ImmutableList<T> Add(T value)
{
- Contract.Ensures(Contract.Result<ImmutableList<T>>() != null);
- Contract.Ensures(Contract.Result<ImmutableList<T>>().Count == this.Count + 1);
var result = _root.Add(value);
return this.Wrap(result);
}
public ImmutableList<T> AddRange(IEnumerable<T> items)
{
Requires.NotNull(items, nameof(items));
- Contract.Ensures(Contract.Result<ImmutableList<T>>() != null);
- Contract.Ensures(Contract.Result<ImmutableList<T>>().Count >= this.Count);
// Some optimizations may apply if we're an empty list.
if (this.IsEmpty)
public ImmutableList<T> Insert(int index, T item)
{
Requires.Range(index >= 0 && index <= this.Count, nameof(index));
- Contract.Ensures(Contract.Result<ImmutableList<T>>() != null);
- Contract.Ensures(Contract.Result<ImmutableList<T>>().Count == this.Count + 1);
return this.Wrap(_root.Insert(index, item));
}
{
Requires.Range(index >= 0 && index <= this.Count, nameof(index));
Requires.NotNull(items, nameof(items));
- Contract.Ensures(Contract.Result<ImmutableList<T>>() != null);
var result = _root.InsertRange(index, items);
[Pure]
public ImmutableList<T> Remove(T value, IEqualityComparer<T> equalityComparer)
{
- Contract.Ensures(Contract.Result<ImmutableList<T>>() != null);
int index = this.IndexOf(value, equalityComparer);
return index < 0 ? this : this.RemoveAt(index);
}
{
Requires.Range(index >= 0 && index <= this.Count, nameof(index));
Requires.Range(count >= 0 && index + count <= this.Count, nameof(count));
- Contract.Ensures(Contract.Result<ImmutableList<T>>() != null);
var result = _root;
int remaining = count;
public ImmutableList<T> RemoveRange(IEnumerable<T> items, IEqualityComparer<T> equalityComparer)
{
Requires.NotNull(items, nameof(items));
- Contract.Ensures(Contract.Result<ImmutableList<T>>() != null);
- Contract.Ensures(Contract.Result<ImmutableList<T>>().Count <= this.Count);
// Some optimizations may apply if we're an empty list.
if (this.IsEmpty)
public ImmutableList<T> RemoveAt(int index)
{
Requires.Range(index >= 0 && index < this.Count, nameof(index));
- Contract.Ensures(Contract.Result<ImmutableList<T>>() != null);
- Contract.Ensures(Contract.Result<ImmutableList<T>>().Count == this.Count - 1);
var result = _root.RemoveAt(index);
return this.Wrap(result);
}
public ImmutableList<T> RemoveAll(Predicate<T> match)
{
Requires.NotNull(match, nameof(match));
- Contract.Ensures(Contract.Result<ImmutableList<T>>() != null);
return this.Wrap(_root.RemoveAll(match));
}
[Pure]
public ImmutableList<T> Replace(T oldValue, T newValue, IEqualityComparer<T> equalityComparer)
{
- Contract.Ensures(Contract.Result<ImmutableList<T>>() != null);
- Contract.Ensures(Contract.Result<ImmutableList<T>>().Count == this.Count);
-
int index = this.IndexOf(oldValue, equalityComparer);
if (index < 0)
{
public ImmutableList<T> Sort(Comparison<T> comparison)
{
Requires.NotNull(comparison, nameof(comparison));
- Contract.Ensures(Contract.Result<ImmutableList<T>>() != null);
return this.Wrap(_root.Sort(comparison));
}
Requires.Range(index >= 0, nameof(index));
Requires.Range(count >= 0, nameof(count));
Requires.Range(index + count <= this.Count, nameof(count));
- Contract.Ensures(Contract.Result<ImmutableList<T>>() != null);
return this.Wrap(_root.Sort(index, count, comparer));
}
/// </summary>
public ImmutableQueue<T> Clear()
{
- Contract.Ensures(Contract.Result<ImmutableQueue<T>>().IsEmpty);
- Contract.Assume(s_EmptyField.IsEmpty);
+ Debug.Assert(s_EmptyField.IsEmpty);
return Empty;
}
{
get
{
- Contract.Ensures(Contract.Result<ImmutableQueue<T>>().IsEmpty);
- Contract.Assume(s_EmptyField.IsEmpty);
+ Debug.Assert(s_EmptyField.IsEmpty);
return s_EmptyField;
}
}
/// </summary>
IImmutableQueue<T> IImmutableQueue<T>.Clear()
{
- Contract.Assume(s_EmptyField.IsEmpty);
+ Debug.Assert(s_EmptyField.IsEmpty);
return this.Clear();
}
{
get
{
- Contract.Ensures(Contract.Result<ImmutableStack<T>>() != null);
-
// Although this is a lazy-init pattern, no lock is required because
// this instance is immutable otherwise, and a double-assignment from multiple
// threads is harmless.
_backwardsReversed = _backwards.Reverse();
}
+ Debug.Assert(_backwardsReversed != null);
return _backwardsReversed;
}
}
[Pure]
public ImmutableQueue<T> Enqueue(T value)
{
- Contract.Ensures(!Contract.Result<ImmutableQueue<T>>().IsEmpty);
-
if (this.IsEmpty)
{
return new ImmutableQueue<T>(ImmutableStack.Create(value), ImmutableStack<T>.Empty);
Requires.NotNull(source, nameof(source));
Requires.NotNull(keySelector, nameof(keySelector));
Requires.NotNull(elementSelector, nameof(elementSelector));
- Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null);
return ImmutableSortedDictionary<TKey, TValue>.Empty.WithComparers(keyComparer, valueComparer)
.AddRange(source.Select(element => new KeyValuePair<TKey, TValue>(keySelector(element), elementSelector(element))));
public static ImmutableSortedDictionary<TKey, TValue> ToImmutableSortedDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> source, IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer)
{
Requires.NotNull(source, nameof(source));
- Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null);
var existingDictionary = source as ImmutableSortedDictionary<TKey, TValue>;
if (existingDictionary != null)
/// </summary>
private Node()
{
- Contract.Ensures(this.IsEmpty);
_frozen = true; // the empty node is *always* frozen.
+ Debug.Assert(this.IsEmpty);
}
/// <summary>
Requires.NotNull(left, nameof(left));
Requires.NotNull(right, nameof(right));
Debug.Assert(!frozen || (left._frozen && right._frozen));
- Contract.Ensures(!this.IsEmpty);
- Contract.Ensures(_key != null);
- Contract.Ensures(_left == left);
- Contract.Ensures(_right == right);
_key = key;
_value = value;
_right = right;
_height = checked((byte)(1 + Math.Max(left._height, right._height)));
_frozen = frozen;
+
+ Debug.Assert(!this.IsEmpty);
}
/// <summary>
{
get
{
- Contract.Ensures((_left != null && _right != null) || Contract.Result<bool>());
return _left == null;
}
}
internal static Node NodeTreeFromSortedDictionary(SortedDictionary<TKey, TValue> dictionary)
{
Requires.NotNull(dictionary, nameof(dictionary));
- Contract.Ensures(Contract.Result<Node>() != null);
var list = dictionary.AsOrderedCollection();
return NodeTreeFromList(list, 0, list.Count);
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
- Contract.Ensures(Contract.Result<Node>() != null);
if (tree._right.IsEmpty)
{
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
- Contract.Ensures(Contract.Result<Node>() != null);
if (tree._left.IsEmpty)
{
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
- Contract.Ensures(Contract.Result<Node>() != null);
if (tree._right.IsEmpty)
{
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
- Contract.Ensures(Contract.Result<Node>() != null);
if (tree._left.IsEmpty)
{
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
- Contract.Ensures(Contract.Result<Node>() != null);
if (IsRightHeavy(tree))
{
Requires.NotNull(items, nameof(items));
Requires.Range(start >= 0, nameof(start));
Requires.Range(length >= 0, nameof(length));
- Contract.Ensures(Contract.Result<Node>() != null);
if (length == 0)
{
/// </summary>
public ImmutableSortedDictionary<TKey, TValue> Clear()
{
- Contract.Ensures(Contract.Result<ImmutableSortedDictionary<TKey, TValue>>() != null);
- Contract.Ensures(Contract.Result<ImmutableSortedDictionary<TKey, TValue>>().IsEmpty);
- Contract.Ensures(Contract.Result<ImmutableSortedDictionary<TKey, TValue>>().KeyComparer == ((ISortKeyCollection<TKey>)this).KeyComparer);
return _root.IsEmpty ? this : Empty.WithComparers(_keyComparer, _valueComparer);
}
public ImmutableSortedDictionary<TKey, TValue> Add(TKey key, TValue value)
{
Requires.NotNullAllowStructs(key, nameof(key));
- Contract.Ensures(Contract.Result<ImmutableSortedDictionary<TKey, TValue>>() != null);
bool mutated;
var result = _root.Add(key, value, _keyComparer, _valueComparer, out mutated);
return this.Wrap(result, _count + 1);
public ImmutableSortedDictionary<TKey, TValue> SetItem(TKey key, TValue value)
{
Requires.NotNullAllowStructs(key, nameof(key));
- Contract.Ensures(Contract.Result<ImmutableSortedDictionary<TKey, TValue>>() != null);
- Contract.Ensures(!Contract.Result<ImmutableSortedDictionary<TKey, TValue>>().IsEmpty);
bool replacedExistingValue, mutated;
var result = _root.SetItem(key, value, _keyComparer, _valueComparer, out replacedExistingValue, out mutated);
return this.Wrap(result, replacedExistingValue ? _count : _count + 1);
public ImmutableSortedDictionary<TKey, TValue> SetItems(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
Requires.NotNull(items, nameof(items));
- Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null);
return this.AddRange(items, overwriteOnCollision: true, avoidToSortedMap: false);
}
public ImmutableSortedDictionary<TKey, TValue> AddRange(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
Requires.NotNull(items, nameof(items));
- Contract.Ensures(Contract.Result<ImmutableSortedDictionary<TKey, TValue>>() != null);
return this.AddRange(items, overwriteOnCollision: false, avoidToSortedMap: false);
}
public ImmutableSortedDictionary<TKey, TValue> Remove(TKey value)
{
Requires.NotNullAllowStructs(value, nameof(value));
- Contract.Ensures(Contract.Result<ImmutableSortedDictionary<TKey, TValue>>() != null);
bool mutated;
var result = _root.Remove(value, _keyComparer, out mutated);
return this.Wrap(result, _count - 1);
public ImmutableSortedDictionary<TKey, TValue> RemoveRange(IEnumerable<TKey> keys)
{
Requires.NotNull(keys, nameof(keys));
- Contract.Ensures(Contract.Result<ImmutableSortedDictionary<TKey, TValue>>() != null);
var result = _root;
int count = _count;
[Pure]
public ImmutableSortedDictionary<TKey, TValue> WithComparers(IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer)
{
- Contract.Ensures(Contract.Result<ImmutableSortedDictionary<TKey, TValue>>() != null);
- Contract.Ensures(Contract.Result<ImmutableSortedDictionary<TKey, TValue>>().IsEmpty == this.IsEmpty);
if (keyComparer == null)
{
keyComparer = Comparer<TKey>.Default;
private ImmutableSortedDictionary<TKey, TValue> AddRange(IEnumerable<KeyValuePair<TKey, TValue>> items, bool overwriteOnCollision, bool avoidToSortedMap)
{
Requires.NotNull(items, nameof(items));
- Contract.Ensures(Contract.Result<ImmutableSortedDictionary<TKey, TValue>>() != null);
// Some optimizations may apply if we're an empty set.
if (this.IsEmpty && !avoidToSortedMap)
using System.Collections.Generic;
using System.ComponentModel;
-using System.Diagnostics.Contracts;
namespace System.Collections.Immutable
{
/// </summary>
private void ThrowIfDisposed()
{
- Contract.Ensures(_root != null);
- Contract.EnsuresOnThrow<ObjectDisposedException>(_root == null);
-
// Since this is a struct, copies might not have been marked as disposed.
// But the stack we share across those copies would know.
// This trick only works when we have a non-null stack.
/// </summary>
private Node()
{
- Contract.Ensures(this.IsEmpty);
_frozen = true; // the empty node is *always* frozen.
+ Debug.Assert(this.IsEmpty);
}
/// <summary>
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
- Contract.Ensures(Contract.Result<Node>() != null);
if (tree._right.IsEmpty)
{
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
- Contract.Ensures(Contract.Result<Node>() != null);
if (tree._left.IsEmpty)
{
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
- Contract.Ensures(Contract.Result<Node>() != null);
if (tree._right.IsEmpty)
{
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
- Contract.Ensures(Contract.Result<Node>() != null);
if (tree._left.IsEmpty)
{
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
- Contract.Ensures(Contract.Result<Node>() != null);
if (IsRightHeavy(tree))
{
/// </summary>
public ImmutableSortedSet<T> Clear()
{
- Contract.Ensures(Contract.Result<ImmutableSortedSet<T>>() != null);
- Contract.Ensures(Contract.Result<ImmutableSortedSet<T>>().IsEmpty);
return _root.IsEmpty ? this : Empty.WithComparer(_comparer);
}
[Pure]
public ImmutableSortedSet<T> Add(T value)
{
- Contract.Ensures(Contract.Result<ImmutableSortedSet<T>>() != null);
bool mutated;
return this.Wrap(_root.Add(value, _comparer, out mutated));
}
[Pure]
public ImmutableSortedSet<T> Remove(T value)
{
- Contract.Ensures(Contract.Result<ImmutableSortedSet<T>>() != null);
bool mutated;
return this.Wrap(_root.Remove(value, _comparer, out mutated));
}
public ImmutableSortedSet<T> Intersect(IEnumerable<T> other)
{
Requires.NotNull(other, nameof(other));
- Contract.Ensures(Contract.Result<ImmutableSortedSet<T>>() != null);
+
var newSet = this.Clear();
foreach (var item in other.GetEnumerableDisposable<T, Enumerator>())
{
}
}
+ Debug.Assert(newSet != null);
return newSet;
}
public ImmutableSortedSet<T> Union(IEnumerable<T> other)
{
Requires.NotNull(other, nameof(other));
- Contract.Ensures(Contract.Result<ImmutableSortedSet<T>>() != null);
ImmutableSortedSet<T> immutableSortedSet;
if (TryCastToImmutableSortedSet(other, out immutableSortedSet) && immutableSortedSet.KeyComparer == this.KeyComparer) // argument is a compatible immutable sorted set
[Pure]
public ImmutableSortedSet<T> WithComparer(IComparer<T> comparer)
{
- Contract.Ensures(Contract.Result<ImmutableSortedSet<T>>() != null);
if (comparer == null)
{
comparer = Comparer<T>.Default;
{
var result = new ImmutableSortedSet<T>(Node.EmptyNode, comparer);
result = result.Union(this);
+ Debug.Assert(result != null);
return result;
}
}
private ImmutableSortedSet<T> UnionIncremental(IEnumerable<T> items)
{
Requires.NotNull(items, nameof(items));
- Contract.Ensures(Contract.Result<ImmutableSortedSet<T>>() != null);
// Let's not implement in terms of ImmutableSortedSet.Add so that we're
// not unnecessarily generating a new wrapping set object for each item.
private ImmutableSortedSet<T> LeafToRootRefill(IEnumerable<T> addedItems)
{
Requires.NotNull(addedItems, nameof(addedItems));
- Contract.Ensures(Contract.Result<ImmutableSortedSet<T>>() != null);
// Rather than build up the immutable structure in the incremental way,
// build it in such a way as to generate minimal garbage, by assembling
public static IImmutableStack<T> Pop<T>(this IImmutableStack<T> stack, out T value)
{
Requires.NotNull(stack, nameof(stack));
- Contract.Ensures(Contract.Result<IImmutableStack<T>>() != null);
value = stack.Peek();
return stack.Pop();
{
get
{
- Contract.Ensures(Contract.Result<ImmutableStack<T>>() != null);
- Contract.Ensures(Contract.Result<ImmutableStack<T>>().IsEmpty);
- Contract.Assume(s_EmptyField.IsEmpty);
+ Debug.Assert(s_EmptyField.IsEmpty);
return s_EmptyField;
}
}
/// </summary>
public ImmutableStack<T> Clear()
{
- Contract.Ensures(Contract.Result<ImmutableStack<T>>() != null);
- Contract.Ensures(Contract.Result<ImmutableStack<T>>().IsEmpty);
- Contract.Assume(s_EmptyField.IsEmpty);
+ Debug.Assert(s_EmptyField.IsEmpty);
return Empty;
}
[Pure]
public ImmutableStack<T> Push(T value)
{
- Contract.Ensures(Contract.Result<ImmutableStack<T>>() != null);
- Contract.Ensures(!Contract.Result<ImmutableStack<T>>().IsEmpty);
return new ImmutableStack<T>(value, this);
}
[Pure]
public ImmutableStack<T> Pop()
{
- Contract.Ensures(Contract.Result<ImmutableStack<T>>() != null);
if (this.IsEmpty)
{
throw new InvalidOperationException(SR.InvalidEmptyOperation);
}
+ Debug.Assert(_tail != null);
return _tail;
}
[Pure]
internal ImmutableStack<T> Reverse()
{
- Contract.Ensures(Contract.Result<ImmutableStack<T>>() != null);
- Contract.Ensures(Contract.Result<ImmutableStack<T>>().IsEmpty == this.IsEmpty);
-
var r = this.Clear();
for (ImmutableStack<T> f = this; !f.IsEmpty; f = f.Pop())
{
r = r.Push(f.Peek());
}
+ Debug.Assert(r != null);
+ Debug.Assert(r.IsEmpty == IsEmpty);
return r;
}
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-
-// ReSharper disable CheckNamespace
-
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.Contracts;
namespace System.Linq
-// ReSharper restore CheckNamespace
{
/// <summary>
/// LINQ extension method overrides that offer greater efficiency for <see cref="ImmutableArray{T}"/> than the standard LINQ methods
}
}
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Thread safety problems with precondition - can't express the precondition as of Dev10.
public override object Dequeue()
{
lock (_root)
}
}
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Thread safety problems with precondition - can't express the precondition as of Dev10.
public override object Peek()
{
lock (_root)
}
}
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
public override object GetByIndex(int index)
{
lock (_root)
}
}
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
public override object GetKey(int index)
{
lock (_root)
}
}
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
public override int IndexOfValue(object value)
{
lock (_root)
}
}
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
public override void RemoveAt(int index)
{
lock (_root)
}
}
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
public override void SetByIndex(int index, object value)
{
lock (_root)
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Globalization;
using System.Reflection;
{
NotNull(values, parameterName);
NotNullElements(values, parameterName);
- Contract.EndContractBlock();
}
[DebuggerStepThrough]
where TValue : class
{
NotNullElements(values, parameterName);
- Contract.EndContractBlock();
}
[DebuggerStepThrough]
where T : class
{
NotNullElements(values, parameterName);
- Contract.EndContractBlock();
}
[DebuggerStepThrough]
private static void NotNullElements<T>(IEnumerable<T> values, string parameterName)
where T : class
{
- if (values != null && !Contract.ForAll(values, (value) => value != null))
+ if (values != null)
{
- throw ExceptionBuilder.CreateContainsNullElement(parameterName);
+ foreach (T value in values)
+ {
+ if (value is null)
+ {
+ throw ExceptionBuilder.CreateContainsNullElement(parameterName);
+ }
+ }
}
- Contract.EndContractBlock();
}
[DebuggerStepThrough]
where TKey : class
where TValue : class
{
- if (values != null && !Contract.ForAll(values, (keyValue) => keyValue.Key != null && keyValue.Value != null))
+ if (values != null)
{
- throw ExceptionBuilder.CreateContainsNullElement(parameterName);
+ foreach (KeyValuePair<TKey, TValue> keyValue in values)
+ {
+ if (keyValue.Key is null || keyValue.Value is null)
+ {
+ throw ExceptionBuilder.CreateContainsNullElement(parameterName);
+ }
+ }
}
- Contract.EndContractBlock();
}
[DebuggerStepThrough]
{
throw new ArgumentException(SR.Format(SR.ArgumentOutOfRange_InvalidEnumInSet, parameterName, value, enumFlagSet.ToString()), parameterName);
}
- Contract.EndContractBlock();
}
public static void NotNull<T>(T value, string parameterName)
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using System.ComponentModel.Composition.ReflectionModel;
+using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
-using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection;
using Microsoft.Internal;
public static TMetadataView GetMetadataView<TMetadataView>(IDictionary<string, object> metadata)
{
Requires.NotNull(metadata, nameof(metadata));
- Contract.Ensures(Contract.Result<TMetadataView>() != null);
return MetadataViewProvider.GetMetadataView<TMetadataView>(metadata);
}
public static ComposablePart CreatePart(object attributedPart)
{
Requires.NotNull(attributedPart, nameof(attributedPart));
- Contract.Ensures(Contract.Result<ComposablePart>() != null);
return AttributedModelDiscovery.CreatePart(attributedPart);
}
{
Requires.NotNull(attributedPart, nameof(attributedPart));
Requires.NotNull(reflectionContext, nameof(reflectionContext));
- Contract.Ensures(Contract.Result<ComposablePart>() != null);
return AttributedModelDiscovery.CreatePart(attributedPart, reflectionContext);
}
{
Requires.NotNull(partDefinition, nameof(partDefinition));
Requires.NotNull(attributedPart, nameof(attributedPart));
- Contract.Ensures(Contract.Result<ComposablePart>() != null);
var reflectionComposablePartDefinition = partDefinition as ReflectionComposablePartDefinition;
if(reflectionComposablePartDefinition == null)
public static ComposablePartDefinition CreatePartDefinition(Type type, ICompositionElement origin)
{
Requires.NotNull(type, nameof(type));
- Contract.Ensures(Contract.Result<ComposablePartDefinition>() != null);
return AttributedModelServices.CreatePartDefinition(type, origin, false);
}
public static string GetTypeIdentity(Type type)
{
Requires.NotNull(type, nameof(type));
- Contract.Ensures(!string.IsNullOrEmpty(Contract.Result<string>()));
return ContractNameServices.GetTypeIdentity(type);
}
public static string GetTypeIdentity(MethodInfo method)
{
Requires.NotNull(method, nameof(method));
- Contract.Ensures(!string.IsNullOrEmpty(Contract.Result<string>()));
return ContractNameServices.GetTypeIdentityFromMethod(method);
}
public static string GetContractName(Type type)
{
Requires.NotNull(type, nameof(type));
- Contract.Ensures(!string.IsNullOrEmpty(Contract.Result<string>()));
return AttributedModelServices.GetTypeIdentity(type);
}
public static ComposablePart AddExportedValue<T>(this CompositionBatch batch, T exportedValue)
{
Requires.NotNull(batch, nameof(batch));
- Contract.Ensures(Contract.Result<ComposablePart>() != null);
string contractName = AttributedModelServices.GetContractName(typeof(T));
public static ComposablePart AddExportedValue<T>(this CompositionBatch batch, string contractName, T exportedValue)
{
Requires.NotNull(batch, nameof(batch));
- Contract.Ensures(Contract.Result<ComposablePart>() != null);
string typeIdentity = AttributedModelServices.GetTypeIdentity(typeof(T));
{
Requires.NotNull(batch, nameof(batch));
Requires.NotNull(attributedPart, nameof(attributedPart));
- Contract.Ensures(Contract.Result<ComposablePart>() != null);
ComposablePart part = AttributedModelServices.CreatePart(attributedPart);
batch.AddPart(part);
+ Debug.Assert(part != null);
return part;
}
{
Requires.NotNull(compositionService, nameof(compositionService));
Requires.NotNull(attributedPart, nameof(attributedPart));
- Contract.Ensures(Contract.Result<ComposablePart>() != null);
ComposablePart part = AttributedModelServices.CreatePart(attributedPart);
compositionService.SatisfyImportsOnce(part);
+ Debug.Assert(part != null);
return part;
}
Requires.NotNull(compositionService, nameof(compositionService));
Requires.NotNull(attributedPart, nameof(attributedPart));
Requires.NotNull(reflectionContext, nameof(reflectionContext));
- Contract.Ensures(Contract.Result<ComposablePart>() != null);
ComposablePart part = AttributedModelServices.CreatePart(attributedPart, reflectionContext);
compositionService.SatisfyImportsOnce(part);
+ Debug.Assert(part != null);
return part;
}
using System.Collections.Generic;
using System.ComponentModel.Composition.Primitives;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Linq;
using System.Threading;
using Microsoft.Internal;
get
{
ThrowIfDisposed();
- Contract.Ensures(Contract.Result<ICollection<ComposablePartCatalog>>() != null);
+ Debug.Assert(_catalogs != null);
return _catalogs;
}
using System.Collections.ObjectModel;
using System.ComponentModel.Composition.Primitives;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Linq;
using System.Threading;
using Microsoft.Internal.Collections;
get
{
ThrowIfDisposed();
- Contract.Ensures(Contract.Result<ReadOnlyCollection<ExportProvider>>() != null);
+ Debug.Assert(_readOnlyProviders != null);
return _readOnlyProviders;
}
using System.ComponentModel.Composition.Primitives;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
-using System.Diagnostics.Contracts;
using System.Globalization;
using System.IO;
using System.Reflection;
}
[DebuggerStepThrough]
- [ContractArgumentValidator]
- [SuppressMessage("Microsoft.Contracts", "CC1053", Justification = "Suppressing warning because this validator has no public contract")]
private void ThrowIfDisposed()
{
if (_isDisposed)
using System.ComponentModel.Composition.Primitives;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
-using System.Diagnostics.Contracts;
using System.Globalization;
using System.IO;
using System.Reflection;
{
get
{
- Contract.Ensures(Contract.Result<Assembly>() != null);
+ Debug.Assert(_assembly != null);
return _assembly;
}
using System.ComponentModel.Composition.ReflectionModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
-using System.Diagnostics.Contracts;
using System.Globalization;
using System.Linq;
using System.Runtime.CompilerServices;
get
{
ThrowIfDisposed();
- Contract.Ensures(Contract.Result<ComposablePartCatalog>() != null);
+ Debug.Assert(_catalog != null);
return _catalog;
}
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
+using System.Diagnostics;
using System.ComponentModel.Composition.Primitives;
-using System.Diagnostics.Contracts;
using Microsoft.Internal;
using Microsoft.Internal.Collections;
{
get
{
- Contract.Ensures(Contract.Result<IEnumerable<ComposablePartDefinition>>() != null);
+ Debug.Assert(_addedDefinitions != null);
return _addedDefinitions;
}
{
get
{
- Contract.Ensures(Contract.Result<IEnumerable<ComposablePartDefinition>>() != null);
-
+ Debug.Assert(_removedDefinitions != null);
+
return _removedDefinitions;
}
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Diagnostics;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.Composition.Primitives;
-using System.Diagnostics.Contracts;
using Microsoft.Internal;
namespace System.ComponentModel.Composition.Hosting
{
get
{
- Contract.Ensures(Contract.Result<ReadOnlyCollection<ComposablePart>>() != null);
-
lock (_lock)
{
_copyNeededForAdd = true;
+ Debug.Assert(_readOnlyPartsToAdd != null);
return _readOnlyPartsToAdd;
}
}
{
get
{
- Contract.Ensures(Contract.Result <ReadOnlyCollection<ComposablePart>>() != null);
-
lock (_lock)
{
_copyNeededForRemove = true;
+ Debug.Assert(_readOnlyPartsToRemove != null);
return _readOnlyPartsToRemove;
}
}
public ComposablePart AddExport(Export export)
{
Requires.NotNull(export, nameof(export));
- Contract.Ensures(Contract.Result<ComposablePart>() != null);
ComposablePart part = new SingleExportComposablePart(export);
using System.ComponentModel.Composition.Primitives;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
-using System.Diagnostics.Contracts;
using System.Threading;
using Microsoft.Internal;
get
{
ThrowIfDisposed();
- Contract.Ensures(Contract.Result<ReadOnlyCollection<ExportProvider>>() != null);
+ Debug.Assert(_providers != null);
return _providers;
}
using System.ComponentModel.Composition.Primitives;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
-using System.Diagnostics.Contracts;
using System.Globalization;
using System.IO;
using System.Linq;
{
get
{
- Contract.Ensures(Contract.Result<string>() != null);
-
+ Debug.Assert(_fullPath != null);
+
return _fullPath;
}
}
{
get
{
- Contract.Ensures(Contract.Result<ReadOnlyCollection<string>>() != null);
-
using (new ReadLock(_thisLock))
{
+ Debug.Assert(_loadedFiles != null);
return _loadedFiles;
}
}
{
get
{
- Contract.Ensures(Contract.Result<string>() != null);
-
+ Debug.Assert(_path != null);
+
return _path;
}
}
using System.Collections.Generic;
using System.ComponentModel.Composition.Primitives;
-using System.Diagnostics.Contracts;
+using System.Diagnostics;
using System.Globalization;
using Microsoft.Internal;
public IEnumerable<Export> GetExports(ImportDefinition definition, AtomicComposition atomicComposition)
{
Requires.NotNull(definition, nameof(definition));
- Contract.Ensures(Contract.Result<IEnumerable<Export>>() != null);
IEnumerable<Export> exports;
ExportCardinalityCheckResult result = TryGetExportsCore(definition, atomicComposition, out exports);
switch(result)
{
case ExportCardinalityCheckResult.Match:
+ Debug.Assert(exports != null);
return exports;
case ExportCardinalityCheckResult.NoExports:
throw new ImportCardinalityMismatchException(SR.Format(SR.CardinalityMismatch_NoExports, definition));
using System.Collections.Generic;
using System.ComponentModel.Composition.Primitives;
-using System.Diagnostics.Contracts;
+using System.Diagnostics;
using System.Linq;
using Microsoft.Internal;
using Microsoft.Internal.Collections;
{
get
{
- Contract.Ensures(Contract.Result<IEnumerable<ExportDefinition>>() != null);
+ Debug.Assert(_addedExports != null);
return _addedExports;
}
{
get
{
- Contract.Ensures(Contract.Result<IEnumerable<ExportDefinition>>() != null);
+ Debug.Assert(_removedExports != null);
return _removedExports;
}
using System.Collections.Generic;
using System.ComponentModel.Composition.Primitives;
-using System.Diagnostics.Contracts;
+using System.Diagnostics;
using System.Linq.Expressions;
using Microsoft.Internal;
{
get
{
- Contract.Ensures(Contract.Result<IDictionary<string, object>>() != null);
-
var reply = _metadata;
if(reply == null)
{
_metadata = reply;
}
+ Debug.Assert(reply != null);
return reply;
}
}
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
-using System.Diagnostics.Contracts;
using System.Linq;
using System.Threading;
using Microsoft.Internal;
ThrowIfDisposed();
Requires.NotNull(definition, nameof(definition));
- Contract.Ensures(Contract.Result<IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>>>() != null);
List<Tuple<ComposablePartDefinition, ExportDefinition>> exports = null;
var candidateParts = GetCandidateParts(definition);
}
}
+ Debug.Assert(exports != null || _EmptyExportsList != null);
return exports ?? _EmptyExportsList;
}
using System.Collections.Generic;
using System.ComponentModel.Composition.Hosting;
+using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
-using System.Diagnostics.Contracts;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
{
get
{
- Contract.Ensures(Contract.Result<IEnumerable<KeyValuePair<string, Type>>>() != null);
-
// NOTE : unlike other arguments, we validate this one as late as possible, because its validation may lead to type loading
ValidateRequiredMetadata();
+ Debug.Assert(_requiredMetadata != null);
return _requiredMetadata;
}
}
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
-using System.Diagnostics.Contracts;
using System.Threading;
using Microsoft.Internal;
{
get
{
- Contract.Ensures(Contract.Result<ExportDefinition>() != null);
-
if (_definition != null)
{
return _definition;
{
get
{
- Contract.Ensures(Contract.Result<IDictionary<string, object>>() != null);
+ Debug.Assert(Definition.Metadata != null);
return Definition.Metadata;
}
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
-using System.Diagnostics.Contracts;
+using System.Diagnostics;
using Microsoft.Internal;
namespace System.ComponentModel.Composition.Primitives
{
get
{
- Contract.Ensures(!string.IsNullOrEmpty(Contract.Result<string>()));
-
if (_contractName != null)
{
return _contractName;
{
get
{
- Contract.Ensures(Contract.Result<IDictionary<string, object>>() != null);
+ Debug.Assert(_metadata != null);
return _metadata;
}
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
-using System.Diagnostics.Contracts;
+using System.Diagnostics;
using System.Globalization;
using System.Linq.Expressions;
using Microsoft.Internal;
{
get
{
- Contract.Ensures(Contract.Result<string>() != null);
+ Debug.Assert(_contractName != null);
return _contractName;
}
{
get
{
- Contract.Ensures(Contract.Result<IDictionary<string, object>>() != null);
+ Debug.Assert(_metadata != null);
return _metadata;
}
{
get
{
- Contract.Ensures(Contract.Result<Expression<Func<ExportDefinition, bool>>>() != null);
-
if (_constraint != null)
{
return _constraint;
using System.Collections.Generic;
using System.ComponentModel.Composition.Primitives;
+using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
-using System.Diagnostics.Contracts;
using System.Globalization;
using System.Linq;
using System.Reflection;
public static Lazy<Type> GetPartType(ComposablePartDefinition partDefinition)
{
Requires.NotNull(partDefinition, nameof(partDefinition));
- Contract.Ensures(Contract.Result<Lazy<Type>>() != null);
ReflectionComposablePartDefinition reflectionPartDefinition = partDefinition as ReflectionComposablePartDefinition;
if (reflectionPartDefinition == null)
public static Lazy<ParameterInfo> GetImportingParameter(ImportDefinition importDefinition)
{
Requires.NotNull(importDefinition, nameof(importDefinition));
- Contract.Ensures(Contract.Result<Lazy<ParameterInfo>>() != null);
ReflectionParameterImportDefinition reflectionParameterImportDefinition = importDefinition as ReflectionParameterImportDefinition;
if (reflectionParameterImportDefinition == null)
nameof(importDefinition));
}
+ Debug.Assert(reflectionParameterImportDefinition.ImportingLazyParameter != null);
return reflectionParameterImportDefinition.ImportingLazyParameter;
}
public static ContractBasedImportDefinition GetExportFactoryProductImportDefinition(ImportDefinition importDefinition)
{
Requires.NotNull(importDefinition, nameof(importDefinition));
- Contract.Ensures(Contract.Result<ContractBasedImportDefinition>() != null);
IPartCreatorImportDefinition partCreatorImportDefinition = importDefinition as IPartCreatorImportDefinition;
if (partCreatorImportDefinition == null)
ICompositionElement origin)
{
Requires.NotNull(partType, nameof(partType));
- Contract.Ensures(Contract.Result<ComposablePartDefinition>() != null);
return new ReflectionComposablePartDefinition(
new ReflectionPartCreationInfo(
{
Requires.NotNullOrEmpty(contractName, nameof(contractName));
Requires.IsInMembertypeSet(exportingMember.MemberType, nameof(exportingMember), MemberTypes.Field | MemberTypes.Property | MemberTypes.NestedType | MemberTypes.TypeInfo | MemberTypes.Method);
- Contract.Ensures(Contract.Result<ExportDefinition>() != null);
return new ReflectionMemberExportDefinition(
exportingMember,
{
Requires.NotNullOrEmpty(contractName, nameof(contractName));
Requires.IsInMembertypeSet(importingMember.MemberType, nameof(importingMember), MemberTypes.Property | MemberTypes.Field);
- Contract.Ensures(Contract.Result<ContractBasedImportDefinition>() != null);
if (isExportFactory)
{
{
Requires.NotNull(parameter, nameof(parameter));
Requires.NotNullOrEmpty(contractName, nameof(contractName));
- Contract.Ensures(Contract.Result<ContractBasedImportDefinition>() != null);
if (isExportFactory)
{
using System.Globalization;
using System.Linq.Expressions;
using Microsoft.Internal;
-using System.Diagnostics.Contracts;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.Composition.Primitives;
{
get
{
- Contract.Ensures(Contract.Result<IDictionary<string, object>>() != null);
-
var reply = this._metadata;
if(reply == null)
{
using System.Threading.Tasks;
using System.IO;
using System.Net.Http.Headers;
-using System.Diagnostics.Contracts;
namespace System.Net.Http
{
{
throw new ArgumentNullException(nameof(nameValueCollection));
}
- Contract.EndContractBlock();
// Encode and concatenate data
StringBuilder builder = new StringBuilder();
using System.Collections.Generic;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Globalization;
using System.IO;
using System.Net.Mail;
// Since we never re-use a "found" value in 'y', we expect 'alreadyFound' to have all fields set to 'true'.
// Otherwise the two collections can't be equal and we should not get here.
- Debug.Assert(Contract.ForAll(alreadyFound, value => { return value; }),
+ Debug.Assert(Array.TrueForAll(alreadyFound, value => value),
"Expected all values in 'alreadyFound' to be true since collections are considered equal.");
return true;
using System.Collections;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
namespace System.Net.Http.Headers
{
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
-using System.Diagnostics.Contracts;
using System.Text;
namespace System.Net.Http.Headers
private HeaderStoreItemInfo GetOrCreateHeaderInfo(HeaderDescriptor descriptor, bool parseRawValues)
{
- Contract.Ensures(Contract.Result<HeaderStoreItemInfo>() != null);
-
HeaderStoreItemInfo result = null;
bool found = false;
if (parseRawValues)
result = CreateAndAddHeaderToStore(descriptor);
}
+ Debug.Assert(result != null);
return result;
}
private static string[] GetValuesAsStrings(HeaderDescriptor descriptor, HeaderStoreItemInfo info, object exclude = null)
{
- Contract.Ensures(Contract.Result<string[]>() != null);
-
int length = GetValueCount(info);
string[] values;
values = Array.Empty<string>();
}
+ Debug.Assert(values != null);
return values;
}
using System.Collections.Generic;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Globalization;
namespace System.Net.Http.Headers
{
Debug.Assert(rangeCollection != null);
Debug.Assert(startIndex >= 0);
- Contract.Ensures((Contract.Result<int>() == 0) || (rangeCollection.Count > 0),
- "If we can parse the string, then we expect to have at least one range item.");
if ((string.IsNullOrEmpty(input)) || (startIndex >= input.Length))
{
using System.Buffers;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.IO;
using System.Net.Http.Headers;
using System.Text;
private MemoryStream CreateMemoryStream(long maxBufferSize, out Exception error)
{
- Contract.Ensures((Contract.Result<MemoryStream>() != null) ||
- (Contract.ValueAtReturn<Exception>(out error) != null));
-
error = null;
// If we have a Content-Length allocate the right amount of buffer up-front. Also check whether the
internal static int GetTokenLength(string input, int startIndex)
{
Debug.Assert(input != null);
- Contract.Ensures((Contract.Result<int>() >= 0) && (Contract.Result<int>() <= (input.Length - startIndex)));
if (startIndex >= input.Length)
{
internal static int GetWhitespaceLength(string input, int startIndex)
{
Debug.Assert(input != null);
- Contract.Ensures((Contract.Result<int>() >= 0) && (Contract.Result<int>() <= (input.Length - startIndex)));
if (startIndex >= input.Length)
{
{
Debug.Assert(input != null);
Debug.Assert((startIndex >= 0) && (startIndex < input.Length));
- Contract.Ensures((Contract.Result<int>() >= 0) && (Contract.Result<int>() <= (input.Length - startIndex)));
int current = startIndex;
char c;
{
Debug.Assert(input != null);
Debug.Assert(startIndex >= 0);
- Contract.Ensures((Contract.Result<int>() >= 0) && (Contract.Result<int>() <= (input.Length - startIndex)));
host = null;
if (startIndex >= input.Length)
{
Debug.Assert(input != null);
Debug.Assert((startIndex >= 0) && (startIndex < input.Length));
- Contract.Ensures((Contract.ValueAtReturn(out length) >= 0) &&
- (Contract.ValueAtReturn(out length) <= (input.Length - startIndex)));
length = 0;
{
Debug.Assert(input != null);
Debug.Assert((startIndex >= 0) && (startIndex < input.Length));
- Contract.Ensures((Contract.Result<HttpParseResult>() != HttpParseResult.Parsed) ||
- (Contract.ValueAtReturn<int>(out length) > 0));
length = 0;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
-using System.Diagnostics.Contracts;
using System.IO;
using System.Net.Http.Headers;
using System.Text;
{
throw new ArgumentException(SR.net_http_argument_empty_string, nameof(subtype));
}
- Contract.EndContractBlock();
ValidateBoundary(boundary);
_boundary = boundary;
{
throw new ArgumentException(SR.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, boundary), nameof(boundary));
}
- Contract.EndContractBlock();
const string AllowedMarks = @"'()+_,-./:=? ";
{
throw new ArgumentNullException(nameof(content));
}
- Contract.EndContractBlock();
_nestedContent.Add(content);
}
// See the LICENSE file in the project root for more information.
using System.Diagnostics.CodeAnalysis;
-using System.Diagnostics.Contracts;
using System.Net.Http.Headers;
namespace System.Net.Http
{
throw new ArgumentNullException(nameof(content));
}
- Contract.EndContractBlock();
if (content.Headers.ContentDisposition == null)
{
{
throw new ArgumentException(SR.net_http_argument_empty_string, nameof(name));
}
- Contract.EndContractBlock();
AddInternal(content, name, null);
}
{
throw new ArgumentException(SR.net_http_argument_empty_string, nameof(fileName));
}
- Contract.EndContractBlock();
AddInternal(content, name, fileName);
}
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.IO;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Runtime.InteropServices;
{
Debug.Assert(stream != null);
Debug.Assert(stream.CanRead || stream.CanWrite || stream.CanSeek);
- Contract.EndContractBlock();
-
Debug.Assert(!stream.CanRead || (stream.CanRead && this is IInputStream));
Debug.Assert(!stream.CanWrite || (stream.CanWrite && this is IOutputStream));
Debug.Assert(!stream.CanSeek || (stream.CanSeek && this is IRandomAccessStream));
throw ex;
}
- // Commented due to a reported CCRewrite bug. Should uncomment when fixed:
- //Contract.Ensures(Contract.Result<IAsyncOperationWithProgress<IBuffer, UInt32>>() != null);
- //Contract.EndContractBlock();
-
Stream str = EnsureNotDisposed();
IAsyncOperationWithProgress<IBuffer, uint> readAsyncOperation;
throw ex;
}
- // Commented due to a reported CCRewrite bug. Should uncomment when fixed:
- //Contract.Ensures(Contract.Result<IAsyncOperationWithProgress<UInt32, UInt32>>() != null);
- //Contract.EndContractBlock();
-
Stream str = EnsureNotDisposed();
return StreamOperationsImplementation.WriteAsync_AbstractStream(str, buffer);
}
public IAsyncOperation<bool> FlushAsync()
{
- Contract.Ensures(Contract.Result<IAsyncOperation<Boolean>>() != null);
- Contract.EndContractBlock();
-
Stream str = EnsureNotDisposed();
return StreamOperationsImplementation.FlushAsync_AbstractStream(str);
}
throw ex;
}
- // Commented due to a reported CCRewrite bug. Should uncomment when fixed:
- //Contract.EndContractBlock();
-
Stream str = EnsureNotDisposed();
long pos = unchecked((long)position);
{
get
{
- Contract.Ensures(Contract.Result<UInt64>() >= 0);
-
Stream str = EnsureNotDisposed();
return (ulong)str.Position;
}
{
get
{
- Contract.Ensures(Contract.Result<UInt64>() >= 0);
-
Stream str = EnsureNotDisposed();
return (ulong)str.Length;
}
throw ex;
}
- // Commented due to a reported CCRewrite bug. Should uncomment when fixed:
- //Contract.EndContractBlock();
-
Stream str = EnsureNotDisposed();
if (!str.CanWrite)
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.IO;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Runtime.InteropServices;
Debug.Assert(0 <= count);
Debug.Assert(count <= int.MaxValue);
Debug.Assert(count <= buffer.Capacity);
- Contract.EndContractBlock();
// We will return a different buffer to the user backed directly by the memory stream (avoids memory copy).
// This is permitted by the WinRT stream contract.
Debug.Assert(count <= int.MaxValue);
Debug.Assert(count <= buffer.Capacity);
Debug.Assert(options == InputStreamOptions.None || options == InputStreamOptions.Partial || options == InputStreamOptions.ReadAhead);
- Contract.EndContractBlock();
int bytesRequested = (int)count;
Debug.Assert(stream != null);
Debug.Assert(stream.CanWrite);
Debug.Assert(buffer != null);
- Contract.EndContractBlock();
// Choose the optimal writing strategy for the kind of buffer supplied:
Func<CancellationToken, IProgress<uint>, Task<uint>> writeOperation;
{
Debug.Assert(stream != null);
Debug.Assert(stream.CanWrite);
- Contract.EndContractBlock();
Func<CancellationToken, Task<bool>> flushOperation = async (cancelToken) =>
{
(winRtStream is IRandomAccessStream && !((IRandomAccessStream)winRtStream).CanWrite)
))
);
- Contract.EndContractBlock();
_winRtStream = winRtStream;
_canRead = canRead;
{
if (value < 0)
throw new ArgumentOutOfRangeException("Position", SR.ArgumentOutOfRange_IO_CannotSeekToNegativePosition);
- Contract.EndContractBlock();
IRandomAccessStream wrtStr = EnsureNotDisposed<IRandomAccessStream>();
{
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_CannotResizeStreamToNegative);
- Contract.EndContractBlock();
IRandomAccessStream wrtStr = EnsureNotDisposed<IRandomAccessStream>();
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InsufficientSpaceInTargetBuffer);
- Contract.EndContractBlock();
-
IInputStream wrtStr = EnsureNotDisposed<IInputStream>();
EnsureCanRead();
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
- Contract.EndContractBlock();
-
EnsureNotDisposed();
EnsureCanRead();
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InsufficientSpaceInTargetBuffer);
- Contract.EndContractBlock();
-
EnsureNotDisposed();
EnsureCanRead();
public override int ReadByte()
{
- Contract.Ensures(Contract.Result<int>() >= -1);
- Contract.Ensures(Contract.Result<int>() < 256);
- Contract.EndContractBlock();
-
// EnsureNotDisposed will be called in Read->BeginRead.
byte[] oneByteArray = OneByteBuffer;
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset);
- Contract.EndContractBlock();
-
IOutputStream wrtStr = EnsureNotDisposed<IOutputStream>();
EnsureCanWrite();
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
- Contract.EndContractBlock();
-
EnsureNotDisposed();
EnsureCanWrite();
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset);
- Contract.EndContractBlock();
-
IOutputStream wrtStr = EnsureNotDisposed<IOutputStream>();
EnsureCanWrite();
using System.ComponentModel;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_WinRtAdapterBufferSizeMayNotBeNegative);
Debug.Assert(!string.IsNullOrWhiteSpace(invokedMethodName));
- Contract.Ensures(Contract.Result<Stream>() != null);
- Contract.EndContractBlock();
// If the WinRT stream is actually a wrapped managed stream, we will unwrap it and return the original.
// In that case we do not need to put the wrapper into the map.
Debug.Assert(bufferSize >= 0);
Debug.Assert(!string.IsNullOrWhiteSpace(invokedMethodName));
- Contract.Ensures(Contract.Result<Stream>() != null);
- Contract.EndContractBlock();
-
// Get the adapter for this windowsRuntimeStream again (it may have been created concurrently).
// If none exists yet, create a new one:
Stream adapter = (bufferSize == 0)
if (!stream.CanRead)
throw new NotSupportedException(SR.NotSupported_CannotConvertNotReadableToInputStream);
- Contract.Ensures(Contract.Result<IInputStream>() != null);
- Contract.EndContractBlock();
-
object adapter = AsWindowsRuntimeStreamInternal(stream);
IInputStream winRtStream = adapter as IInputStream;
if (!stream.CanWrite)
throw new NotSupportedException(SR.NotSupported_CannotConvertNotWritableToOutputStream);
- Contract.Ensures(Contract.Result<IOutputStream>() != null);
- Contract.EndContractBlock();
-
object adapter = AsWindowsRuntimeStreamInternal(stream);
IOutputStream winRtStream = adapter as IOutputStream;
if (!stream.CanSeek)
throw new NotSupportedException(SR.NotSupported_CannotConvertNotSeekableToRandomAccessStream);
- Contract.Ensures(Contract.Result<IRandomAccessStream>() != null);
- Contract.EndContractBlock();
-
object adapter = AsWindowsRuntimeStreamInternal(stream);
IRandomAccessStream winRtStream = adapter as IRandomAccessStream;
private static object AsWindowsRuntimeStreamInternal(Stream stream)
{
- Contract.Ensures(Contract.Result<Object>() != null);
- Contract.EndContractBlock();
-
// Check to see if the managed stream is actually a wrapper of a WinRT stream:
// (This can be either an adapter directly, or an adapter wrapped in a BufferedStream.)
WinRtToNetFxStreamAdapter sAdptr = stream as WinRtToNetFxStreamAdapter;
private static NetFxToWinRtStreamAdapter AsWindowsRuntimeStreamInternalFactoryHelper(Stream stream)
{
Debug.Assert(stream != null);
- Contract.Ensures(Contract.Result<NetFxToWinRtStreamAdapter>() != null);
- Contract.EndContractBlock();
// Get the adapter for managed stream again (it may have been created concurrently).
// If none exists yet, create a new one:
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
if (taskProvider == null)
throw new ArgumentNullException(nameof(taskProvider));
- Contract.EndContractBlock();
-
return new TaskToAsyncActionAdapter(taskProvider);
}
if (taskProvider == null)
throw new ArgumentNullException(nameof(taskProvider));
- Contract.EndContractBlock();
-
return new TaskToAsyncActionWithProgressAdapter<TProgress>(taskProvider);
}
if (taskProvider == null)
throw new ArgumentNullException(nameof(taskProvider));
- Contract.EndContractBlock();
-
return new TaskToAsyncOperationAdapter<TResult>(taskProvider);
}
if (taskProvider == null)
throw new ArgumentNullException(nameof(taskProvider));
- Contract.EndContractBlock();
-
return new TaskToAsyncOperationWithProgressAdapter<TResult, TProgress>(taskProvider);
}
{
if (error == null)
throw new ArgumentNullException(nameof(error));
- Contract.EndContractBlock();
var asyncInfo = new TaskToAsyncActionAdapter(isCanceled: false);
{
if (error == null)
throw new ArgumentNullException(nameof(error));
- Contract.EndContractBlock();
var asyncInfo = new TaskToAsyncActionWithProgressAdapter<TProgress>(isCanceled: false);
{
if (error == null)
throw new ArgumentNullException(nameof(error));
- Contract.EndContractBlock();
var asyncInfo = new TaskToAsyncOperationAdapter<TResult>(default(TResult));
{
if (error == null)
throw new ArgumentNullException(nameof(error));
- Contract.EndContractBlock();
var asyncInfo = new TaskToAsyncOperationWithProgressAdapter<TResult, TProgress>(default(TResult));
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
{
if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity));
- Contract.Ensures(Contract.Result<IBuffer>() != null);
- Contract.Ensures(Contract.Result<IBuffer>().Length == unchecked((uint)0));
- Contract.Ensures(Contract.Result<IBuffer>().Capacity == unchecked((uint)capacity));
- Contract.EndContractBlock();
-
return new WindowsRuntimeBuffer(capacity);
}
if (data.Length - offset < capacity) throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset);
if (capacity < length) throw new ArgumentException(SR.Argument_InsufficientBufferCapacity);
- Contract.Ensures(Contract.Result<IBuffer>() != null);
- Contract.Ensures(Contract.Result<IBuffer>().Length == unchecked((uint)length));
- Contract.Ensures(Contract.Result<IBuffer>().Capacity == unchecked((uint)capacity));
-
- Contract.EndContractBlock();
-
byte[] underlyingData = new byte[capacity];
Buffer.BlockCopy(data, offset, underlyingData, 0, length);
return new WindowsRuntimeBuffer(underlyingData, 0, length, capacity);
if (capacity < 0)
throw new ArgumentOutOfRangeException(nameof(capacity));
- Contract.EndContractBlock();
-
_data = new byte[capacity];
_dataStartOffs = 0;
_usefulDataLength = 0;
if (data.Length - offset < length) throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset);
if (data.Length - offset < capacity) throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset);
if (capacity < length) throw new ArgumentException(SR.Argument_InsufficientBufferCapacity);
- Contract.EndContractBlock();
_data = data;
_dataStartOffs = offset;
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System.Diagnostics.Contracts;
using System.Diagnostics;
using System.IO;
using Windows.Foundation;
{
if (source == null) throw new ArgumentNullException(nameof(source));
- Contract.Ensures(Contract.Result<IBuffer>() != null);
- Contract.Ensures(Contract.Result<IBuffer>().Length == unchecked((uint)source.Length));
- Contract.Ensures(Contract.Result<IBuffer>().Capacity == unchecked((uint)source.Length));
- Contract.EndContractBlock();
-
return AsBuffer(source, 0, source.Length, source.Length);
}
if (length < 0) throw new ArgumentOutOfRangeException(nameof(length));
if (source.Length - offset < length) throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset);
- Contract.Ensures(Contract.Result<IBuffer>() != null);
- Contract.Ensures(Contract.Result<IBuffer>().Length == unchecked((uint)length));
- Contract.Ensures(Contract.Result<IBuffer>().Capacity == unchecked((uint)length));
- Contract.EndContractBlock();
-
return AsBuffer(source, offset, length, length);
}
if (source.Length - offset < capacity) throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset);
if (capacity < length) throw new ArgumentException(SR.Argument_InsufficientBufferCapacity);
- Contract.Ensures(Contract.Result<IBuffer>() != null);
- Contract.Ensures(Contract.Result<IBuffer>().Length == unchecked((uint)length));
- Contract.Ensures(Contract.Result<IBuffer>().Capacity == unchecked((uint)capacity));
- Contract.EndContractBlock();
-
return new WindowsRuntimeBuffer(source, offset, length, capacity);
}
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (destination == null) throw new ArgumentNullException(nameof(destination));
- Contract.EndContractBlock();
CopyTo(source, 0, destination, 0, source.Length);
}
if (source.Length <= sourceIndex) throw new ArgumentException(SR.Argument_IndexOutOfArrayBounds, nameof(sourceIndex));
if (source.Length - sourceIndex < count) throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset);
if (destination.Capacity - destinationIndex < count) throw new ArgumentException(SR.Argument_InsufficientSpaceInTargetBuffer);
- Contract.EndContractBlock();
// If destination is backed by a managed array, use the array instead of the pointer as it does not require pinning:
byte[] destDataArr;
public static byte[] ToArray(this IBuffer source)
{
if (source == null) throw new ArgumentNullException(nameof(source));
- Contract.EndContractBlock();
return ToArray(source, 0, checked((int)source.Length));
}
if (count < 0) throw new ArgumentOutOfRangeException(nameof(count));
if (source.Capacity <= sourceIndex) throw new ArgumentException(SR.Argument_BufferIndexExceedsCapacity);
if (source.Capacity - sourceIndex < count) throw new ArgumentException(SR.Argument_InsufficientSpaceInSourceBuffer);
- Contract.EndContractBlock();
if (count == 0)
return Array.Empty<Byte>();
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (destination == null) throw new ArgumentNullException(nameof(destination));
- Contract.EndContractBlock();
CopyTo(source, 0, destination, 0, checked((int)source.Length));
}
if (source.Capacity - sourceIndex < count) throw new ArgumentException(SR.Argument_InsufficientSpaceInSourceBuffer);
if (destination.Length <= destinationIndex) throw new ArgumentException(SR.Argument_IndexOutOfArrayBounds);
if (destination.Length - destinationIndex < count) throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset);
- Contract.EndContractBlock();
// If source is backed by a managed array, use the array instead of the pointer as it does not require pinning:
byte[] srcDataArr;
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (destination == null) throw new ArgumentNullException(nameof(destination));
- Contract.EndContractBlock();
CopyTo(source, 0, destination, 0, source.Length);
}
if (source.Capacity - sourceIndex < count) throw new ArgumentException(SR.Argument_InsufficientSpaceInSourceBuffer);
if (destination.Capacity <= destinationIndex) throw new ArgumentException(SR.Argument_BufferIndexExceedsCapacity);
if (destination.Capacity - destinationIndex < count) throw new ArgumentException(SR.Argument_InsufficientSpaceInTargetBuffer);
- Contract.EndContractBlock();
// If source are destination are backed by managed arrays, use the arrays instead of the pointers as it does not require pinning:
byte[] srcDataArr, destDataArr;
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
- Contract.EndContractBlock();
-
WindowsRuntimeBuffer winRtBuffer = buffer as WindowsRuntimeBuffer;
if (winRtBuffer == null)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
- Contract.EndContractBlock();
-
if (otherBuffer == null)
return false;
if (underlyingStream == null)
throw new ArgumentNullException(nameof(underlyingStream));
- Contract.Ensures(Contract.Result<IBuffer>() != null);
- Contract.Ensures(Contract.Result<IBuffer>().Length == underlyingStream.Length);
- Contract.Ensures(Contract.Result<IBuffer>().Capacity == underlyingStream.Capacity);
-
- Contract.EndContractBlock();
ArraySegment<byte> streamData;
if (!underlyingStream.TryGetBuffer(out streamData))
{
if (underlyingStream.Capacity <= positionInStream)
throw new ArgumentException(SR.Argument_StreamPositionBeyondEOS);
- Contract.Ensures(Contract.Result<IBuffer>() != null);
- Contract.Ensures(Contract.Result<IBuffer>().Length == length);
- Contract.Ensures(Contract.Result<IBuffer>().Capacity == length);
-
- Contract.EndContractBlock();
ArraySegment<byte> streamData;
if (!underlyingStream.TryGetBuffer(out streamData))
if (source == null)
throw new ArgumentNullException(nameof(source));
- Contract.Ensures(Contract.Result<Stream>() != null);
- Contract.Ensures(Contract.Result<Stream>().Length == (uint)source.Capacity);
-
- Contract.EndContractBlock();
-
byte[] dataArr;
int dataOffs;
if (source.TryGetUnderlyingData(out dataArr, out dataOffs))
if (source == null) throw new ArgumentNullException(nameof(source));
if (source.Capacity <= byteOffset) throw new ArgumentException(SR.Argument_BufferIndexExceedsCapacity, nameof(byteOffset));
- Contract.EndContractBlock();
-
byte[] srcDataArr;
int srcDataOffs;
if (source.TryGetUnderlyingData(out srcDataArr, out srcDataOffs))
using Internal.Threading.Tasks;
using System.ComponentModel;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.WindowsRuntime;
if (asyncInfo == null)
throw new ArgumentNullException(nameof(asyncInfo));
- Contract.EndContractBlock();
-
AsyncCausalitySupport.RemoveFromActiveTasks(this.Task);
try
using Internal.Interop;
using Internal.Threading.Tasks;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using Windows.Foundation;
if (asyncInfo == null)
throw new ArgumentNullException(nameof(asyncInfo));
- Contract.EndContractBlock();
-
AsyncCausalitySupport.RemoveFromActiveTasks(this.Task);
try
|| (null != (taskProvider as Func<IProgress<TProgressInfo>, Task>))
|| (null != (taskProvider as Func<CancellationToken, IProgress<TProgressInfo>, Task>)));
- Contract.Ensures(!this.CompletedSynchronously);
-
- Contract.EndContractBlock();
-
// The IAsyncInfo is reasonably expected to be created/started by the same code that wires up the Completed and Progress handlers.
// Record the current SynchronizationContext so that we can invoke completion and progress callbacks in it later.
_startingContext = GetStartingContext();
if (underlyingTask.Status == TaskStatus.Created)
throw new InvalidOperationException(SR.InvalidOperation_UnstartedTaskSpecified);
- Contract.Ensures(!this.CompletedSynchronously);
-
- Contract.EndContractBlock();
-
// The IAsyncInfo is reasonably expected to be created/started by the same code that wires up the Completed and Progress handlers.
// Record the current SynchronizationContext so that we can invoke completion and progress callbacks in it later.
_startingContext = GetStartingContext();
/// <param name="synchronousResult">The result of this synchronously completed IAsyncInfo.</param>
internal TaskToAsyncInfoAdapter(TResult synchronousResult)
{
- Contract.Ensures(this.CompletedSynchronously);
- Contract.Ensures(this.IsInRunToCompletionState);
-
// We already completed. There will be no progress callback invokations and a potential completed handler invokation will be synchronous.
// We do not need the starting SynchronizationContext:
_startingContext = null;
get
{
EnsureNotClosed();
- Contract.Ensures(CompletedSynchronously || Contract.Result<Task>() != null);
- Contract.EndContractBlock();
if (CompletedSynchronously)
return null;
private Task InvokeTaskProvider(Delegate taskProvider)
{
- Contract.EndContractBlock();
-
var funcVoidTask = taskProvider as Func<Task>;
if (funcVoidTask != null)
{
using Internal.Runtime.InteropServices.WindowsRuntime;
using System;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Diagnostics.Tracing;
using System.Reflection;
using System.Runtime.CompilerServices;
{
if (d == null)
throw new ArgumentNullException(nameof(d));
- Contract.EndContractBlock();
var ignored = _dispatcher.RunAsync(CoreDispatcherPriority.Normal, new Invoker(d, state).Invoke);
}
{
if (d == null)
throw new ArgumentNullException(nameof(d));
- Contract.EndContractBlock();
// We explicitly choose to ignore the return value here. This enqueue operation might fail if the
// dispatcher queue was shut down before we got here. In that case, we choose to just move on and
using Internal.Runtime.InteropServices.WindowsRuntime;
using System.ComponentModel;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading;
if (source == null)
throw new ArgumentNullException(nameof(source));
- Contract.EndContractBlock();
-
// If source is actually a NetFx-to-WinRT adapter, unwrap it instead of creating a new Task:
var wrapper = source as TaskToAsyncActionAdapter;
if (wrapper != null && !wrapper.CompletedSynchronously)
if (source == null)
throw new ArgumentNullException(nameof(source));
- Contract.EndContractBlock();
-
// If source is actually a NetFx-to-WinRT adapter, unwrap it instead of creating a new Task:
var wrapper = source as TaskToAsyncOperationAdapter<TResult>;
if (wrapper != null && !wrapper.CompletedSynchronously)
if (source == null)
throw new ArgumentNullException(nameof(source));
- Contract.EndContractBlock();
-
// If source is actually a NetFx-to-WinRT adapter, unwrap it instead of creating a new Task:
var wrapper = source as TaskToAsyncActionWithProgressAdapter<TProgress>;
if (wrapper != null && !wrapper.CompletedSynchronously)
if (source == null)
throw new ArgumentNullException(nameof(source));
- Contract.EndContractBlock();
-
// If source is actually a NetFx-to-WinRT adapter, unwrap it instead of creating a new Task:
var wrapper = source as TaskToAsyncOperationWithProgressAdapter<TResult, TProgress>;
if (wrapper != null && !wrapper.CompletedSynchronously)
if (source == null)
throw new ArgumentNullException(nameof(source));
- Contract.EndContractBlock();
-
return new TaskToAsyncActionAdapter(source, underlyingCancelTokenSource: null);
}
if (source == null)
throw new ArgumentNullException(nameof(source));
- Contract.EndContractBlock();
-
return new TaskToAsyncOperationAdapter<TResult>(source, underlyingCancelTokenSource: null);
}
// See the LICENSE file in the project root for more information.
using System.ComponentModel;
-using System.Diagnostics.Contracts;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
if (source == null)
throw new ArgumentNullException(nameof(source));
- Contract.EndContractBlock();
-
// If source is actually a NetFx-to-WinRT adapter, unwrap it instead of creating a new Task:
var wrapper = source as TaskToAsyncActionAdapter;
if (wrapper != null && !wrapper.CompletedSynchronously)
if (source == null)
throw new ArgumentNullException(nameof(source));
- Contract.EndContractBlock();
-
// If source is actually a NetFx-to-WinRT adapter, unwrap it instead of creating a new Task:
var wrapper = source as TaskToAsyncOperationAdapter<TResult>;
if (wrapper != null && !wrapper.CompletedSynchronously)
if (source == null)
throw new ArgumentNullException(nameof(source));
- Contract.EndContractBlock();
-
// If source is actually a NetFx-to-WinRT adapter, unwrap it instead of creating a new Task:
var wrapper = source as TaskToAsyncActionWithProgressAdapter<TProgress>;
if (wrapper != null && !wrapper.CompletedSynchronously)
if (source == null)
throw new ArgumentNullException(nameof(source));
- Contract.EndContractBlock();
-
// If source is actually a NetFx-to-WinRT adapter, unwrap it instead of creating a new Task:
var wrapper = source as TaskToAsyncOperationWithProgressAdapter<TResult, TProgress>;
if (wrapper != null && !wrapper.CompletedSynchronously)
if (source == null)
throw new ArgumentNullException(nameof(source));
- Contract.EndContractBlock();
-
return new TaskToAsyncActionAdapter(source, underlyingCancelTokenSource: null);
}
if (source == null)
throw new ArgumentNullException(nameof(source));
- Contract.EndContractBlock();
-
return new TaskToAsyncOperationAdapter<TResult>(source, underlyingCancelTokenSource: null);
}
#endregion Converters from System.Threading.Tasks.Task to Windows.Foundation.IAsyncInfo (and interfaces that derive from it)
[MemberData(nameof(UnsupportedEnumType_TestData))]
public static void IsDefined_UnsupportedEnumType_ThrowsInvalidOperationException(Type enumType, object value)
{
- // A Contract.Assert(false, "...") is hit for certain unsupported primitives
Exception ex = Assert.ThrowsAny<Exception>(() => Enum.IsDefined(enumType, value));
string exName = ex.GetType().Name;
Assert.True(exName == nameof(InvalidOperationException) || exName == "ContractException");
[MemberData(nameof(UnsupportedEnum_TestData))]
public static void ToString_UnsupportedEnumType_ThrowsArgumentException(Enum e)
{
- // A Contract.Assert(false, "...") is hit for certain unsupported primitives
Exception formatXException = Assert.ThrowsAny<Exception>(() => e.ToString("X"));
string formatXExceptionName = formatXException.GetType().Name;
Assert.True(formatXExceptionName == nameof(InvalidOperationException) || formatXExceptionName == "ContractException");
[MemberData(nameof(UnsupportedEnumType_TestData))]
public static void Format_UnsupportedEnumType_ThrowsArgumentException(Type enumType, object value)
{
- // A Contract.Assert(false, "...") is hit for certain unsupported primitives
Exception formatGException = Assert.ThrowsAny<Exception>(() => Enum.Format(enumType, value, "G"));
string formatGExceptionName = formatGException.GetType().Name;
Assert.True(formatGExceptionName == nameof(InvalidOperationException) || formatGExceptionName == "ContractException");
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
-using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Threading.Tasks.Dataflow.Internal;
// Validate arguments
if (source == null) throw new ArgumentNullException(nameof(source));
if (target == null) throw new ArgumentNullException(nameof(target));
- Contract.EndContractBlock();
// This method exists purely to pass default DataflowLinkOptions
// to increase usability of the "90%" case.
if (target == null) throw new ArgumentNullException(nameof(target));
if (linkOptions == null) throw new ArgumentNullException(nameof(linkOptions));
if (predicate == null) throw new ArgumentNullException(nameof(predicate));
- Contract.EndContractBlock();
// Create the filter, which links to the real target, and then
// link the real source to this intermediate filter.
// is an internal target that should only ever have source non-null.
if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, nameof(messageHeader));
if (source == null) throw new ArgumentNullException(nameof(source));
- Contract.EndContractBlock();
// Run the filter.
bool passedFilter = RunPredicate(messageValue);
{
// Validate arguments. No validation necessary for item.
if (target == null) throw new ArgumentNullException(nameof(target));
- Contract.EndContractBlock();
// Fast path check for cancellation
if (cancellationToken.IsCancellationRequested)
// Validate arguments
if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, nameof(messageHeader));
if (target == null) throw new ArgumentNullException(nameof(target));
- Contract.EndContractBlock();
// If the task has already completed, there's nothing to consume. This could happen if
// cancellation was already requested and completed the task as a result.
// Validate arguments
if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, nameof(messageHeader));
if (target == null) throw new ArgumentNullException(nameof(target));
- Contract.EndContractBlock();
// If the task has already completed, such as due to cancellation, there's nothing to reserve.
if (Task.IsCompleted) return false;
// Validate arguments
if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, nameof(messageHeader));
if (target == null) throw new ArgumentNullException(nameof(target));
- Contract.EndContractBlock();
// If this is not the message we posted, bail
if (messageHeader.Id != Common.SINGLE_MESSAGE_ID)
public static bool TryReceive<TOutput>(this IReceivableSourceBlock<TOutput> source, out TOutput item)
{
if (source == null) throw new ArgumentNullException(nameof(source));
- Contract.EndContractBlock();
return source.TryReceive(null, out item);
}
// Validate arguments
if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, nameof(messageHeader));
if (source == null && consumeToAccept) throw new ArgumentException(SR.Argument_CantConsumeFromANullSource, nameof(consumeToAccept));
- Contract.EndContractBlock();
DataflowMessageStatus status = DataflowMessageStatus.NotAvailable;
{
// Validate arguments
if (source == null) throw new ArgumentNullException(nameof(source));
- Contract.EndContractBlock();
// Fast path for cancellation
if (cancellationToken.IsCancellationRequested)
{
if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, nameof(messageHeader));
if (source == null) throw new ArgumentNullException(nameof(source));
- Contract.EndContractBlock();
TrySetResult(true);
return DataflowMessageStatus.DecliningPermanently;
void IDataflowBlock.Fault(Exception exception)
{
if (exception == null) throw new ArgumentNullException(nameof(exception));
- Contract.EndContractBlock();
TrySetResult(false);
}
{
if (target == null) throw new ArgumentNullException(nameof(target));
if (source == null) throw new ArgumentNullException(nameof(source));
- Contract.EndContractBlock();
return new EncapsulatingPropagator<TInput, TOutput>(target, source);
}
void IDataflowBlock.Fault(Exception exception)
{
if (exception == null) throw new ArgumentNullException(nameof(exception));
- Contract.EndContractBlock();
_target.Fault(exception);
}
// Validate arguments
if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, nameof(messageHeader));
if (source == null && consumeToAccept) throw new ArgumentException(SR.Argument_CantConsumeFromANullSource, nameof(consumeToAccept));
- Contract.EndContractBlock();
lock (_completed)
{
public static IObservable<TOutput> AsObservable<TOutput>(this ISourceBlock<TOutput> source)
{
if (source == null) throw new ArgumentNullException(nameof(source));
- Contract.EndContractBlock();
return SourceObservable<TOutput>.From(source);
}
{
// Validate arguments
if (observer == null) throw new ArgumentNullException(nameof(observer));
- Contract.EndContractBlock();
Common.ContractAssertMonitorStatus(_SubscriptionLock, held: false);
Task sourceCompletionTask = Common.GetPotentiallyNotSupportedCompletionTask(_source);
public static IObserver<TInput> AsObserver<TInput>(this ITargetBlock<TInput> target)
{
if (target == null) throw new ArgumentNullException(nameof(target));
- Contract.EndContractBlock();
return new TargetObserver<TInput>(target);
}
DataflowMessageStatus ITargetBlock<TInput>.OfferMessage(DataflowMessageHeader messageHeader, TInput messageValue, ISourceBlock<TInput> source, bool consumeToAccept)
{
if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, nameof(messageHeader));
- Contract.EndContractBlock();
// If the source requires an explicit synchronous consumption, do it
if (consumeToAccept)
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Threading.Tasks.Dataflow.Internal;
namespace System.Threading.Tasks.Dataflow
public DataflowMessageHeader(long id)
{
if (id == default(long)) throw new ArgumentException(SR.Argument_InvalidMessageId, nameof(id));
- Contract.EndContractBlock();
_id = id;
}
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
-using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Threading.Tasks.Dataflow.Internal;
// Validate arguments
if (action == null) throw new ArgumentNullException(nameof(action));
if (dataflowBlockOptions == null) throw new ArgumentNullException(nameof(dataflowBlockOptions));
- Contract.Ensures((_spscTarget != null) ^ (_defaultTarget != null), "One and only one of the two targets must be non-null after construction");
- Contract.EndContractBlock();
// Ensure we have options that can't be changed by the caller
dataflowBlockOptions = dataflowBlockOptions.DefaultOrClone();
etwLog.DataflowBlockCreated(this, dataflowBlockOptions);
}
#endif
+
+ Debug.Assert((_spscTarget != null) ^ (_defaultTarget != null), "One and only one of the two targets must be non-null after construction");
}
/// <summary>Processes the message with a user-provided action.</summary>
void IDataflowBlock.Fault(Exception exception)
{
if (exception == null) throw new ArgumentNullException(nameof(exception));
- Contract.EndContractBlock();
if (_defaultTarget != null)
{
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
-using System.Diagnostics.Contracts;
using System.Linq;
using System.Security;
using System.Threading.Tasks.Dataflow.Internal;
if (batchSize < 1) throw new ArgumentOutOfRangeException(nameof(batchSize), SR.ArgumentOutOfRange_GenericPositive);
if (dataflowBlockOptions == null) throw new ArgumentNullException(nameof(dataflowBlockOptions));
if (dataflowBlockOptions.BoundedCapacity > 0 && dataflowBlockOptions.BoundedCapacity < batchSize) throw new ArgumentOutOfRangeException(nameof(batchSize), SR.ArgumentOutOfRange_BatchSizeMustBeNoGreaterThanBoundedCapacity);
- Contract.EndContractBlock();
// Ensure we have options that can't be changed by the caller
dataflowBlockOptions = dataflowBlockOptions.DefaultOrClone();
void IDataflowBlock.Fault(Exception exception)
{
if (exception == null) throw new ArgumentNullException(nameof(exception));
- Contract.EndContractBlock();
_target.Complete(exception, dropPendingMessages: true, releaseReservedMessages: false);
}
// Validate arguments
if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, nameof(messageHeader));
if (source == null && consumeToAccept) throw new ArgumentException(SR.Argument_CantConsumeFromANullSource, nameof(consumeToAccept));
- Contract.EndContractBlock();
lock (IncomingLock)
{
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
-using System.Diagnostics.Contracts;
using System.Threading.Tasks.Dataflow.Internal;
namespace System.Threading.Tasks.Dataflow
if (dataflowBlockOptions == null) throw new ArgumentNullException(nameof(dataflowBlockOptions));
if (!dataflowBlockOptions.Greedy) throw new ArgumentException(SR.Argument_NonGreedyNotSupported, nameof(dataflowBlockOptions));
if (dataflowBlockOptions.BoundedCapacity != DataflowBlockOptions.Unbounded) throw new ArgumentException(SR.Argument_BoundedCapacityNotSupported, nameof(dataflowBlockOptions));
- Contract.EndContractBlock();
// Store arguments
_batchSize = batchSize;
void IDataflowBlock.Fault(Exception exception)
{
if (exception == null) throw new ArgumentNullException(nameof(exception));
- Contract.EndContractBlock();
Debug.Assert(_sharedResources != null, "_sharedResources not initialized");
Debug.Assert(_sharedResources._incomingLock != null, "_sharedResources._incomingLock not initialized");
{
throw new ArgumentException(SR.Argument_NonGreedyNotSupported, nameof(dataflowBlockOptions));
}
- Contract.EndContractBlock();
// Store arguments
_batchSize = batchSize;
void IDataflowBlock.Fault(Exception exception)
{
if (exception == null) throw new ArgumentNullException(nameof(exception));
- Contract.EndContractBlock();
Debug.Assert(_sharedResources != null, "_sharedResources not initialized");
Debug.Assert(_sharedResources._incomingLock != null, "_sharedResources._incomingLock not initialized");
// Validate arguments
if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, nameof(messageHeader));
if (source == null && consumeToAccept) throw new ArgumentException(SR.Argument_CantConsumeFromANullSource, nameof(consumeToAccept));
- Contract.EndContractBlock();
lock (_sharedResources._incomingLock)
{
void IDataflowBlock.Fault(Exception exception)
{
if (exception == null) throw new ArgumentNullException(nameof(exception));
- Contract.EndContractBlock();
lock (_sharedResources._incomingLock)
{
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
-using System.Diagnostics.Contracts;
using System.Linq;
using System.Security;
using System.Threading.Tasks.Dataflow.Internal;
{
// Validate arguments
if (dataflowBlockOptions == null) throw new ArgumentNullException(nameof(dataflowBlockOptions));
- Contract.EndContractBlock();
// Ensure we have options that can't be changed by the caller
dataflowBlockOptions = dataflowBlockOptions.DefaultOrClone();
void IDataflowBlock.Fault(Exception exception)
{
if (exception == null) throw new ArgumentNullException(nameof(exception));
- Contract.EndContractBlock();
CompleteCore(exception, storeExceptionEvenIfAlreadyCompleting: false);
}
{
Debug.Assert(storeExceptionEvenIfAlreadyCompleting || !revertProcessingState,
"Indicating dirty processing state may only come with storeExceptionEvenIfAlreadyCompleting==true.");
- Contract.EndContractBlock();
lock (IncomingLock)
{
// Validate arguments
if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, nameof(messageHeader));
if (source == null && consumeToAccept) throw new ArgumentException(SR.Argument_CantConsumeFromANullSource, nameof(consumeToAccept));
- Contract.EndContractBlock();
lock (IncomingLock)
{
// Validate arguments
if (target == null) throw new ArgumentNullException(nameof(target));
if (linkOptions == null) throw new ArgumentNullException(nameof(linkOptions));
- Contract.EndContractBlock();
lock (OutgoingLock)
{
// Validate arguments
if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, nameof(messageHeader));
if (target == null) throw new ArgumentNullException(nameof(target));
- Contract.EndContractBlock();
TOutput valueToClone;
lock (OutgoingLock) // We may currently be calling out under this lock to the target; requires it to be reentrant
// Validate arguments
if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, nameof(messageHeader));
if (target == null) throw new ArgumentNullException(nameof(target));
- Contract.EndContractBlock();
lock (OutgoingLock)
{
// Validate arguments
if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, nameof(messageHeader));
if (target == null) throw new ArgumentNullException(nameof(target));
- Contract.EndContractBlock();
lock (OutgoingLock)
{
using System.Collections.Generic;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Security;
using System.Threading.Tasks.Dataflow.Internal;
using System.Diagnostics.CodeAnalysis;
public BufferBlock(DataflowBlockOptions dataflowBlockOptions)
{
if (dataflowBlockOptions == null) throw new ArgumentNullException(nameof(dataflowBlockOptions));
- Contract.EndContractBlock();
// Ensure we have options that can't be changed by the caller
dataflowBlockOptions = dataflowBlockOptions.DefaultOrClone();
// Validate arguments
if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, nameof(messageHeader));
if (source == null && consumeToAccept) throw new ArgumentException(SR.Argument_CantConsumeFromANullSource, nameof(consumeToAccept));
- Contract.EndContractBlock();
lock (IncomingLock)
{
void IDataflowBlock.Fault(Exception exception)
{
if (exception == null) throw new ArgumentNullException(nameof(exception));
- Contract.EndContractBlock();
CompleteCore(exception, storeExceptionEvenIfAlreadyCompleting: false);
}
{
Debug.Assert(storeExceptionEvenIfAlreadyCompleting || !revertProcessingState,
"Indicating dirty processing state may only come with storeExceptionEvenIfAlreadyCompleting==true.");
- Contract.EndContractBlock();
lock (IncomingLock)
{
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
-using System.Diagnostics.Contracts;
using System.Linq;
using System.Security;
using System.Threading.Tasks.Dataflow.Internal;
{
// Validate arguments
if (dataflowBlockOptions == null) throw new ArgumentNullException(nameof(dataflowBlockOptions));
- Contract.EndContractBlock();
// Ensure we have options that can't be changed by the caller
dataflowBlockOptions = dataflowBlockOptions.DefaultOrClone();
void IDataflowBlock.Fault(Exception exception)
{
if (exception == null) throw new ArgumentNullException(nameof(exception));
- Contract.EndContractBlock();
Debug.Assert(_sharedResources != null, "_sharedResources not initialized");
Debug.Assert(_sharedResources._exceptionAction != null, "_sharedResources._exceptionAction not initialized");
{
// Validate arguments
if (dataflowBlockOptions == null) throw new ArgumentNullException(nameof(dataflowBlockOptions));
- Contract.EndContractBlock();
// Ensure we have options that can't be changed by the caller
dataflowBlockOptions = dataflowBlockOptions.DefaultOrClone();
void IDataflowBlock.Fault(Exception exception)
{
if (exception == null) throw new ArgumentNullException(nameof(exception));
- Contract.EndContractBlock();
Debug.Assert(_sharedResources != null, "_sharedResources not initialized");
Debug.Assert(_sharedResources._exceptionAction != null, "_sharedResources._exceptionAction not initialized");
// Validate arguments
if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, nameof(messageHeader));
if (source == null && consumeToAccept) throw new ArgumentException(SR.Argument_CantConsumeFromANullSource, nameof(consumeToAccept));
- Contract.EndContractBlock();
lock (_sharedResources.IncomingLock)
{
void IDataflowBlock.Fault(Exception exception)
{
if (exception == null) throw new ArgumentNullException(nameof(exception));
- Contract.EndContractBlock();
CompleteCore(exception, dropPendingMessages: true, releaseReservedMessages: false);
}
using System.Collections.Generic;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
using System.Threading.Tasks.Dataflow.Internal;
using System.Diagnostics.CodeAnalysis;
if (dataflowBlockOptions == null) throw new ArgumentNullException(nameof(dataflowBlockOptions));
Debug.Assert(transformSync == null ^ transformAsync == null, "Exactly one of transformSync and transformAsync must be null.");
- Contract.EndContractBlock();
// Ensure we have options that can't be changed by the caller
dataflowBlockOptions = dataflowBlockOptions.DefaultOrClone();
void IDataflowBlock.Fault(Exception exception)
{
if (exception == null) throw new ArgumentNullException(nameof(exception));
- Contract.EndContractBlock();
_target.Complete(exception, dropPendingMessages: true);
}
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
-using System.Diagnostics.Contracts;
using System.Linq;
using System.Threading.Tasks.Dataflow.Internal;
using System.Collections.ObjectModel;
if (dataflowBlockOptions == null) throw new ArgumentNullException(nameof(dataflowBlockOptions));
Debug.Assert(transformSync == null ^ transformAsync == null, "Exactly one of transformSync and transformAsync must be null.");
- Contract.EndContractBlock();
// Ensure we have options that can't be changed by the caller
dataflowBlockOptions = dataflowBlockOptions.DefaultOrClone();
void IDataflowBlock.Fault(Exception exception)
{
if (exception == null) throw new ArgumentNullException(nameof(exception));
- Contract.EndContractBlock();
_target.Complete(exception, dropPendingMessages: true);
}
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
-using System.Diagnostics.Contracts;
using System.Security;
using System.Threading.Tasks.Dataflow.Internal;
{
// Validate arguments
if (dataflowBlockOptions == null) throw new ArgumentNullException(nameof(dataflowBlockOptions));
- Contract.EndContractBlock();
// Store the option
_cloningFunction = cloningFunction;
void IDataflowBlock.Fault(Exception exception)
{
if (exception == null) throw new ArgumentNullException(nameof(exception));
- Contract.EndContractBlock();
CompleteCore(exception, storeExceptionEvenIfAlreadyCompleting: false);
}
{
Debug.Assert(exception != null || !storeExceptionEvenIfAlreadyCompleting,
"When storeExceptionEvenIfAlreadyCompleting is set to true, an exception must be provided.");
- Contract.EndContractBlock();
bool thisThreadReservedCompletion = false;
lock (ValueLock)
// Validate arguments
if (target == null) throw new ArgumentNullException(nameof(target));
if (linkOptions == null) throw new ArgumentNullException(nameof(linkOptions));
- Contract.EndContractBlock();
bool hasValue;
bool isCompleted;
// Validate arguments
if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, nameof(messageHeader));
if (source == null && consumeToAccept) throw new ArgumentException(SR.Argument_CantConsumeFromANullSource, nameof(consumeToAccept));
- Contract.EndContractBlock();
bool thisThreadReservedCompletion = false;
lock (ValueLock)
// Validate arguments
if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, nameof(messageHeader));
if (target == null) throw new ArgumentNullException(nameof(target));
- Contract.EndContractBlock();
// As long as the message being requested is the one we have, allow it to be consumed,
// but make a copy using the provided cloning function.
// Validate arguments
if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, nameof(messageHeader));
if (target == null) throw new ArgumentNullException(nameof(target));
- Contract.EndContractBlock();
// As long as the message is the one we have, it can be "reserved."
// Reservations on a WriteOnceBlock are not exclusive, because
// Validate arguments
if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, nameof(messageHeader));
if (target == null) throw new ArgumentNullException(nameof(target));
- Contract.EndContractBlock();
// As long as the message is the one we have, everything's fine.
if (_header.Id != messageHeader.Id) throw new InvalidOperationException(SR.InvalidOperation_MessageNotReservedByTarget);
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
-using System.Diagnostics.Contracts;
using System.Linq;
using System.Security;
// Validate arguments
if (target == null) throw new ArgumentNullException(nameof(target));
if (linkOptions == null) throw new ArgumentNullException(nameof(linkOptions));
- Contract.EndContractBlock();
// If the block is already completed, there is not much to do -
// we have to propagate completion if that was requested, and
// Validate arguments
if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, nameof(messageHeader));
if (target == null) throw new ArgumentNullException(nameof(target));
- Contract.EndContractBlock();
TOutput consumedMessageValue = default(TOutput);
// Validate arguments
if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, nameof(messageHeader));
if (target == null) throw new ArgumentNullException(nameof(target));
- Contract.EndContractBlock();
lock (OutgoingLock)
{
// Validate arguments
if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, nameof(messageHeader));
if (target == null) throw new ArgumentNullException(nameof(target));
- Contract.EndContractBlock();
lock (OutgoingLock)
{
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
-using System.Diagnostics.Contracts;
using System.Linq;
namespace System.Threading.Tasks.Dataflow.Internal
{
Debug.Assert(storeExceptionEvenIfAlreadyCompleting || !revertProcessingState,
"Indicating dirty processing state may only come with storeExceptionEvenIfAlreadyCompleting==true.");
- Contract.EndContractBlock();
// Ensure that no new messages may be added
lock (IncomingLock)
// Validate arguments
if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, nameof(messageHeader));
if (source == null && consumeToAccept) throw new ArgumentException(SR.Argument_CantConsumeFromANullSource, nameof(consumeToAccept));
- Contract.EndContractBlock();
lock (IncomingLock)
{
ManualResetEvent mreFaulted = new ManualResetEvent(false);
bool innerStarted = false;
- // I Think SpinWait has been implemented on all future platforms because
- // it is in the Contract.
- // So we can ignore this Thread.SpinWait(100);
-
SpinWait sw = new SpinWait();
Task tFaulted = Task.Factory.StartNew(delegate
{