private void RunCore( IterationMode iterationMode, int repeatCount, List <Measurement> measurements) { DebugCode.BugIf(measurements.Count > 0, "measurements not empty."); DebugCode.BugIf(measurements.Capacity < repeatCount, "measurements capacity not set."); var action = iterationMode.IsIdle() ? IdleAction : MainAction; var resultIterationsCount = ResultIterationsCount; // TODO: reenable after https://github.com/dotnet/BenchmarkDotNet/issues/302#issuecomment-262057686 //if (!iterationMode.IsIdle()) // SetupAction?.Invoke(); ForceGcCollect(); if (ForceAllocations) // DONTTOUCH: DO NOT merge loops as it will produce inaccurate results for microbenchmarks. { for (var i = 0; i < repeatCount; i++) { ForceGcCollect(); var clock = Clock.Start(); action(resultIterationsCount); var clockSpan = clock.Stop(); measurements.Add( new Measurement(0, iterationMode, i + 1, 1, clockSpan.GetNanoseconds())); } } else { for (var i = 0; i < repeatCount; i++) { var clock = Clock.Start(); action(resultIterationsCount); var clockSpan = clock.Stop(); measurements.Add( new Measurement(0, iterationMode, i + 1, 1, clockSpan.GetNanoseconds())); } } ForceGcCollect(); // TODO: reenable after https://github.com/dotnet/BenchmarkDotNet/issues/302#issuecomment-262057686 //if (!iterationMode.IsIdle()) // CleanupAction?.Invoke(); }
public static bool IsSubClass([NotNull] this Type type, [NotNull] Type check) { Code.NotNull(type, nameof(type)); Code.NotNull(check, nameof(check)); if (type == check) { return(false); } while (true) { if (check.IsInterface) { // ReSharper disable once LoopCanBeConvertedToQuery foreach (var interfaceType in type.GetInterfaces()) { if (interfaceType == check || interfaceType.IsSubClass(check)) { return(true); } } } if (type.IsGenericType && !type.IsGenericTypeDefinition) { var definition = type.GetGenericTypeDefinition(); DebugCode.BugIf(definition == null, "definition == null"); if (definition == check || definition.IsSubClass(check)) { return(true); } } type = type.BaseType; if (type == null) { return(false); } if (type == check) { return(true); } } }
private int FindEdge(Node node, char c, out Node edge) { edge = default; if (node.IsLeaf) { return(-1); } DebugCode.BugIf(node.Children == null, "node.Children == null"); var edgeIndex = node.Children.LowerBound(c, EdgeComparer); if (edgeIndex == node.Children.Count) { return(-1); } edge = GetNode(node.Children[edgeIndex]); return(edge.Length > 0 && InternalData[edge.Begin] == c ? edgeIndex : -1); }
public string Print() { var sb = new StringBuilder(); var currentIndex = RootNodeIndex; #if LESSTHAN_NET45 var stack = new ListEx <StringLocation>(); #else var stack = new List <StringLocation>(); #endif for (;;) { PrintNodeWithPath(sb, currentIndex, stack); var node = GetNode(currentIndex); if (node.Children != null) { stack.Add(new StringLocation(currentIndex, node.Children.Count - 2)); currentIndex = node.Children[node.Children.Count - 1]; continue; } currentIndex = -1; while (stack.Count > 0) { var t = stack[stack.Count - 1]; stack.RemoveAt(stack.Count - 1); node = GetNode(t.Start); var nextChild = t.Length; if (nextChild >= 0) { DebugCode.BugIf(node.Children == null, "node.Children == null"); currentIndex = node.Children[nextChild]; stack.Add(new StringLocation(t.Start, nextChild - 1)); break; } } if (currentIndex == -1) { break; } } return(sb.ToString()); }
private static void CopyDirectoryIfExists(string source, string target, bool overwrite = false) { DebugIoCode.IsWellFormedPath(source, nameof(source)); DebugIoCode.IsWellFormedPath(target, nameof(target)); source = PathHelpers.EnsureContainerPath(Path.GetFullPath(source)); target = PathHelpers.EnsureContainerPath(Path.GetFullPath(target)); if (!Directory.Exists(source)) { return; } if (!Directory.Exists(target)) { Directory.CreateDirectory(target); } foreach (var sourceDirectory in Directory.GetDirectories(source, "*", SearchOption.AllDirectories)) { DebugCode.BugIf( !sourceDirectory.Substring(0, source.Length).Equals(source, StringComparison.InvariantCultureIgnoreCase), $"GetDirectories() return invalid path. {sourceDirectory} is not a child of {source}"); var targetDirectory = Path.Combine(target, sourceDirectory.Substring(source.Length)); Directory.CreateDirectory(targetDirectory); } foreach (var sourceFile in Directory.GetFiles(source, "*", SearchOption.AllDirectories)) { DebugCode.BugIf( !sourceFile.Substring(0, source.Length).Equals(source, StringComparison.InvariantCultureIgnoreCase), $"GetFiles() return invalid path. {sourceFile} is not a child of {source}"); var targetFile = Path.Combine(target, sourceFile.Substring(source.Length)); if (overwrite || !File.Exists(targetFile)) { File.Copy(sourceFile, targetFile, overwrite); } } }
/// <summary>Workaround that enables usage of Microsoft.Diagnostics.Tracing.TraceEvent together with shadow copy assemblies.</summary> /// <remarks>SEE https://github.com/Microsoft/perfview/issues/292</remarks> public static void WorkaroundEnsureNativeDlls() { var etwAssembly = typeof(ETWTraceEventSource).Assembly; var location = Path.GetDirectoryName(etwAssembly.Location); var codebase = etwAssembly.GetAssemblyDirectory(); if (location != null && codebase != null && !location.Equals(codebase, StringComparison.InvariantCultureIgnoreCase)) { DebugCode.BugIf( Path.GetFullPath(location).ToUpperInvariant() == Path.GetFullPath(codebase).ToUpperInvariant(), "Path.GetFullPath(location).ToUpperInvariant() == Path.GetFullPath(codebase).ToUpperInvariant()"); CopyDirectoryIfExists( Path.Combine(codebase, "amd64"), Path.Combine(location, "amd64")); CopyDirectoryIfExists( Path.Combine(codebase, "x86"), Path.Combine(location, "x86")); } }
private void SetIndexes(int startIndex, int middleIndex, int endIndex) { DebugCode.BugIf(startIndex > middleIndex, "startIndex > middleIndex"); DebugCode.BugIf(middleIndex > endIndex, "middleIndex > endIndex"); if (startIndex == endIndex) { _treeIndexes[startIndex] = startIndex; } else if (startIndex == endIndex - 1) { DebugCode.BugIf(middleIndex != startIndex, "middleIndex != startIndex"); _treeIndexes[endIndex] = endIndex; _treeIndexes[startIndex] = MaxToIndex(startIndex, endIndex); } else if (startIndex == endIndex - 2) { DebugCode.BugIf(middleIndex != startIndex + 1, "middleIndex != startIndex + 1"); _treeIndexes[endIndex] = endIndex; _treeIndexes[startIndex] = MaxToIndex(startIndex, endIndex); _treeIndexes[middleIndex] = MaxToIndex(startIndex, MaxToIndex(middleIndex, endIndex)); } else { DebugCode.BugIf( middleIndex != startIndex + (endIndex - startIndex) / 2, "middleIndex != startIndex + (endIndex-startIndex) / 2"); var newMiddleA = startIndex + (middleIndex - 1 - startIndex) / 2; SetIndexes(startIndex, newMiddleA, middleIndex - 1); var newMiddleB = middleIndex + 1 + (endIndex - (middleIndex + 1)) / 2; SetIndexes(middleIndex + 1, newMiddleB, endIndex); _treeIndexes[middleIndex] = MaxToIndex(_treeIndexes[newMiddleA], MaxToIndex(middleIndex, _treeIndexes[newMiddleB])); } }
public static string GetShortAssemblyQualifiedName([NotNull] this Type type) { Code.NotNull(type, nameof(type)); void WriteAssemblyName(StringBuilder sb, Type t) { sb.Append(", "); var index = -1; var assemblyFullName = t.Assembly.FullName; while (true) { index = assemblyFullName.IndexOf(',', index + 1); DebugCode.BugIf(index == 0, "Invalid assembly name"); if (index < 0) { sb.Append(assemblyFullName); return; } if (assemblyFullName[index - 1] != '\\') { sb.Append(assemblyFullName, 0, index); return; } } } void WriteGenericArguments(StringBuilder sb, Type t) { DebugCode.AssertState(t.IsGenericType && !t.IsGenericTypeDefinition, "Invalid type"); sb.Append('['); var arguments = t.GetGenericArguments(); for (var i = 0; i < arguments.Length; i++) { if (i != 0) { sb.Append(','); } sb.Append('['); WriteFull(sb, arguments[i]); sb.Append(']'); } sb.Append(']'); } void WriteElementType(StringBuilder sb, Type t) { DebugCode.AssertState(t.IsArray || t.IsPointer || t.IsByRef, "Invalid type"); Write(sb, t.GetElementType()); if (t.IsArray) { sb.Append('['); sb.Append(',', t.GetArrayRank() - 1); sb.Append(']'); } else { sb.Append(t.IsPointer ? '*' : '&'); } } void WriteType(StringBuilder sb, Type t) { if (t.DeclaringType != null) { WriteType(sb, t.DeclaringType); sb.Append('+'); } sb.Append(t.Name); } void Write(StringBuilder sb, Type t) { if (t.IsGenericType && !t.IsGenericTypeDefinition) { WriteType(sb, t); WriteGenericArguments(sb, t); } else if (t.IsArray || t.IsPointer || t.IsByRef) { WriteElementType(sb, t); } else { WriteType(sb, t); } } void WriteFull(StringBuilder sb, Type t) { if (t.Namespace.NotNullNorEmpty()) { sb.Append(t.Namespace); sb.Append('.'); } Write(sb, t); WriteAssemblyName(sb, t); } var builder = new StringBuilder(); WriteFull(builder, type); return(builder.ToString()); }
private static Expression TransformInternal([CanBeNull] this Expression expr, [NotNull, InstantHandle] Func <Expression, Expression> func) { if (expr == null) { return(null); } { var ex = func(expr); if (ex != expr) { return(ex); } } switch (expr.NodeType) { case ExpressionType.Add: case ExpressionType.AddChecked: case ExpressionType.And: case ExpressionType.AndAlso: case ExpressionType.ArrayIndex: case ExpressionType.Assign: case ExpressionType.Coalesce: case ExpressionType.Divide: case ExpressionType.Equal: case ExpressionType.ExclusiveOr: case ExpressionType.GreaterThan: case ExpressionType.GreaterThanOrEqual: case ExpressionType.LeftShift: case ExpressionType.LessThan: case ExpressionType.LessThanOrEqual: case ExpressionType.Modulo: case ExpressionType.Multiply: case ExpressionType.MultiplyChecked: case ExpressionType.NotEqual: case ExpressionType.Or: case ExpressionType.OrElse: case ExpressionType.Power: case ExpressionType.RightShift: case ExpressionType.Subtract: case ExpressionType.SubtractChecked: case ExpressionType.AddAssign: case ExpressionType.AndAssign: case ExpressionType.DivideAssign: case ExpressionType.ExclusiveOrAssign: case ExpressionType.LeftShiftAssign: case ExpressionType.ModuloAssign: case ExpressionType.MultiplyAssign: case ExpressionType.OrAssign: case ExpressionType.PowerAssign: case ExpressionType.RightShiftAssign: case ExpressionType.SubtractAssign: case ExpressionType.AddAssignChecked: case ExpressionType.MultiplyAssignChecked: case ExpressionType.SubtractAssignChecked: { var e = (BinaryExpression)expr; return(e.Update( TransformInternal(e.Left, func), (LambdaExpression)TransformInternal(e.Conversion, func), TransformInternal(e.Right, func))); } case ExpressionType.ArrayLength: case ExpressionType.Convert: case ExpressionType.ConvertChecked: case ExpressionType.Negate: case ExpressionType.NegateChecked: case ExpressionType.Not: case ExpressionType.Quote: case ExpressionType.TypeAs: case ExpressionType.UnaryPlus: case ExpressionType.Decrement: case ExpressionType.Increment: case ExpressionType.IsFalse: case ExpressionType.IsTrue: case ExpressionType.Throw: case ExpressionType.Unbox: case ExpressionType.PreIncrementAssign: case ExpressionType.PreDecrementAssign: case ExpressionType.PostIncrementAssign: case ExpressionType.PostDecrementAssign: case ExpressionType.OnesComplement: { var e = (UnaryExpression)expr; return(e.Update(TransformInternal(e.Operand, func))); } case ExpressionType.Call: { var e = (MethodCallExpression)expr; return(e.Update( TransformInternal(e.Object, func), TransformInternal(e.Arguments, func))); } case ExpressionType.Conditional: { var e = (ConditionalExpression)expr; return(e.Update( TransformInternal(e.Test, func), TransformInternal(e.IfTrue, func), TransformInternal(e.IfFalse, func))); } case ExpressionType.Invoke: { var e = (InvocationExpression)expr; return(e.Update( TransformInternal(e.Expression, func), TransformInternal(e.Arguments, func))); } case ExpressionType.Lambda: { var e = (LambdaExpression)expr; var b = TransformInternal(e.Body, func); var p = TransformInternal(e.Parameters, func); return(b != e.Body || !ReferenceEquals(p, e.Parameters) ? Expression.Lambda(expr.Type, b, p.ToArray()) : expr); } case ExpressionType.ListInit: { var e = (ListInitExpression)expr; return(e.Update( (NewExpression)TransformInternal(e.NewExpression, func), TransformInternal( e.Initializers, p => { var args = TransformInternal(p.Arguments, func); return !ReferenceEquals(args, p.Arguments) ? Expression.ElementInit(p.AddMethod, args) : p; }))); } case ExpressionType.MemberAccess: { var e = (MemberExpression)expr; DebugCode.BugIf(e.Expression == null, "e.Expression == null"); return(e.Update(TransformInternal(e.Expression, func))); } case ExpressionType.MemberInit: { MemberBinding Modify(MemberBinding b) { switch (b.BindingType) { case MemberBindingType.Assignment: { var ma = (MemberAssignment)b; return(ma.Update(TransformInternal(ma.Expression, func))); } case MemberBindingType.ListBinding: { var ml = (MemberListBinding)b; return(ml.Update(TransformInternal(ml.Initializers, p => { var args = TransformInternal(p.Arguments, func); return !ReferenceEquals(args, p.Arguments) ? Expression.ElementInit(p.AddMethod, args) : p; }))); } case MemberBindingType.MemberBinding: { var mm = (MemberMemberBinding)b; return(mm.Update(TransformInternal(mm.Bindings, Modify))); } } return(b); } var e = (MemberInitExpression)expr; return(e.Update( (NewExpression)TransformInternal(e.NewExpression, func), TransformInternal(e.Bindings, Modify))); } case ExpressionType.New: { var e = (NewExpression)expr; return(e.Update(TransformInternal(e.Arguments, func))); } case ExpressionType.NewArrayBounds: case ExpressionType.NewArrayInit: { var e = (NewArrayExpression)expr; return(e.Update(TransformInternal(e.Expressions, func))); } case ExpressionType.TypeEqual: case ExpressionType.TypeIs: { var e = (TypeBinaryExpression)expr; return(e.Update(TransformInternal(e.Expression, func))); } case ExpressionType.Block: { var e = (BlockExpression)expr; return(e.Update( TransformInternal(e.Variables, func), TransformInternal(e.Expressions, func))); } case ExpressionType.DebugInfo: case ExpressionType.Default: case ExpressionType.Extension: case ExpressionType.Constant: case ExpressionType.Parameter: return(expr); case ExpressionType.Dynamic: { var e = (DynamicExpression)expr; return(e.Update(TransformInternal(e.Arguments, func))); } case ExpressionType.Goto: { var e = (GotoExpression)expr; return(e.Update(e.Target, TransformInternal(e.Value, func))); } case ExpressionType.Index: { var e = (IndexExpression)expr; DebugCode.BugIf(e.Object == null, "e.Object == null"); return(e.Update( TransformInternal(e.Object, func), TransformInternal(e.Arguments, func))); } case ExpressionType.Label: { var e = (LabelExpression)expr; return(e.Update(e.Target, TransformInternal(e.DefaultValue, func))); } case ExpressionType.RuntimeVariables: { var e = (RuntimeVariablesExpression)expr; return(e.Update(TransformInternal(e.Variables, func))); } case ExpressionType.Loop: { var e = (LoopExpression)expr; return(e.Update(e.BreakLabel, e.ContinueLabel, TransformInternal(e.Body, func))); } case ExpressionType.Switch: { var e = (SwitchExpression)expr; return(e.Update( TransformInternal(e.SwitchValue, func), TransformInternal( e.Cases, cs => cs.Update(TransformInternal(cs.TestValues, func), TransformInternal(cs.Body, func))), TransformInternal(e.DefaultBody, func))); } case ExpressionType.Try: { var e = (TryExpression)expr; return(e.Update( TransformInternal(e.Body, func), TransformInternal( e.Handlers, h => h.Update( (ParameterExpression)TransformInternal(h.Variable, func), TransformInternal(h.Filter, func), TransformInternal(h.Body, func))), TransformInternal(e.Finally, func), TransformInternal(e.Fault, func))); } } throw new InvalidOperationException(); }
/// <summary>Indicates whether the current range is equal to another.</summary> /// <param name="other">A range to compare with this.</param> /// <returns> /// <c>True</c> if the current range is equal to the <paramref name="other"/> parameter; /// otherwise, false. /// </returns> public bool Equals(CompositeRange <T, TKey> other) { // TODO: BADCODE, rewrite if (IsEmpty) { return(other.IsEmpty); } if (other.IsEmpty) { return(false); } DebugCode.BugIf(_ranges == null, "_ranges == null"); DebugCode.BugIf(other._ranges == null, "other._ranges == null"); var otherRanges = other._ranges; if (_containingRange != other._containingRange || _ranges.Count != otherRanges.Count) { return(false); } var previousRange = Range <T> .Empty; var keys = new Dictionary <TKey, int>(); var nullKeysCount = 0; for (var i = 0; i < _ranges.Count; i++) { var currentWithoutKey = _ranges[i].WithoutKey(); // TODO: helper method to compare without key. if (!currentWithoutKey.Equals(otherRanges[i].WithoutKey())) { return(false); } if (currentWithoutKey != previousRange) { var sameKeys = nullKeysCount == 0 && keys.Values.All(a => a == 0); if (!sameKeys) { return(false); } keys.Clear(); nullKeysCount = 0; } var key = _ranges[i].Key; if (key == null) { nullKeysCount++; } else { keys[key] = keys.GetValueOrDefault(key) + 1; } var otherKey = otherRanges[i].Key; if (otherKey == null) { nullKeysCount--; } else { keys[otherKey] = keys.GetValueOrDefault(otherKey) - 1; } previousRange = currentWithoutKey; } return(nullKeysCount == 0 && keys.Values.All(a => a == 0)); }
private static string[] ParseCsv(TextReader reader, ref int lineNum, char separator) { var curChar = CharReader.Create(reader); if (curChar.IsEof) { return(null); // EOF reached } if (curChar.IsEol) { lineNum++; return(Array <string> .Empty); } var result = new List <string>(); StringBuilder curField = null; var state = ParserState.ExpectField; var column = 1; while (true) { var skip = false; while (!skip) { switch (state) { case ParserState.ExpectField: if (curChar.IsEof || curChar.IsEol) { if (result.Count > 0) // Special case - empty string not treated as single empty value { result.Add(""); } return(result.ToArray()); } if (curChar.Char == separator) { result.Add(""); state = ParserState.AfterField; break; } skip = true; if (curChar.IsWhitespace) { break; } curField = new StringBuilder(); if (curChar.IsDoubleQuota) { state = ParserState.QuotedField; break; } state = ParserState.Field; curField.Append(curChar.Char); break; case ParserState.Field: DebugCode.BugIf(curField == null, "curField should be not null"); if (curChar.IsEof || curChar.IsEol || curChar.Char == separator) { result.Add(curField.ToString().Trim()); state = ParserState.AfterField; break; } skip = true; curField.Append(curChar.Char); break; case ParserState.QuotedField: DebugCode.BugIf(curField == null, "curField should be not null"); if (curChar.IsEof) { throw new FormatException($"Unexpected EOF at line {lineNum} column {column}"); } skip = true; if (curChar.IsEol) { curField.Append("\r\n"); break; } if (curChar.IsDoubleQuota) { var peek = curChar.Peek(); if (peek.IsDoubleQuota) // Escaped '"' { curField.Append('"'); curChar = curChar.Next(); } else { result.Add(curField.ToString()); state = ParserState.AfterField; } break; } curField.Append(curChar.Char); break; case ParserState.AfterField: if (curChar.IsEof || curChar.IsEol) { return(result.ToArray()); } skip = true; if (curChar.IsWhitespace) { continue; } if (curChar.Char == separator) { state = ParserState.ExpectField; break; } throw new FormatException($"Unexpected char '{curChar.Char}' at line {lineNum} column {column}"); default: throw new ArgumentOutOfRangeException(); } } curChar = curChar.Next(); column++; if (curChar.IsEol) { lineNum++; column = 1; } } }
private static string BufferToString(char[] buffer) { DebugCode.BugIf(buffer[buffer.Length - 1] != 0, "buffer[buffer.Length - 1] != 0"); return(new string(buffer, 0, buffer.Length - 1)); }