using System;
using System.Runtime.CompilerServices;
using System.Globalization;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
// The following code assumes that the current era value can not be -1.
if (_currentEraValue == -1)
{
- Contract.Assert(BaseCalendarID != CalendarId.UNINITIALIZED_VALUE, "[Calendar.CurrentEraValue] Expected a real calendar ID");
+ Debug.Assert(BaseCalendarID != CalendarId.UNINITIALIZED_VALUE, "[Calendar.CurrentEraValue] Expected a real calendar ID");
_currentEraValue = CalendarData.GetCalendarData(BaseCalendarID).iCurrentEra;
}
return (_currentEraValue);
// this value can be less than 0. It's fine since we are making it positive again in calculating offset.
int dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7);
int offset = (dayForJan1 - firstDayOfWeek + 14) % 7;
- Contract.Assert(offset >= 0, "Calendar.GetFirstDayWeekOfYear(): offset >= 0");
+ Debug.Assert(offset >= 0, "Calendar.GetFirstDayWeekOfYear(): offset >= 0");
return ((dayOfYear + offset) / 7 + 1);
}
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Security;
break;
default:
const string unsupportedDateFieldSymbols = "YuUrQqwWDFg";
- Contract.Assert(unsupportedDateFieldSymbols.IndexOf(input[index]) == -1,
+ Debug.Assert(unsupportedDateFieldSymbols.IndexOf(input[index]) == -1,
string.Format(CultureInfo.InvariantCulture,
"Encountered an unexpected date field symbol '{0}' from ICU which has no known corresponding .NET equivalent.",
input[index]));
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Collections.Generic;
if (!LoadCalendarDataFromSystem(localeName, calendarId))
{
- Contract.Assert(false, "[CalendarData] LoadCalendarDataFromSystem call isn't expected to fail for calendar " + calendarId + " locale " + localeName);
+ Debug.Assert(false, "[CalendarData] LoadCalendarDataFromSystem call isn't expected to fail for calendar " + calendarId + " locale " + localeName);
// Something failed, try invariant for missing parts
// This is really not good, but we don't want the callers to crash.
// See the LICENSE file in the project root for more information.
using System;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Globalization
// the following formulas defines a polynomial function which gives us the amount that the earth is slowing down for specific year ranges
private static double DefaultEphemerisCorrection(int gregorianYear)
{
- Contract.Assert(gregorianYear < 1620 || 2020 <= gregorianYear);
+ Debug.Assert(gregorianYear < 1620 || 2020 <= gregorianYear);
long january1stOfYear = GetNumberOfDays(new DateTime(gregorianYear, 1, 1));
double daysSinceStartOf1810 = january1stOfYear - StartOf1810;
double x = TwelveHours + daysSinceStartOf1810;
private static double EphemerisCorrection1988to2019(int gregorianYear)
{
- Contract.Assert(1988 <= gregorianYear && gregorianYear <= 2019);
+ Debug.Assert(1988 <= gregorianYear && gregorianYear <= 2019);
return (double)(gregorianYear - 1933) / SecondsPerDay;
}
private static double EphemerisCorrection1900to1987(int gregorianYear)
{
- Contract.Assert(1900 <= gregorianYear && gregorianYear <= 1987);
+ Debug.Assert(1900 <= gregorianYear && gregorianYear <= 1987);
double centuriesFrom1900 = CenturiesFrom1900(gregorianYear);
return PolynomialSum(s_coefficients1900to1987, centuriesFrom1900);
}
private static double EphemerisCorrection1800to1899(int gregorianYear)
{
- Contract.Assert(1800 <= gregorianYear && gregorianYear <= 1899);
+ Debug.Assert(1800 <= gregorianYear && gregorianYear <= 1899);
double centuriesFrom1900 = CenturiesFrom1900(gregorianYear);
return PolynomialSum(s_coefficients1800to1899, centuriesFrom1900);
}
private static double EphemerisCorrection1700to1799(int gregorianYear)
{
- Contract.Assert(1700 <= gregorianYear && gregorianYear <= 1799);
+ Debug.Assert(1700 <= gregorianYear && gregorianYear <= 1799);
double yearsSince1700 = gregorianYear - 1700;
return PolynomialSum(s_coefficients1700to1799, yearsSince1700) / SecondsPerDay;
}
private static double EphemerisCorrection1620to1699(int gregorianYear)
{
- Contract.Assert(1620 <= gregorianYear && gregorianYear <= 1699);
+ Debug.Assert(1620 <= gregorianYear && gregorianYear <= 1699);
double yearsSince1600 = gregorianYear - 1600;
return PolynomialSum(s_coefficients1620to1699, yearsSince1600) / SecondsPerDay;
}
}
}
- Contract.Assert(false, "Not expected to come here");
+ Debug.Assert(false, "Not expected to come here");
return DefaultEphemerisCorrection(year);
}
break;
}
}
- Contract.Assert(day != upperBoundNewYearDay);
+ Debug.Assert(day != upperBoundNewYearDay);
return day - 1;
}
using System.Runtime.CompilerServices;
using System.Reflection;
using System.Security;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Globalization
internal static int InternalConvertToUtf32(String s, int index)
{
- Contract.Assert(s != null, "s != null");
- Contract.Assert(index >= 0 && index < s.Length, "index < s.Length");
+ Debug.Assert(s != null, "s != null");
+ Debug.Assert(index >= 0 && index < s.Length, "index < s.Length");
if (index < s.Length - 1)
{
int temp1 = (int)s[index] - HIGH_SURROGATE_START;
internal static int InternalConvertToUtf32(String s, int index, out int charLength)
{
- Contract.Assert(s != null, "s != null");
- Contract.Assert(s.Length > 0, "s.Length > 0");
- Contract.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length");
+ Debug.Assert(s != null, "s != null");
+ Debug.Assert(s.Length > 0, "s.Length > 0");
+ Debug.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length");
charLength = 1;
if (index < s.Length - 1)
{
internal static bool IsWhiteSpace(String s, int index)
{
- Contract.Assert(s != null, "s!=null");
- Contract.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length");
+ Debug.Assert(s != null, "s!=null");
+ Debug.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length");
UnicodeCategory uc = GetUnicodeCategory(s, index);
// In Unicode 3.0, U+2028 is the only character which is under the category "LineSeparator".
//
internal unsafe static double InternalGetNumericValue(int ch)
{
- Contract.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
+ Debug.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
// Get the level 2 item from the highest 12 bit (8 - 19) of ch.
ushort index = s_pNumericLevel1Index[ch >> 8];
// Get the level 2 WORD offset from the 4 - 7 bit of ch. This provides the base offset of the level 3 table.
internal unsafe static ushort InternalGetDigitValues(int ch)
{
- Contract.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
+ Debug.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
// Get the level 2 item from the highest 12 bit (8 - 19) of ch.
ushort index = s_pNumericLevel1Index[ch >> 8];
// Get the level 2 WORD offset from the 4 - 7 bit of ch. This provides the base offset of the level 3 table.
internal unsafe static byte InternalGetCategoryValue(int ch, int offset)
{
- Contract.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
+ Debug.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
// Get the level 2 item from the highest 12 bit (8 - 19) of ch.
ushort index = s_pCategoryLevel1Index[ch >> 8];
// Get the level 2 WORD offset from the 4 - 7 bit of ch. This provides the base offset of the level 3 table.
// Make sure that OtherNotAssigned is the last category in UnicodeCategory.
// If that changes, change the following assertion as well.
//
- //Contract.Assert(uc >= 0 && uc <= UnicodeCategory.OtherNotAssigned, "Table returns incorrect Unicode category");
+ //Debug.Assert(uc >= 0 && uc <= UnicodeCategory.OtherNotAssigned, "Table returns incorrect Unicode category");
return (uc);
}
}
internal static UnicodeCategory InternalGetUnicodeCategory(String value, int index)
{
- Contract.Assert(value != null, "value can not be null");
- Contract.Assert(index < value.Length, "index < value.Length");
+ Debug.Assert(value != null, "value can not be null");
+ Debug.Assert(index < value.Length, "index < value.Length");
return (InternalGetUnicodeCategory(InternalConvertToUtf32(value, index)));
}
internal static UnicodeCategory InternalGetUnicodeCategory(String str, int index, out int charLength)
{
- Contract.Assert(str != null, "str can not be null");
- Contract.Assert(str.Length > 0, "str.Length > 0"); ;
- Contract.Assert(index >= 0 && index < str.Length, "index >= 0 && index < str.Length");
+ Debug.Assert(str != null, "str can not be null");
+ Debug.Assert(str.Length > 0, "str.Length > 0"); ;
+ Debug.Assert(index >= 0 && index < str.Length, "index >= 0 && index < str.Length");
return (InternalGetUnicodeCategory(InternalConvertToUtf32(str, index, out charLength)));
}
internal static bool IsCombiningCategory(UnicodeCategory uc)
{
- Contract.Assert(uc >= 0, "uc >= 0");
+ Debug.Assert(uc >= 0, "uc >= 0");
return (
uc == UnicodeCategory.NonSpacingMark ||
uc == UnicodeCategory.SpacingCombiningMark ||
// 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.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
internal static unsafe int IndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase)
{
- Contract.Assert(source != null);
- Contract.Assert(value != null);
+ Debug.Assert(source != null);
+ Debug.Assert(value != null);
if (value.Length == 0)
{
internal static unsafe int LastIndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase)
{
- Contract.Assert(source != null);
- Contract.Assert(value != null);
+ Debug.Assert(source != null);
+ Debug.Assert(value != null);
if (value.Length == 0)
{
private int GetHashCodeOfStringCore(string source, CompareOptions options)
{
- Contract.Assert(source != null);
- Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
+ Debug.Assert(source != null);
+ Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
return GetHashCodeOfStringCore(source, options, forceRandomizedHashing: false, additionalEntropy: 0);
}
private unsafe int CompareString(string string1, int offset1, int length1, string string2, int offset2, int length2, CompareOptions options)
{
- Contract.Assert(string1 != null);
- Contract.Assert(string2 != null);
- Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
+ Debug.Assert(string1 != null);
+ Debug.Assert(string2 != null);
+ Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
fixed (char* pString1 = string1)
{
private unsafe int IndexOfCore(string source, string target, int startIndex, int count, CompareOptions options)
{
- Contract.Assert(!string.IsNullOrEmpty(source));
- Contract.Assert(target != null);
- Contract.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
+ Debug.Assert(!string.IsNullOrEmpty(source));
+ Debug.Assert(target != null);
+ Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
if (target.Length == 0)
{
private unsafe int LastIndexOfCore(string source, string target, int startIndex, int count, CompareOptions options)
{
- Contract.Assert(!string.IsNullOrEmpty(source));
- Contract.Assert(target != null);
- Contract.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
+ Debug.Assert(!string.IsNullOrEmpty(source));
+ Debug.Assert(target != null);
+ Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
if (target.Length == 0)
{
private bool StartsWith(string source, string prefix, CompareOptions options)
{
- Contract.Assert(!string.IsNullOrEmpty(source));
- Contract.Assert(!string.IsNullOrEmpty(prefix));
- Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
+ Debug.Assert(!string.IsNullOrEmpty(source));
+ Debug.Assert(!string.IsNullOrEmpty(prefix));
+ Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options) && source.IsFastSort() && prefix.IsFastSort())
{
private bool EndsWith(string source, string suffix, CompareOptions options)
{
- Contract.Assert(!string.IsNullOrEmpty(source));
- Contract.Assert(!string.IsNullOrEmpty(suffix));
- Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
+ Debug.Assert(!string.IsNullOrEmpty(source));
+ Debug.Assert(!string.IsNullOrEmpty(suffix));
+ Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options) && source.IsFastSort() && suffix.IsFastSort())
{
internal unsafe int GetHashCodeOfStringCore(string source, CompareOptions options, bool forceRandomizedHashing, long additionalEntropy)
{
- Contract.Assert(source != null);
- Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
+ Debug.Assert(source != null);
+ Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
if (source.Length == 0)
{
int bytesWritten = System.Text.Encoding.UTF8.GetBytes(s, 0, s.Length, buffer, 0);
- Contract.Assert(bytesWritten == byteLen);
+ Debug.Assert(bytesWritten == byteLen);
return buffer;
}
// 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.Diagnostics.Contracts;
namespace System.Globalization
internal static int IndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase)
{
- Contract.Assert(source != null);
- Contract.Assert(value != null);
+ Debug.Assert(source != null);
+ Debug.Assert(value != null);
return FindStringOrdinal(FIND_FROMSTART, source, startIndex, count, value, value.Length, ignoreCase);
}
internal static int LastIndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase)
{
- Contract.Assert(source != null);
- Contract.Assert(value != null);
+ Debug.Assert(source != null);
+ Debug.Assert(value != null);
return FindStringOrdinal(FIND_FROMEND, source, startIndex - count + 1, count, value, value.Length, ignoreCase);
}
private unsafe int GetHashCodeOfStringCore(string source, CompareOptions options)
{
- Contract.Assert(source != null);
- Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
+ Debug.Assert(source != null);
+ Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
if (source.Length == 0)
{
private unsafe int CompareString(string string1, int offset1, int length1, string string2, int offset2, int length2, CompareOptions options)
{
- Contract.Assert(string1 != null);
- Contract.Assert(string2 != null);
- Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
+ Debug.Assert(string1 != null);
+ Debug.Assert(string2 != null);
+ Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
string localeName = _sortHandle != IntPtr.Zero ? null : _sortName;
private int IndexOfCore(string source, string target, int startIndex, int count, CompareOptions options)
{
- Contract.Assert(!string.IsNullOrEmpty(source));
- Contract.Assert(target != null);
- Contract.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
+ Debug.Assert(!string.IsNullOrEmpty(source));
+ Debug.Assert(target != null);
+ Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
// TODO: Consider moving this up to the relevent APIs we need to ensure this behavior for
// and add a precondition that target is not empty.
private int LastIndexOfCore(string source, string target, int startIndex, int count, CompareOptions options)
{
- Contract.Assert(!string.IsNullOrEmpty(source));
- Contract.Assert(target != null);
- Contract.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
+ Debug.Assert(!string.IsNullOrEmpty(source));
+ Debug.Assert(target != null);
+ Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
// TODO: Consider moving this up to the relevent APIs we need to ensure this behavior for
// and add a precondition that target is not empty.
private bool StartsWith(string source, string prefix, CompareOptions options)
{
- Contract.Assert(!string.IsNullOrEmpty(source));
- Contract.Assert(!string.IsNullOrEmpty(prefix));
- Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
+ Debug.Assert(!string.IsNullOrEmpty(source));
+ Debug.Assert(!string.IsNullOrEmpty(prefix));
+ Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
return FindString(FIND_STARTSWITH | (uint)GetNativeCompareFlags(options),
source,
private bool EndsWith(string source, string suffix, CompareOptions options)
{
- Contract.Assert(!string.IsNullOrEmpty(source));
- Contract.Assert(!string.IsNullOrEmpty(suffix));
- Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
+ Debug.Assert(!string.IsNullOrEmpty(source));
+ Debug.Assert(!string.IsNullOrEmpty(suffix));
+ Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
return FindString(FIND_ENDSWITH | (uint)GetNativeCompareFlags(options),
source,
// Suffix & Prefix shouldn't use this, make sure to turn off the NORM_LINGUISTIC_CASING flag
if (options == CompareOptions.Ordinal) { nativeCompareFlags = COMPARE_OPTIONS_ORDINAL; }
- Contract.Assert(((options & ~(CompareOptions.IgnoreCase |
+ Debug.Assert(((options & ~(CompareOptions.IgnoreCase |
CompareOptions.IgnoreKanaType |
CompareOptions.IgnoreNonSpace |
CompareOptions.IgnoreSymbols |
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
{
get
{
- Contract.Assert(_name != null, "CompareInfo.Name Expected _name to be set");
+ Debug.Assert(_name != null, "CompareInfo.Name Expected _name to be set");
if (_name == "zh-CHT" || _name == "zh-CHS")
{
return _name;
//
internal static unsafe int CompareOrdinalIgnoreCase(string strA, int indexA, int lengthA, string strB, int indexB, int lengthB)
{
- Contract.Assert(indexA + lengthA <= strA.Length);
- Contract.Assert(indexB + lengthB <= strB.Length);
+ Debug.Assert(indexA + lengthA <= strA.Length);
+ Debug.Assert(indexB + lengthB <= strB.Length);
int length = Math.Min(lengthA, lengthB);
int range = length;
using System;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Security;
[SecuritySafeCritical]
private unsafe bool InitCultureData()
{
- Contract.Assert(_sRealName != null);
+ Debug.Assert(_sRealName != null);
string alternateSortName = string.Empty;
string realNameBuffer = _sRealName;
private string GetLocaleInfo(LocaleStringData type)
{
- Contract.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo] Expected _sWindowsName to be populated already");
+ Debug.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo] Expected _sWindowsName to be populated already");
return GetLocaleInfo(_sWindowsName, type);
}
[SecuritySafeCritical]
private string GetLocaleInfo(string localeName, LocaleStringData type)
{
- Contract.Assert(localeName != null, "[CultureData.GetLocaleInfo] Expected localeName to be not be null");
+ Debug.Assert(localeName != null, "[CultureData.GetLocaleInfo] Expected localeName to be not be null");
switch (type)
{
{
// Failed, just use empty string
StringBuilderCache.Release(sb);
- Contract.Assert(false, "[CultureData.GetLocaleInfo(LocaleStringData)] Failed");
+ Debug.Assert(false, "[CultureData.GetLocaleInfo(LocaleStringData)] Failed");
return String.Empty;
}
return StringBuilderCache.GetStringAndRelease(sb);
[SecuritySafeCritical]
private int GetLocaleInfo(LocaleNumberData type)
{
- Contract.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo(LocaleNumberData)] Expected _sWindowsName to be populated already");
+ Debug.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo(LocaleNumberData)] Expected _sWindowsName to be populated already");
switch (type)
{
if (!result)
{
// Failed, just use 0
- Contract.Assert(false, "[CultureData.GetLocaleInfo(LocaleNumberData)] failed");
+ Debug.Assert(false, "[CultureData.GetLocaleInfo(LocaleNumberData)] failed");
}
return value;
[SecuritySafeCritical]
private int[] GetLocaleInfo(LocaleGroupingData type)
{
- Contract.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo(LocaleGroupingData)] Expected _sWindowsName to be populated already");
+ Debug.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo(LocaleGroupingData)] Expected _sWindowsName to be populated already");
int primaryGroupingSize = 0;
int secondaryGroupingSize = 0;
bool result = Interop.GlobalizationInterop.GetLocaleInfoGroupingSizes(_sWindowsName, (uint)type, ref primaryGroupingSize, ref secondaryGroupingSize);
if (!result)
{
- Contract.Assert(false, "[CultureData.GetLocaleInfo(LocaleGroupingData type)] failed");
+ Debug.Assert(false, "[CultureData.GetLocaleInfo(LocaleGroupingData type)] failed");
}
if (secondaryGroupingSize == 0)
[SecuritySafeCritical]
private string GetTimeFormatString(bool shortFormat)
{
- Contract.Assert(_sWindowsName != null, "[CultureData.GetTimeFormatString(bool shortFormat)] Expected _sWindowsName to be populated already");
+ Debug.Assert(_sWindowsName != null, "[CultureData.GetTimeFormatString(bool shortFormat)] Expected _sWindowsName to be populated already");
StringBuilder sb = StringBuilderCache.Acquire(ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY);
{
// Failed, just use empty string
StringBuilderCache.Release(sb);
- Contract.Assert(false, "[CultureData.GetTimeFormatString(bool shortFormat)] Failed");
+ Debug.Assert(false, "[CultureData.GetTimeFormatString(bool shortFormat)] Failed");
return String.Empty;
}
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Text;
private string GetLocaleInfo(LocaleStringData type)
{
- Contract.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfo] Expected _sWindowsName to be populated by already");
+ Debug.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfo] Expected _sWindowsName to be populated by already");
return GetLocaleInfo(_sWindowsName, type);
}
// Ask OS for data, note that we presume it returns success, so we have to know that
// sWindowsName is valid before calling.
- Contract.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected _sWindowsName to be populated by already");
+ Debug.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected _sWindowsName to be populated by already");
int result = Interop.mincore.GetLocaleInfoExInt(_sWindowsName, lctype);
return result;
private int GetFirstDayOfWeek()
{
- Contract.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected _sWindowsName to be populated by already");
+ Debug.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected _sWindowsName to be populated by already");
const uint LOCALE_IFIRSTDAYOFWEEK = 0x0000100C;
private String[] GetTimeFormats()
{
// Note that this gets overrides for us all the time
- Contract.Assert(_sWindowsName != null, "[CultureData.DoEnumTimeFormats] Expected _sWindowsName to be populated by already");
+ Debug.Assert(_sWindowsName != null, "[CultureData.DoEnumTimeFormats] Expected _sWindowsName to be populated by already");
String[] result = ReescapeWin32Strings(nativeEnumTimeFormats(_sWindowsName, 0, UseUserOverride));
return result;
private String[] GetShortTimeFormats()
{
// Note that this gets overrides for us all the time
- Contract.Assert(_sWindowsName != null, "[CultureData.DoEnumShortTimeFormats] Expected _sWindowsName to be populated by already");
+ Debug.Assert(_sWindowsName != null, "[CultureData.DoEnumShortTimeFormats] Expected _sWindowsName to be populated by already");
String[] result = ReescapeWin32Strings(nativeEnumTimeFormats(_sWindowsName, TIME_NOSECONDS, UseUserOverride));
return result;
// region name match the requested region name
private static CultureData GetCultureDataFromRegionName(String regionName)
{
- Contract.Assert(regionName != null);
+ Debug.Assert(regionName != null);
const uint LOCALE_SUPPLEMENTAL = 0x00000002;
const uint LOCALE_SPECIFICDATA = 0x00000020;
private static string GetLocaleInfoFromLCType(string localeName, uint lctype, bool useUserOveride)
{
- Contract.Assert(localeName != null, "[CultureData.GetLocaleInfoFromLCType] Expected localeName to be not be null");
+ Debug.Assert(localeName != null, "[CultureData.GetLocaleInfoFromLCType] Expected localeName to be not be null");
// Fix lctype if we don't want overrides
if (!useUserOveride)
using System.Threading;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Globalization
{
get
{
- Contract.Assert(_sRealName != null, "[CultureData.CultureName] Expected _sRealName to be populated by already");
+ Debug.Assert(_sRealName != null, "[CultureData.CultureName] Expected _sRealName to be populated by already");
// since windows doesn't know about zh-CHS and zh-CHT,
// we leave sRealName == zh-Hanx but we still need to
// pretend that it was zh-CHX.
get
{
// This got populated during the culture initialization
- Contract.Assert(_sSpecificCulture != null, "[CultureData.SSPECIFICCULTURE] Expected this.sSpecificCulture to be populated by culture data initialization already");
+ Debug.Assert(_sSpecificCulture != null, "[CultureData.SSPECIFICCULTURE] Expected this.sSpecificCulture to be populated by culture data initialization already");
return _sSpecificCulture;
}
}
// We then have to copy that list to a new array of the right size.
// Default calendar should be first
CalendarId[] calendars = new CalendarId[23];
- Contract.Assert(_sWindowsName != null, "[CultureData.CalendarIds] Expected _sWindowsName to be populated by already");
+ Debug.Assert(_sWindowsName != null, "[CultureData.CalendarIds] Expected _sWindowsName to be populated by already");
int count = CalendarData.GetCalendars(_sWindowsName, _bUseOverrides, calendars);
// See if we had a calendar to add.
internal CalendarData GetCalendar(CalendarId calendarId)
{
- Contract.Assert(calendarId > 0 && calendarId <= CalendarId.LAST_CALENDAR,
+ Debug.Assert(calendarId > 0 && calendarId <= CalendarId.LAST_CALENDAR,
"[CultureData.GetCalendar] Expect calendarId to be in a valid range");
// arrays are 0 based, calendarIds are 1 based
// Make sure that calendar has data
if (calendarData == null)
{
- Contract.Assert(_sWindowsName != null, "[CultureData.GetCalendar] Expected _sWindowsName to be populated by already");
+ Debug.Assert(_sWindowsName != null, "[CultureData.GetCalendar] Expected _sWindowsName to be populated by already");
calendarData = new CalendarData(_sWindowsName, calendarId, this.UseUserOverride);
_calendars[calendarIndex] = calendarData;
}
{
if (_iReadingLayout == undef)
{
- Contract.Assert(_sRealName != null, "[CultureData.IsRightToLeft] Expected _sRealName to be populated by already");
+ Debug.Assert(_sRealName != null, "[CultureData.IsRightToLeft] Expected _sRealName to be populated by already");
_iReadingLayout = GetLocaleInfo(LocaleNumberData.ReadingLayout);
}
{
// Note: Custom cultures might point at another culture's textinfo, however windows knows how
// to redirect it to the desired textinfo culture, so this is OK.
- Contract.Assert(_sRealName != null, "[CultureData.STEXTINFO] Expected _sRealName to be populated by already");
+ Debug.Assert(_sRealName != null, "[CultureData.STEXTINFO] Expected _sRealName to be populated by already");
return (_sRealName);
}
}
{
get
{
- Contract.Assert(_sRealName != null, "[CultureData.SCOMPAREINFO] Expected _sRealName to be populated by already");
+ Debug.Assert(_sRealName != null, "[CultureData.SCOMPAREINFO] Expected _sRealName to be populated by already");
return (_sRealName);
}
}
{
if (_iLanguage == 0)
{
- Contract.Assert(_sRealName != null, "[CultureData.ILANGUAGE] Expected this.sRealName to be populated by COMNlsInfo::nativeInitCultureData already");
+ Debug.Assert(_sRealName != null, "[CultureData.ILANGUAGE] Expected this.sRealName to be populated by COMNlsInfo::nativeInitCultureData already");
_iLanguage = LocaleNameToLCID(_sRealName);
}
return _iLanguage;
// All of our era names
internal String[] EraNames(CalendarId calendarId)
{
- Contract.Assert(calendarId > 0, "[CultureData.saEraNames] Expected Calendar.ID > 0");
+ Debug.Assert(calendarId > 0, "[CultureData.saEraNames] Expected Calendar.ID > 0");
return this.GetCalendar(calendarId).saEraNames;
}
internal String[] AbbrevEraNames(CalendarId calendarId)
{
- Contract.Assert(calendarId > 0, "[CultureData.saAbbrevEraNames] Expected Calendar.ID > 0");
+ Debug.Assert(calendarId > 0, "[CultureData.saAbbrevEraNames] Expected Calendar.ID > 0");
return this.GetCalendar(calendarId).saAbbrevEraNames;
}
internal String[] AbbreviatedEnglishEraNames(CalendarId calendarId)
{
- Contract.Assert(calendarId > 0, "[CultureData.saAbbrevEraNames] Expected Calendar.ID > 0");
+ Debug.Assert(calendarId > 0, "[CultureData.saAbbrevEraNames] Expected Calendar.ID > 0");
return this.GetCalendar(calendarId).saAbbrevEnglishEraNames;
}
private static int IndexOfTimePart(string format, int startIndex, string timeParts)
{
- Contract.Assert(startIndex >= 0, "startIndex cannot be negative");
- Contract.Assert(timeParts.IndexOfAny(new char[] { '\'', '\\' }) == -1, "timeParts cannot include quote characters");
+ Debug.Assert(startIndex >= 0, "startIndex cannot be negative");
+ Debug.Assert(timeParts.IndexOfAny(new char[] { '\'', '\\' }) == -1, "timeParts cannot include quote characters");
bool inQuote = false;
for (int i = startIndex; i < format.Length; ++i)
{
}
else
{
- Contract.Assert(_sWindowsName != null, "[CultureData.GetNFIValues] Expected _sWindowsName to be populated by already");
+ Debug.Assert(_sWindowsName != null, "[CultureData.GetNFIValues] Expected _sWindowsName to be populated by already");
// String values
nfi.positiveSign = GetLocaleInfo(LocaleStringData.PositiveSign);
nfi.negativeSign = GetLocaleInfo(LocaleStringData.NegativeSign);
using System;
using System.Collections;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime;
using System.Runtime.CompilerServices;
[OnDeserialized]
private void OnDeserialized(StreamingContext ctx)
{
- Contract.Assert(m_name != null, "[CultureInfo.OnDeserialized] m_name != null");
+ Debug.Assert(m_name != null, "[CultureInfo.OnDeserialized] m_name != null");
InitializeFromName(m_name, m_useUserOverride);
}
Init();
}
- Contract.Assert(s_userDefaultCulture != null);
+ Debug.Assert(s_userDefaultCulture != null);
return s_userDefaultCulture;
}
Init();
}
- Contract.Assert(s_userDefaultCulture != null);
+ Debug.Assert(s_userDefaultCulture != null);
return s_userDefaultCulture;
}
{
Init();
}
- Contract.Assert(s_userDefaultCulture != null, "[CultureInfo.InstalledUICulture] s_userDefaultCulture != null");
+ Debug.Assert(s_userDefaultCulture != null, "[CultureInfo.InstalledUICulture] s_userDefaultCulture != null");
return s_userDefaultCulture;
}
}
get
{
Contract.Ensures(Contract.Result<String>() != null);
- Contract.Assert(m_name != null, "[CultureInfo.DisplayName] Always expect m_name to be set");
+ Debug.Assert(m_name != null, "[CultureInfo.DisplayName] Always expect m_name to be set");
return m_cultureData.SLOCALIZEDDISPLAYNAME;
}
//calendars unless they're required.
internal static Calendar GetCalendarInstanceRare(CalendarId calType)
{
- Contract.Assert(calType != CalendarId.GREGORIAN, "calType!=CalendarId.GREGORIAN");
+ Debug.Assert(calType != CalendarId.GREGORIAN, "calType!=CalendarId.GREGORIAN");
switch (calType)
{
{
if (calendar == null)
{
- Contract.Assert(this.m_cultureData.CalendarIds.Length > 0, "this.m_cultureData.CalendarIds.Length > 0");
+ Debug.Assert(this.m_cultureData.CalendarIds.Length > 0, "this.m_cultureData.CalendarIds.Length > 0");
// Get the default calendar for this culture. Note that the value can be
// from registry if this is a user default culture.
Calendar newObj = this.m_cultureData.DefaultCalendar;
using System;
using System.Collections;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
{
// Get the abbreviated day names for our current calendar
this.abbreviatedDayNames = _cultureData.AbbreviatedDayNames(Calendar.ID);
- Contract.Assert(this.abbreviatedDayNames.Length == 7, "[DateTimeFormatInfo.GetAbbreviatedDayOfWeekNames] Expected 7 day names in a week");
+ Debug.Assert(this.abbreviatedDayNames.Length == 7, "[DateTimeFormatInfo.GetAbbreviatedDayOfWeekNames] Expected 7 day names in a week");
}
return (this.abbreviatedDayNames);
}
{
// Get the super short day names for our current calendar
this.m_superShortDayNames = _cultureData.SuperShortDayNames(Calendar.ID);
- Contract.Assert(this.m_superShortDayNames.Length == 7, "[DateTimeFormatInfo.internalGetSuperShortDayNames] Expected 7 day names in a week");
+ Debug.Assert(this.m_superShortDayNames.Length == 7, "[DateTimeFormatInfo.internalGetSuperShortDayNames] Expected 7 day names in a week");
}
return (this.m_superShortDayNames);
}
{
// Get the day names for our current calendar
this.dayNames = _cultureData.DayNames(Calendar.ID);
- Contract.Assert(this.dayNames.Length == 7, "[DateTimeFormatInfo.GetDayOfWeekNames] Expected 7 day names in a week");
+ Debug.Assert(this.dayNames.Length == 7, "[DateTimeFormatInfo.GetDayOfWeekNames] Expected 7 day names in a week");
}
return (this.dayNames);
}
{
// Get the month names for our current calendar
this.abbreviatedMonthNames = _cultureData.AbbreviatedMonthNames(Calendar.ID);
- Contract.Assert(this.abbreviatedMonthNames.Length == 12 || this.abbreviatedMonthNames.Length == 13,
+ Debug.Assert(this.abbreviatedMonthNames.Length == 12 || this.abbreviatedMonthNames.Length == 13,
"[DateTimeFormatInfo.GetAbbreviatedMonthNames] Expected 12 or 13 month names in a year");
}
return (this.abbreviatedMonthNames);
{
// Get the month names for our current calendar
this.monthNames = _cultureData.MonthNames(Calendar.ID);
- Contract.Assert(this.monthNames.Length == 12 || this.monthNames.Length == 13,
+ Debug.Assert(this.monthNames.Length == 12 || this.monthNames.Length == 13,
"[DateTimeFormatInfo.GetMonthNames] Expected 12 or 13 month names in a year");
}
private void InitializeOverridableProperties(CultureData cultureData, CalendarId calendarId)
{
Contract.Requires(cultureData != null);
- Contract.Assert(calendarId != CalendarId.UNINITIALIZED_VALUE, "[DateTimeFormatInfo.Populate] Expected initalized calendarId");
+ Debug.Assert(calendarId != CalendarId.UNINITIALIZED_VALUE, "[DateTimeFormatInfo.Populate] Expected initalized calendarId");
if (this.firstDayOfWeek == -1) { this.firstDayOfWeek = cultureData.IFIRSTDAYOFWEEK; }
if (this.calendarWeekRule == -1) { this.calendarWeekRule = cultureData.IFIRSTWEEKOFYEAR; }
if (this.dateSeparator == null) { this.dateSeparator = cultureData.DateSeparator(calendarId); }
this.allLongTimePatterns = _cultureData.LongTimes;
- Contract.Assert(this.allLongTimePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some long time patterns");
+ Debug.Assert(this.allLongTimePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some long time patterns");
this.allShortTimePatterns = _cultureData.ShortTimes;
- Contract.Assert(this.allShortTimePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some short time patterns");
+ Debug.Assert(this.allShortTimePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some short time patterns");
this.allLongDatePatterns = cultureData.LongDates(calendarId);
- Contract.Assert(this.allLongDatePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some long date patterns");
+ Debug.Assert(this.allLongDatePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some long date patterns");
this.allShortDatePatterns = cultureData.ShortDates(calendarId);
- Contract.Assert(this.allShortDatePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some short date patterns");
+ Debug.Assert(this.allShortDatePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some short date patterns");
this.allYearMonthPatterns = cultureData.YearMonths(calendarId);
- Contract.Assert(this.allYearMonthPatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some year month patterns");
+ Debug.Assert(this.allYearMonthPatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some year month patterns");
}
[OptionalField(VersionAdded = 1)]
{
this.amDesignator = _cultureData.SAM1159;
}
- Contract.Assert(this.amDesignator != null, "DateTimeFormatInfo.AMDesignator, amDesignator != null");
+ Debug.Assert(this.amDesignator != null, "DateTimeFormatInfo.AMDesignator, amDesignator != null");
return (this.amDesignator);
}
{
Contract.Ensures(Contract.Result<Calendar>() != null);
- Contract.Assert(this.calendar != null, "DateTimeFormatInfo.Calendar: calendar != null");
+ Debug.Assert(this.calendar != null, "DateTimeFormatInfo.Calendar: calendar != null");
return (this.calendar);
}
{
if (this.m_abbrevEnglishEraNames == null)
{
- Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.AbbreviatedEnglishEraNames] Expected Calendar.ID > 0");
+ Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.AbbreviatedEnglishEraNames] Expected Calendar.ID > 0");
this.m_abbrevEnglishEraNames = _cultureData.AbbreviatedEnglishEraNames(Calendar.ID);
}
return (this.m_abbrevEnglishEraNames);
{
dateSeparator = _cultureData.DateSeparator(Calendar.ID);
}
- Contract.Assert(this.dateSeparator != null, "DateTimeFormatInfo.DateSeparator, dateSeparator != null");
+ Debug.Assert(this.dateSeparator != null, "DateTimeFormatInfo.DateSeparator, dateSeparator != null");
return dateSeparator;
}
{
this.firstDayOfWeek = _cultureData.IFIRSTDAYOFWEEK;
}
- Contract.Assert(this.firstDayOfWeek != -1, "DateTimeFormatInfo.FirstDayOfWeek, firstDayOfWeek != -1");
+ Debug.Assert(this.firstDayOfWeek != -1, "DateTimeFormatInfo.FirstDayOfWeek, firstDayOfWeek != -1");
return ((DayOfWeek)this.firstDayOfWeek);
}
{
this.calendarWeekRule = _cultureData.IFIRSTWEEKOFYEAR;
}
- Contract.Assert(this.calendarWeekRule != -1, "DateTimeFormatInfo.CalendarWeekRule, calendarWeekRule != -1");
+ Debug.Assert(this.calendarWeekRule != -1, "DateTimeFormatInfo.CalendarWeekRule, calendarWeekRule != -1");
return ((CalendarWeekRule)this.calendarWeekRule);
}
{
if (this.monthDayPattern == null)
{
- Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.MonthDayPattern] Expected calID > 0");
+ Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.MonthDayPattern] Expected calID > 0");
this.monthDayPattern = _cultureData.MonthDay(Calendar.ID);
}
- Contract.Assert(this.monthDayPattern != null, "DateTimeFormatInfo.MonthDayPattern, monthDayPattern != null");
+ Debug.Assert(this.monthDayPattern != null, "DateTimeFormatInfo.MonthDayPattern, monthDayPattern != null");
return (this.monthDayPattern);
}
{
this.pmDesignator = _cultureData.SPM2359;
}
- Contract.Assert(this.pmDesignator != null, "DateTimeFormatInfo.PMDesignator, pmDesignator != null");
+ Debug.Assert(this.pmDesignator != null, "DateTimeFormatInfo.PMDesignator, pmDesignator != null");
return (this.pmDesignator);
}
{
timeSeparator = _cultureData.TimeSeparator;
}
- Contract.Assert(this.timeSeparator != null, "DateTimeFormatInfo.TimeSeparator, timeSeparator != null");
+ Debug.Assert(this.timeSeparator != null, "DateTimeFormatInfo.TimeSeparator, timeSeparator != null");
return (timeSeparator);
}
if (this.m_genitiveAbbreviatedMonthNames == null)
{
this.m_genitiveAbbreviatedMonthNames = _cultureData.AbbreviatedGenitiveMonthNames(this.Calendar.ID);
- Contract.Assert(this.m_genitiveAbbreviatedMonthNames.Length == 13,
+ Debug.Assert(this.m_genitiveAbbreviatedMonthNames.Length == 13,
"[DateTimeFormatInfo.GetGenitiveMonthNames] Expected 13 abbreviated genitive month names in a year");
}
return (this.m_genitiveAbbreviatedMonthNames);
if (this.genitiveMonthNames == null)
{
this.genitiveMonthNames = _cultureData.GenitiveMonthNames(this.Calendar.ID);
- Contract.Assert(this.genitiveMonthNames.Length == 13,
+ Debug.Assert(this.genitiveMonthNames.Length == 13,
"[DateTimeFormatInfo.GetGenitiveMonthNames] Expected 13 genitive month names in a year");
}
return (this.genitiveMonthNames);
{
if (this.leapYearMonthNames == null)
{
- Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.internalGetLeapYearMonthNames] Expected Calendar.ID > 0");
+ Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.internalGetLeapYearMonthNames] Expected Calendar.ID > 0");
this.leapYearMonthNames = _cultureData.LeapYearMonthNames(Calendar.ID);
- Contract.Assert(this.leapYearMonthNames.Length == 13,
+ Debug.Assert(this.leapYearMonthNames.Length == 13,
"[DateTimeFormatInfo.internalGetLeapYearMonthNames] Expepcted 13 leap year month names");
}
return (leapYearMonthNames);
// The resulting [] can get returned to the calling app, so clone it.
private static string[] GetMergedPatterns(string[] patterns, string defaultPattern)
{
- Contract.Assert(patterns != null && patterns.Length > 0,
+ Debug.Assert(patterns != null && patterns.Length > 0,
"[DateTimeFormatInfo.GetMergedPatterns]Expected array of at least one pattern");
- Contract.Assert(defaultPattern != null,
+ Debug.Assert(defaultPattern != null,
"[DateTimeFormatInfo.GetMergedPatterns]Expected non null default string");
// If the default happens to be the first in the list just return (a cloned) copy
{
if (this.allYearMonthPatterns == null)
{
- Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedYearMonthPatterns] Expected Calendar.ID > 0");
+ Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedYearMonthPatterns] Expected Calendar.ID > 0");
this.allYearMonthPatterns = _cultureData.YearMonths(this.Calendar.ID);
- Contract.Assert(this.allYearMonthPatterns.Length > 0,
+ Debug.Assert(this.allYearMonthPatterns.Length > 0,
"[DateTimeFormatInfo.UnclonedYearMonthPatterns] Expected some year month patterns");
}
{
if (allShortDatePatterns == null)
{
- Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedShortDatePatterns] Expected Calendar.ID > 0");
+ Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedShortDatePatterns] Expected Calendar.ID > 0");
this.allShortDatePatterns = _cultureData.ShortDates(this.Calendar.ID);
- Contract.Assert(this.allShortDatePatterns.Length > 0,
+ Debug.Assert(this.allShortDatePatterns.Length > 0,
"[DateTimeFormatInfo.UnclonedShortDatePatterns] Expected some short date patterns");
}
{
if (allLongDatePatterns == null)
{
- Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedLongDatePatterns] Expected Calendar.ID > 0");
+ Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedLongDatePatterns] Expected Calendar.ID > 0");
this.allLongDatePatterns = _cultureData.LongDates(this.Calendar.ID);
- Contract.Assert(this.allLongDatePatterns.Length > 0,
+ Debug.Assert(this.allLongDatePatterns.Length > 0,
"[DateTimeFormatInfo.UnclonedLongDatePatterns] Expected some long date patterns");
}
if (this.allShortTimePatterns == null)
{
this.allShortTimePatterns = _cultureData.ShortTimes;
- Contract.Assert(this.allShortTimePatterns.Length > 0,
+ Debug.Assert(this.allShortTimePatterns.Length > 0,
"[DateTimeFormatInfo.UnclonedShortTimePatterns] Expected some short time patterns");
}
if (this.allLongTimePatterns == null)
{
this.allLongTimePatterns = _cultureData.LongTimes;
- Contract.Assert(this.allLongTimePatterns.Length > 0,
+ Debug.Assert(this.allLongTimePatterns.Length > 0,
"[DateTimeFormatInfo.UnclonedLongTimePatterns] Expected some long time patterns");
}
} while (i < str.Value.Length && (state != HebrewNumberParsingState.FoundEndOfHebrewNumber));
// When we are here, we are either at the end of the string, or we find a valid Hebrew number.
- Contract.Assert(state == HebrewNumberParsingState.ContinueParsing || state == HebrewNumberParsingState.FoundEndOfHebrewNumber,
+ Debug.Assert(state == HebrewNumberParsingState.ContinueParsing || state == HebrewNumberParsingState.FoundEndOfHebrewNumber,
"Invalid returned state from HebrewNumber.ParseByChar()");
if (state != HebrewNumberParsingState.FoundEndOfHebrewNumber)
tokenValue = 0;
TokenHashValue value;
- Contract.Assert(str.Index < str.Value.Length, "DateTimeFormatInfo.Tokenize(): start < value.Length");
+ Debug.Assert(str.Index < str.Value.Length, "DateTimeFormatInfo.Tokenize(): start < value.Length");
char ch = str.m_current;
bool isLetter = Char.IsLetter(ch);
}
previousNode = temp;
};
- Contract.Assert(false, "The hashtable is full. This should not happen.");
+ Debug.Assert(false, "The hashtable is full. This should not happen.");
}
private void InsertHash(TokenHashValue[] hashTable, String str, TokenType tokenType, int tokenValue)
hashcode += hashProbe;
if (hashcode >= TOKEN_HASH_SIZE) hashcode -= TOKEN_HASH_SIZE;
} while (i < TOKEN_HASH_SIZE);
- Contract.Assert(false, "The hashtable is full. This should not happen.");
+ Debug.Assert(false, "The hashtable is full. This should not happen.");
}
private bool CompareStringIgnoreCaseOptimized(string string1, int offset1, int length1, string string2, int offset2, int length2)
using System;
using System.Text;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Globalization
// is true.
//
NumDays -= (long)(s_lunarMonthLen[hebrewYearType * MaxMonthPlusOne + lunarDate.month] - lunarDate.day);
- Contract.Assert(NumDays >= 1, "NumDays >= 1");
+ Debug.Assert(NumDays >= 1, "NumDays >= 1");
// If NumDays is 1, then we are done. Otherwise, find the correct Hebrew month
// and day.
int hebrewYearType = GetHebrewYearType(year, era);
CheckHebrewMonthValue(year, month, era);
- Contract.Assert(hebrewYearType >= 1 && hebrewYearType <= 6,
+ Debug.Assert(hebrewYearType >= 1 && hebrewYearType <= 6,
"hebrewYearType should be from 1 to 6, but now hebrewYearType = " + hebrewYearType + " for hebrew year " + year);
int monthDays = s_lunarMonthLen[hebrewYearType * MaxMonthPlusOne + month];
if (monthDays == 0)
Number -= 5000;
}
- Contract.Assert(Number > 0 && Number <= 999, "Number is out of range."); ;
+ Debug.Assert(Number > 0 && Number <= 999, "Number is out of range."); ;
//
// Get the Hundreds.
// 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.Diagnostics.Contracts;
// This file contains the handling of Windows OS specific culture features.
int right = s_lcids.Length - 1;
int index;
- Contract.Assert(s_lcids.Length == s_lcidToCultureNameIndices.Length);
+ Debug.Assert(s_lcids.Length == s_lcidToCultureNameIndices.Length);
while (left <= right)
{
if (culture == s_lcids[index])
{
int indexToLocaleNamesIndices = s_lcidToCultureNameIndices[index];
- Contract.Assert(indexToLocaleNamesIndices < s_localeNamesIndices.Length - 1);
+ Debug.Assert(indexToLocaleNamesIndices < s_localeNamesIndices.Length - 1);
return c_localeNames.Substring(s_localeNamesIndices[indexToLocaleNamesIndices],
s_localeNamesIndices[indexToLocaleNamesIndices + 1] -
return -1;
}
- Contract.Assert((s_localeNamesIndices.Length-1 == (s_nameIndexToNumericData.Length/NUMERIC_LOCALE_DATA_COUNT_PER_ROW)) &&
+ Debug.Assert((s_localeNamesIndices.Length-1 == (s_nameIndexToNumericData.Length/NUMERIC_LOCALE_DATA_COUNT_PER_ROW)) &&
index < s_localeNamesIndices.Length);
return s_nameIndexToNumericData[index * NUMERIC_LOCALE_DATA_COUNT_PER_ROW + (int) part];
return null;
}
- Contract.Assert(s_localeNamesIndices.Length-1 == (c_threeLetterWindowsLanguageName.Length / 3));
+ Debug.Assert(s_localeNamesIndices.Length-1 == (c_threeLetterWindowsLanguageName.Length / 3));
return c_threeLetterWindowsLanguageName.Substring(index * 3, 3);
}
return ""; // fallback to invariant
}
- Contract.Assert(indexToIndicesTable < s_localeNamesIndices.Length-1);
+ Debug.Assert(indexToIndicesTable < s_localeNamesIndices.Length-1);
return c_localeNames.Substring(s_localeNamesIndices[indexToIndicesTable],
s_localeNamesIndices[indexToIndicesTable+1] - s_localeNamesIndices[indexToIndicesTable]);
int index;
int result;
- Contract.Assert(s_localeNamesIndices[s_localeNamesIndices.Length - 1] == c_localeNames.Length);
+ Debug.Assert(s_localeNamesIndices[s_localeNamesIndices.Length - 1] == c_localeNames.Length);
name = CultureData.AnsiToLower(name);
{
index = ((right - left) / 2) + left;
- Contract.Assert(index < s_localeNamesIndices.Length - 1);
+ Debug.Assert(index < s_localeNamesIndices.Length - 1);
result = CompareOrdinal(name, c_localeNames, s_localeNamesIndices[index], s_localeNamesIndices[index + 1] - s_localeNamesIndices[index]);
if (result == 0)
{
// Walk the remaining elements (it'll be 3 or fewer).
for (; left <= right; left++)
{
- Contract.Assert(left < s_localeNamesIndices.Length - 1);
+ Debug.Assert(left < s_localeNamesIndices.Length - 1);
if (CompareOrdinal(name, c_localeNames, s_localeNamesIndices[left], s_localeNamesIndices[left + 1] - s_localeNamesIndices[left]) == 0)
{
return (left);
// See the LICENSE file in the project root for more information.
using System;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Globalization
private static int MonthFromOrdinalDay(int ordinalDay)
{
- Contract.Assert(ordinalDay <= 366);
+ Debug.Assert(ordinalDay <= 366);
int index = 0;
while (ordinalDay > DaysToMonth[index])
index++;
private static int DaysInPreviousMonths(int month)
{
- Contract.Assert(1 <= month && month <= 12);
+ Debug.Assert(1 <= month && month <= 12);
--month; // months are one based but for calculations use 0 based
return DaysToMonth[month];
}
long yearStart = CalendricalCalculationsHelper.PersianNewYearOnOrBefore(NumDays);
int y = (int)(Math.Floor(((yearStart - PersianEpoch) / CalendricalCalculationsHelper.MeanTropicalYearInDays) + 0.5)) + 1;
- Contract.Assert(y >= 1);
+ Debug.Assert(y >= 1);
if (part == DatePartYear)
{
}
int m = MonthFromOrdinalDay(ordinalDay);
- Contract.Assert(ordinalDay >= 1);
- Contract.Assert(m >= 1 && m <= 12);
+ Debug.Assert(ordinalDay >= 1);
+ Debug.Assert(m >= 1 && m <= 12);
if (part == DatePartMonth)
{
return m;
}
int d = ordinalDay - DaysInPreviousMonths(m);
- Contract.Assert(1 <= d);
- Contract.Assert(d <= 31);
+ Debug.Assert(1 <= d);
+ Debug.Assert(d <= 31);
//
// Calculate the Persian Day.
int daysInMonth = DaysToMonth[month] - DaysToMonth[month - 1];
if ((month == MonthsPerYear) && !IsLeapYear(year))
{
- Contract.Assert(daysInMonth == 30);
+ Debug.Assert(daysInMonth == 30);
--daysInMonth;
}
return daysInMonth;
////////////////////////////////////////////////////////////////////////////
using System;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
{
get
{
- Contract.Assert(_name != null, "Expected RegionInfo._name to be populated already");
+ Debug.Assert(_name != null, "Expected RegionInfo._name to be populated already");
return (_name);
}
}
using System;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[System.Runtime.InteropServices.ComVisible(true)]
byte[] key1Data = sortkey1._keyData;
byte[] key2Data = sortkey2._keyData;
- Contract.Assert(key1Data != null, "key1Data != null");
- Contract.Assert(key2Data != null, "key2Data != null");
+ Debug.Assert(key1Data != null, "key1Data != null");
+ Debug.Assert(key2Data != null, "key2Data != null");
if (key1Data.Length == 0)
{
////////////////////////////////////////////////////////////////////////////
using System;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
internal static int GetCurrentTextElementLen(string str, int index, int len, ref UnicodeCategory ucCurrent, ref int currentCharCount)
{
- Contract.Assert(index >= 0 && len >= 0, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
- Contract.Assert(index < len, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
+ Debug.Assert(index >= 0 && len >= 0, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
+ Debug.Assert(index < len, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
if (index + currentCharCount == len)
{
// This is the last character/surrogate in the string.
////////////////////////////////////////////////////////////////////////////
using System.Collections;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
internal TextElementEnumerator(String str, int startIndex, int strLen)
{
- Contract.Assert(str != null, "TextElementEnumerator(): str != null");
- Contract.Assert(startIndex >= 0 && strLen >= 0, "TextElementEnumerator(): startIndex >= 0 && strLen >= 0");
- Contract.Assert(strLen >= startIndex, "TextElementEnumerator(): strLen >= startIndex");
+ Debug.Assert(str != null, "TextElementEnumerator(): str != null");
+ Debug.Assert(startIndex >= 0 && strLen >= 0, "TextElementEnumerator(): startIndex >= 0 && strLen >= 0");
+ Debug.Assert(strLen >= startIndex, "TextElementEnumerator(): strLen >= startIndex");
_str = str;
_startIndex = startIndex;
_strLen = strLen;
// 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.Diagnostics.Contracts;
using System.Security;
using System.Text;
[SecuritySafeCritical]
private unsafe string ChangeCase(string s, bool toUpper)
{
- Contract.Assert(s != null);
+ Debug.Assert(s != null);
if (s.Length == 0)
{
private bool NeedsTurkishCasing(string localeName)
{
- Contract.Assert(localeName != null);
+ Debug.Assert(localeName != null);
return CultureInfo.GetCultureInfo(localeName).CompareInfo.Compare("\u0131", "I", CompareOptions.IgnoreCase) == 0;
}
// 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.Diagnostics.Contracts;
namespace System.Globalization
private unsafe string ChangeCase(string s, bool toUpper)
{
- Contract.Assert(s != null);
+ Debug.Assert(s != null);
//
// Get the length of the string.
throw new InvalidOperationException(SR.InvalidOperation_ReadOnly);
}
- Contract.Assert(ret == nLengthInput, "Expected getting the same length of the original string");
+ Debug.Assert(ret == nLengthInput, "Expected getting the same length of the original string");
return result;
}
}
////////////////////////////////////////////////////////////////////////////
using System;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime;
using System.Runtime.CompilerServices;
private static int AddNonLetter(ref StringBuilder result, ref String input, int inputIndex, int charLen)
{
- Contract.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddNonLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!");
+ Debug.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddNonLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!");
if (charLen == 2)
{
// Surrogate pair
private int AddTitlecaseLetter(ref StringBuilder result, ref String input, int inputIndex, int charLen)
{
- Contract.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddTitlecaseLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!");
+ Debug.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddTitlecaseLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!");
// for surrogate pairs do a simple ToUpper operation on the substring
if (charLen == 2)
private unsafe int GetCaseInsensitiveHashCodeSlow(String str)
{
- Contract.Assert(str != null);
+ Debug.Assert(str != null);
string upper = ToUpper(str);
// See the LICENSE file in the project root for more information.
using System;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Globalization
=========================ConvertHijriToGregorian============================*/
private static void ConvertHijriToGregorian(int HijriYear, int HijriMonth, int HijriDay, ref int yg, ref int mg, ref int dg)
{
- Contract.Assert((HijriYear >= MinCalendarYear) && (HijriYear <= MaxCalendarYear), "Hijri year is out of range.");
- Contract.Assert(HijriMonth >= 1, "Hijri month is out of range.");
- Contract.Assert(HijriDay >= 1, "Hijri day is out of range.");
+ Debug.Assert((HijriYear >= MinCalendarYear) && (HijriYear <= MaxCalendarYear), "Hijri year is out of range.");
+ Debug.Assert(HijriMonth >= 1, "Hijri month is out of range.");
+ Debug.Assert(HijriDay >= 1, "Hijri day is out of range.");
int index, b, nDays = HijriDay - 1;
DateTime dt;
TimeSpan ts;
int yh1 = 0, mh1 = 0, dh1 = 0;
- Contract.Assert((time.Ticks >= minDate.Ticks) && (time.Ticks <= maxDate.Ticks), "Gregorian date is out of range.");
+ Debug.Assert((time.Ticks >= minDate.Ticks) && (time.Ticks <= maxDate.Ticks), "Gregorian date is out of range.");
// Find the index where we should start our search by quessing the Hijri year that we will be in HijriYearInfo.
// A Hijri year is 354 or 355 days. Use 355 days so that we will search from a lower index.
{
int days = 0, b;
- Contract.Assert((year >= MinCalendarYear) && (year <= MaxCalendarYear), "Hijri year is out of range.");
+ Debug.Assert((year >= MinCalendarYear) && (year <= MaxCalendarYear), "Hijri year is out of range.");
b = s_hijriYearInfo[year - MinCalendarYear].HijriMonthsLengthFlags;
days = days + 29 + (b & 1); /* Add the months lengths before mh */
b = b >> 1;
}
- Contract.Assert((days == 354) || (days == 355), "Hijri year has to be 354 or 355 days.");
+ Debug.Assert((days == 354) || (days == 355), "Hijri year has to be 354 or 355 days.");
return days;
}
// See the LICENSE file in the project root for more information.
using System;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
private Thread AsThread()
{
- Contract.Assert(this is Thread);
+ Debug.Assert(this is Thread);
return (Thread)this;
}
#if FEATURE_COMINTEROP_APARTMENT_SUPPORT
return (ApartmentState)GetApartmentStateNative();
#else // !FEATURE_COMINTEROP_APARTMENT_SUPPORT
- Contract.Assert(false); // the Thread class in CoreFX should have handled this case
+ Debug.Assert(false); // the Thread class in CoreFX should have handled this case
return ApartmentState.MTA;
#endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT
}
#if FEATURE_COMINTEROP_APARTMENT_SUPPORT
return SetApartmentStateHelper(state, false);
#else // !FEATURE_COMINTEROP_APARTMENT_SUPPORT
- Contract.Assert(false); // the Thread class in CoreFX should have handled this case
+ Debug.Assert(false); // the Thread class in CoreFX should have handled this case
return false;
#endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public void DisableComObjectEagerCleanup()
{
- Contract.Assert(false); // the Thread class in CoreFX should have handled this case
+ Debug.Assert(false); // the Thread class in CoreFX should have handled this case
}
#endif // FEATURE_COMINTEROP
using System.Text;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
#if FEATURE_EXCEPTION_NOTIFICATIONS
using System.Runtime.ExceptionServices;
if (s_flags == 0)
s_flags = nGetAppXFlags();
- Contract.Assert(s_flags != 0);
+ Debug.Assert(s_flags != 0);
return s_flags;
}
}
/// </summary>
private void CreateAppDomainManager()
{
- Contract.Assert(_domainManager == null, "_domainManager == null");
+ Debug.Assert(_domainManager == null, "_domainManager == null");
AppDomainSetup adSetup = FusionStore;
#if FEATURE_VERSIONING
// for perf, we don't intialize the _compatFlags dictionary when we don't need to. However, we do need to make a
// note that we've run this method, because IsCompatibilityFlagsSet needs to return different values for the
// case where the compat flags have been setup.
- Contract.Assert(!_compatFlagsInitialized);
+ Debug.Assert(!_compatFlagsInitialized);
_compatFlagsInitialized = true;
CompatibilitySwitches.InitializeSwitches();
TargetFrameworkAttribute[] attrs = (TargetFrameworkAttribute[])assembly.GetCustomAttributes(typeof(TargetFrameworkAttribute));
if (attrs != null && attrs.Length > 0)
{
- Contract.Assert(attrs.Length == 1);
+ Debug.Assert(attrs.Length == 1);
targetFrameworkName = attrs[0].FrameworkName;
_FusionStore.TargetFrameworkName = targetFrameworkName;
}
/// </summary>
private void SetAppDomainManagerType(string assembly, string type)
{
- Contract.Assert(assembly != null, "assembly != null");
- Contract.Assert(type != null, "type != null");
+ Debug.Assert(assembly != null, "assembly != null");
+ Debug.Assert(type != null, "type != null");
SetAppDomainManagerType(GetNativeHandle(), assembly, type);
}
case (int) AppDomainSetup.LoaderInformation.ApplicationNameValue:
return FusionStore.ApplicationName;
default:
- Contract.Assert(false, "Need to handle new LoaderInformation value in AppDomain.GetData()");
+ Debug.Assert(false, "Need to handle new LoaderInformation value in AppDomain.GetData()");
return null;
}
}
internal AppDomainSetup FusionStore
{
get {
- Contract.Assert(_FusionStore != null,
+ Debug.Assert(_FusionStore != null,
"Fusion store has not been correctly setup in this domain");
return _FusionStore;
}
private void SetupLoaderOptimization(LoaderOptimization policy)
{
if(policy != LoaderOptimization.NotSpecified) {
- Contract.Assert(FusionStore.LoaderOptimization == LoaderOptimization.NotSpecified,
+ Debug.Assert(FusionStore.LoaderOptimization == LoaderOptimization.NotSpecified,
"It is illegal to change the Loader optimization on a domain");
FusionStore.LoaderOptimization = policy;
using System.Security;
using System.Security.Policy;
using Path = System.IO.Path;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Collections.Generic;
if(String.IsNullOrEmpty(s))
return -1;
- Contract.Assert('A' == ACTAG_APP_BASE_URL[0] , "Assumption violated");
+ Debug.Assert('A' == ACTAG_APP_BASE_URL[0] , "Assumption violated");
if (s[0]=='A' && s == ACTAG_APP_BASE_URL)
return (int)LoaderInformation.ApplicationBaseValue;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using System.Security;
+ using System.Diagnostics;
using System.Security.Permissions;
using System.Diagnostics.Contracts;
private static int GetMedian(int low, int hi) {
// Note both may be negative, if we are dealing with arrays w/ negative lower bounds.
Contract.Requires(low <= hi);
- Contract.Assert( hi - low >= 0, "Length overflow!");
+ Debug.Assert( hi - low >= 0, "Length overflow!");
return low + ((hi - low) >> 1);
}
private int _endIndex; // cache array length, since it's a little slow.
internal SZArrayEnumerator(Array array) {
- Contract.Assert(array.Rank == 1 && array.GetLowerBound(0) == 0, "SZArrayEnumerator only works on single dimension arrays w/ a lower bound of zero.");
+ Debug.Assert(array.Rank == 1 && array.GetLowerBound(0) == 0, "SZArrayEnumerator only works on single dimension arrays w/ a lower bound of zero.");
_array = array;
_index = -1;
_endIndex = array.Length;
sealed class SZArrayHelper {
// It is never legal to instantiate this class.
private SZArrayHelper() {
- Contract.Assert(false, "Hey! How'd I get here?");
+ Debug.Assert(false, "Hey! How'd I get here?");
}
// -----------------------------------------------------------
internal SZGenericArrayEnumerator(T[] array, int endIndex) {
// We allow passing null array in case of empty enumerator.
- Contract.Assert(array != null || endIndex == -1, "endIndex should be -1 in the case of a null array (for the empty enumerator).");
+ Debug.Assert(array != null || endIndex == -1, "endIndex should be -1 in the case of a null array (for the empty enumerator).");
_array = array;
_index = -1;
_endIndex = endIndex;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System
{
get
{
- Contract.Assert( (null == _array && 0 == _offset && 0 == _count)
+ Debug.Assert( (null == _array && 0 == _offset && 0 == _count)
|| (null != _array && _offset >= 0 && _count >= 0 && _offset + _count <= _array.Length),
"ArraySegment is invalid");
// after reading each field out of an ArraySegment into their stack.
Contract.Ensures(Contract.Result<int>() >= 0);
- Contract.Assert( (null == _array && 0 == _offset && 0 == _count)
+ Debug.Assert( (null == _array && 0 == _offset && 0 == _count)
|| (null != _array && _offset >= 0 && _count >= 0 && _offset + _count <= _array.Length),
"ArraySegment is invalid");
// after reading each field out of an ArraySegment into their stack.
Contract.Ensures(Contract.Result<int>() >= 0);
- Contract.Assert( (null == _array && 0 == _offset && 0 == _count)
+ Debug.Assert( (null == _array && 0 == _offset && 0 == _count)
|| (null != _array && _offset >= 0 && _count >= 0 && _offset + _count <= _array.Length),
"ArraySegment is invalid");
int index = System.Array.IndexOf<T>(_array, item, _offset, _count);
- Contract.Assert(index == -1 ||
+ Debug.Assert(index == -1 ||
(index >= _offset && index < _offset + _count));
return index >= 0 ? index - _offset : -1;
int index = System.Array.IndexOf<T>(_array, item, _offset, _count);
- Contract.Assert(index == -1 ||
+ Debug.Assert(index == -1 ||
(index >= _offset && index < _offset + _count));
return index >= 0;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Globalization;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Security;
using System.Security.Permissions;
return element.IsDefined(attributeType, false);
default:
- Contract.Assert(false, "Invalid type for ParameterInfo member in Attribute class");
+ Debug.Assert(false, "Invalid type for ParameterInfo member in Attribute class");
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidParamInfo"));
}
}
// Attributes can only contain single-dimension arrays, so we don't need to worry about
// multidimensional arrays.
- Contract.Assert(thisValueArray.Rank == 1 && thatValueArray.Rank == 1);
+ Debug.Assert(thisValueArray.Rank == 1 && thatValueArray.Rank == 1);
for (int j = 0; j < thisValueArray.Length; j++)
{
if (!AreFieldValuesEqual(thisValueArray.GetValue(j), thatValueArray.GetValue(j)))
// An object of type Attribute will cause a stack overflow.
// However, this should never happen because custom attributes cannot contain values other than
// constants, single-dimensional arrays and typeof expressions.
- Contract.Assert(!(thisValue is Attribute));
+ Debug.Assert(!(thisValue is Attribute));
if (!thisValue.Equals(thatValue))
return false;
}
using System;
using System.Runtime.CompilerServices;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Security;
}
private static char GetHexValue(int i) {
- Contract.Assert( i >=0 && i <16, "i is out of range.");
+ Debug.Assert( i >=0 && i <16, "i is out of range.");
if (i<10) {
return (char)(i + '0');
}
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Security;
using System.Runtime;
//
internal unsafe static int IndexOfByte(byte* src, byte value, int index, int count)
{
- Contract.Assert(src != null, "src should not be null");
+ Debug.Assert(src != null, "src should not be null");
byte* pByte = src + index;
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal unsafe static void Memcpy(byte[] dest, int destIndex, byte* src, int srcIndex, int len) {
- Contract.Assert( (srcIndex >= 0) && (destIndex >= 0) && (len >= 0), "Index and length must be non-negative!");
- Contract.Assert(dest.Length - destIndex >= len, "not enough bytes in dest");
+ Debug.Assert( (srcIndex >= 0) && (destIndex >= 0) && (len >= 0), "Index and length must be non-negative!");
+ Debug.Assert(dest.Length - destIndex >= len, "not enough bytes in dest");
// If dest has 0 elements, the fixed statement will throw an
// IndexOutOfRangeException. Special-case 0-byte copies.
if (len==0)
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal unsafe static void Memcpy(byte* pDest, int destIndex, byte[] src, int srcIndex, int len)
{
- Contract.Assert( (srcIndex >= 0) && (destIndex >= 0) && (len >= 0), "Index and length must be non-negative!");
- Contract.Assert(src.Length - srcIndex >= len, "not enough bytes in src");
+ Debug.Assert( (srcIndex >= 0) && (destIndex >= 0) && (len >= 0), "Index and length must be non-negative!");
+ Debug.Assert(src.Length - srcIndex >= len, "not enough bytes in src");
// If dest has 0 elements, the fixed statement will throw an
// IndexOutOfRangeException. Special-case 0-byte copies.
if (len==0)
#else // ARM
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
internal unsafe static void Memcpy(byte* dest, byte* src, int len) {
- Contract.Assert(len >= 0, "Negative length in memcopy!");
+ Debug.Assert(len >= 0, "Negative length in memcopy!");
Memmove(dest, src, (uint)len);
}
#endif // ARM
// We know due to the above switch-case that this loop will always run 1 iteration; max
// bytes we copy before checking is 23 (7 to align the pointers, 16 for 1 iteration) so
// the switch handles lengths 0-22.
- Contract.Assert(end >= 7 && i <= end);
+ Debug.Assert(end >= 7 && i <= end);
// This is separated out into a different variable, so the i + 16 addition can be
// performed at the start of the pipeline and the loop condition does not have
using System.Runtime;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[System.Runtime.InteropServices.ComVisible(true)]
// Return the Unicode category for Unicode character <= 0x00ff.
private static UnicodeCategory GetLatin1UnicodeCategory(char ch) {
- Contract.Assert(IsLatin1(ch), "Char.GetLatin1UnicodeCategory(): ch should be <= 007f");
+ Debug.Assert(IsLatin1(ch), "Char.GetLatin1UnicodeCategory(): ch should be <= 007f");
return (UnicodeCategory)(categoryForLatin1[(int)ch]);
}
[Conditional("DEBUG")]
private void Assert(bool condition)
{
- Contract.Assert(condition);
+ Debug.Assert(condition);
}
/// <summary>
int index = 0;
foreach (T element in collection)
{
- Contract.Assert(index >= 0 && index < SEGMENT_SIZE);
+ Debug.Assert(index >= 0 && index < SEGMENT_SIZE);
localTail.UnsafeAdd(element);
index++;
[OnDeserialized]
private void OnDeserialized(StreamingContext context)
{
- Contract.Assert(m_serializationArray != null);
+ Debug.Assert(m_serializationArray != null);
InitializeFromCollection(m_serializationArray);
m_serializationArray = null;
}
m_array = new T[SEGMENT_SIZE];
m_state = new VolatileBool[SEGMENT_SIZE]; //all initialized to false
m_high = -1;
- Contract.Assert(index >= 0);
+ Debug.Assert(index >= 0);
m_index = index;
m_source = source;
}
/// <param name="value"></param>
internal void UnsafeAdd(T value)
{
- Contract.Assert(m_high < SEGMENT_SIZE - 1);
+ Debug.Assert(m_high < SEGMENT_SIZE - 1);
m_high++;
m_array[m_high] = value;
m_state[m_high].m_value = true;
/// <returns>the reference to the new Segment</returns>
internal Segment UnsafeGrow()
{
- Contract.Assert(m_high >= SEGMENT_SIZE - 1);
+ Debug.Assert(m_high >= SEGMENT_SIZE - 1);
Segment newSegment = new Segment(m_index + 1, m_source); //m_index is Int64, we don't need to worry about overflow
m_next = newSegment;
return newSegment;
//no CAS is needed, since there is no contention (other threads are blocked, busy waiting)
Segment newSegment = new Segment(m_index + 1, m_source); //m_index is Int64, we don't need to worry about overflow
m_next = newSegment;
- Contract.Assert(m_source.m_tail == this);
+ Debug.Assert(m_source.m_tail == this);
m_source.m_tail = m_next;
}
{
spinLocal.SpinOnce();
}
- Contract.Assert(m_source.m_head == this);
+ Debug.Assert(m_source.m_head == this);
m_source.m_head = m_next;
}
return true;
using System.Collections.Generic;
using System.Security.Permissions;
using System.Threading;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
//perform deferred allocating of the local variables.
if (m_localOffset == null)
{
- Contract.Assert(m_currentChunkSize == null);
+ Debug.Assert(m_currentChunkSize == null);
m_localOffset = new SharedInt(-1);
m_currentChunkSize = new SharedInt(0);
m_doublingCountdown = CHUNK_DOUBLING_RATE;
{
// The second part of the || condition is necessary to handle the case when MoveNext() is called
// after a previous MoveNext call returned false.
- Contract.Assert(m_localOffset.Value == m_currentChunkSize.Value - 1 || m_currentChunkSize.Value == 0);
+ Debug.Assert(m_localOffset.Value == m_currentChunkSize.Value - 1 || m_currentChunkSize.Value == 0);
//set the requested chunk size to a proper value
int requestedChunkSize;
// Decrement your doubling countdown
m_doublingCountdown--;
- Contract.Assert(requestedChunkSize > 0 && requestedChunkSize <= m_maxChunkSize);
+ Debug.Assert(requestedChunkSize > 0 && requestedChunkSize <= m_maxChunkSize);
//GrabNextChunk will update the value of m_currentChunkSize
if (GrabNextChunk(requestedChunkSize))
{
- Contract.Assert(m_currentChunkSize.Value <= requestedChunkSize && m_currentChunkSize.Value > 0);
+ Debug.Assert(m_currentChunkSize.Value <= requestedChunkSize && m_currentChunkSize.Value > 0);
m_localOffset.Value = 0;
return true;
}
/// </returns>
internal bool GrabChunk_Single(KeyValuePair<long,TSource>[] destArray, int requestedChunkSize, ref int actualNumElementsGrabbed)
{
- Contract.Assert(m_useSingleChunking, "Expected m_useSingleChecking to be true");
- Contract.Assert(requestedChunkSize == 1, "Got requested chunk size of " + requestedChunkSize + " when single-chunking was on");
- Contract.Assert(actualNumElementsGrabbed == 0, "Expected actualNumElementsGrabbed == 0, instead it is " + actualNumElementsGrabbed);
- Contract.Assert(destArray.Length == 1, "Expected destArray to be of length 1, instead its length is " + destArray.Length);
+ Debug.Assert(m_useSingleChunking, "Expected m_useSingleChecking to be true");
+ Debug.Assert(requestedChunkSize == 1, "Got requested chunk size of " + requestedChunkSize + " when single-chunking was on");
+ Debug.Assert(actualNumElementsGrabbed == 0, "Expected actualNumElementsGrabbed == 0, instead it is " + actualNumElementsGrabbed);
+ Debug.Assert(destArray.Length == 1, "Expected destArray to be of length 1, instead its length is " + destArray.Length);
lock (m_sharedLock)
{
/// </returns>
internal bool GrabChunk_Buffered(KeyValuePair<long,TSource>[] destArray, int requestedChunkSize, ref int actualNumElementsGrabbed)
{
- Contract.Assert(requestedChunkSize > 0);
- Contract.Assert(!m_useSingleChunking, "Did not expect to be in single-chunking mode");
+ Debug.Assert(requestedChunkSize > 0);
+ Debug.Assert(!m_useSingleChunking, "Did not expect to be in single-chunking mode");
TryCopyFromFillBuffer(destArray, requestedChunkSize, ref actualNumElementsGrabbed);
while( m_activeCopiers > 0) sw.SpinOnce();
}
- Contract.Assert(m_sharedIndex != null); //already been allocated in MoveNext() before calling GrabNextChunk
+ Debug.Assert(m_sharedIndex != null); //already been allocated in MoveNext() before calling GrabNextChunk
// Now's the time to actually enumerate the source
/// </returns>
override protected bool GrabNextChunk(int requestedChunkSize)
{
- Contract.Assert(requestedChunkSize > 0);
+ Debug.Assert(requestedChunkSize > 0);
if (HasNoElementsLeft)
{
{
//we only set it from false to true once
//we should never set it back in any circumstances
- Contract.Assert(value);
- Contract.Assert(!m_hasNoElementsLeft.Value);
+ Debug.Assert(value);
+ Debug.Assert(!m_hasNoElementsLeft.Value);
m_hasNoElementsLeft.Value = true;
}
}
{
throw new InvalidOperationException(Environment.GetResourceString("PartitionerStatic_CurrentCalledBeforeMoveNext"));
}
- Contract.Assert(m_localList != null);
- Contract.Assert(m_localOffset.Value >= 0 && m_localOffset.Value < m_currentChunkSize.Value);
+ Debug.Assert(m_localList != null);
+ Debug.Assert(m_localOffset.Value >= 0 && m_localOffset.Value < m_currentChunkSize.Value);
return (m_localList[m_localOffset.Value]);
}
}
/// </returns>
override protected bool GrabNextChunk(int requestedChunkSize)
{
- Contract.Assert(requestedChunkSize > 0);
+ Debug.Assert(requestedChunkSize > 0);
while (!HasNoElementsLeft)
{
- Contract.Assert(m_sharedIndex != null);
+ Debug.Assert(m_sharedIndex != null);
// use the new Volatile.Read method because it is cheaper than Interlocked.Read on AMD64 architecture
long oldSharedIndex = Volatile.Read(ref m_sharedIndex.Value);
{
get
{
- Contract.Assert(m_sharedIndex != null);
+ Debug.Assert(m_sharedIndex != null);
// use the new Volatile.Read method because it is cheaper than Interlocked.Read on AMD64 architecture
return Volatile.Read(ref m_sharedIndex.Value) >= SourceCount - 1;
}
set
{
- Contract.Assert(false);
+ Debug.Assert(false);
}
}
throw new InvalidOperationException(Environment.GetResourceString("PartitionerStatic_CurrentCalledBeforeMoveNext"));
}
- Contract.Assert(m_localOffset.Value >= 0 && m_localOffset.Value < m_currentChunkSize.Value);
+ Debug.Assert(m_localOffset.Value >= 0 && m_localOffset.Value < m_currentChunkSize.Value);
return new KeyValuePair<long, TSource>(m_startIndex + m_localOffset.Value,
m_sharedReader[m_startIndex + m_localOffset.Value]);
}
throw new InvalidOperationException(Environment.GetResourceString("PartitionerStatic_CurrentCalledBeforeMoveNext"));
}
- Contract.Assert(m_localOffset.Value >= 0 && m_localOffset.Value < m_currentChunkSize.Value);
+ Debug.Assert(m_localOffset.Value >= 0 && m_localOffset.Value < m_currentChunkSize.Value);
return new KeyValuePair<long, TSource>(m_startIndex + m_localOffset.Value,
m_sharedReader[m_startIndex + m_localOffset.Value]);
}
internal StaticIndexRangePartitionerForIList(IList<TSource> list)
: base()
{
- Contract.Assert(list != null);
+ Debug.Assert(list != null);
m_list = list;
}
override protected int SourceCount
internal StaticIndexRangePartitionForIList(IList<TSource> list, int startIndex, int endIndex)
: base(startIndex, endIndex)
{
- Contract.Assert(startIndex >= 0 && endIndex <= list.Count - 1);
+ Debug.Assert(startIndex >= 0 && endIndex <= list.Count - 1);
m_list = list;
}
throw new InvalidOperationException(Environment.GetResourceString("PartitionerStatic_CurrentCalledBeforeMoveNext"));
}
- Contract.Assert(m_offset >= m_startIndex && m_offset <= m_endIndex);
+ Debug.Assert(m_offset >= m_startIndex && m_offset <= m_endIndex);
return (new KeyValuePair<long, TSource>(m_offset, m_list[m_offset]));
}
}
internal StaticIndexRangePartitionerForArray(TSource[] array)
: base()
{
- Contract.Assert(array != null);
+ Debug.Assert(array != null);
m_array = array;
}
override protected int SourceCount
internal StaticIndexRangePartitionForArray(TSource[] array, int startIndex, int endIndex)
: base(startIndex, endIndex)
{
- Contract.Assert(startIndex >= 0 && endIndex <= array.Length - 1);
+ Debug.Assert(startIndex >= 0 && endIndex <= array.Length - 1);
m_array = array;
}
throw new InvalidOperationException(Environment.GetResourceString("PartitionerStatic_CurrentCalledBeforeMoveNext"));
}
- Contract.Assert(m_offset >= m_startIndex && m_offset <= m_endIndex);
+ Debug.Assert(m_offset >= m_startIndex && m_offset <= m_endIndex);
return (new KeyValuePair<long, TSource>(m_offset, m_array[m_offset]));
}
}
}
else
{
- Contract.Assert((DEFAULT_BYTES_PER_CHUNK % IntPtr.Size) == 0, "bytes per chunk should be a multiple of pointer size");
+ Debug.Assert((DEFAULT_BYTES_PER_CHUNK % IntPtr.Size) == 0, "bytes per chunk should be a multiple of pointer size");
chunkSize = (DEFAULT_BYTES_PER_CHUNK / IntPtr.Size);
}
return chunkSize;
using System;
using System.Globalization;
using System.Runtime.CompilerServices;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.Versioning;
public void Sort(T[] keys, int index, int length, IComparer<T> comparer)
{
- Contract.Assert(keys != null, "Check the arguments in the caller!");
- Contract.Assert( index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
+ Debug.Assert(keys != null, "Check the arguments in the caller!");
+ Debug.Assert( index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
// Add a try block here to detect IComparers (or their
// underlying IComparables, etc) that are bogus.
internal static void Sort(T[] keys, int index, int length, Comparison<T> comparer)
{
- Contract.Assert(keys != null, "Check the arguments in the caller!");
- Contract.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
- Contract.Assert(comparer != null, "Check the arguments in the caller!");
+ Debug.Assert(keys != null, "Check the arguments in the caller!");
+ Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
+ Debug.Assert(comparer != null, "Check the arguments in the caller!");
// Add a try block here to detect bogus comparisons
try
public void Sort(T[] keys, int index, int length, IComparer<T> comparer)
{
- Contract.Assert(keys != null, "Check the arguments in the caller!");
- Contract.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
+ Debug.Assert(keys != null, "Check the arguments in the caller!");
+ Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
try
{
public int BinarySearch(T[] array, int index, int length, T value, IComparer<T> comparer)
{
- Contract.Assert(array != null, "Check the arguments in the caller!");
- Contract.Assert(index >= 0 && length >= 0 && (array.Length - index >= length), "Check the arguments in the caller!");
+ Debug.Assert(array != null, "Check the arguments in the caller!");
+ Debug.Assert(index >= 0 && length >= 0 && (array.Length - index >= length), "Check the arguments in the caller!");
try
{
public void Sort(TKey[] keys, TValue[] values, int index, int length, IComparer<TKey> comparer)
{
- Contract.Assert(keys != null, "Check the arguments in the caller!"); // Precondition on interface method
- Contract.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
+ Debug.Assert(keys != null, "Check the arguments in the caller!"); // Precondition on interface method
+ Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
// Add a try block here to detect IComparers (or their
// underlying IComparables, etc) that are bogus.
{
public void Sort(TKey[] keys, TValue[] values, int index, int length, IComparer<TKey> comparer)
{
- Contract.Assert(keys != null, "Check the arguments in the caller!");
- Contract.Assert( index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
+ Debug.Assert(keys != null, "Check the arguments in the caller!");
+ Debug.Assert( index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
// Add a try block here to detect IComparers (or their
// underlying IComparables, etc) that are bogus.
using System;
using System.Collections;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
//using System.Globalization;
using System.Runtime.CompilerServices;
{
public Int32EnumComparer()
{
- Contract.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!");
+ Debug.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!");
}
// Used by the serialization engine.
{
public UInt32EnumComparer()
{
- Contract.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!");
+ Debug.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!");
}
// Used by the serialization engine.
{
public Int64EnumComparer()
{
- Contract.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!");
+ Debug.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!");
}
// Used by the serialization engine.
{
public UInt64EnumComparer()
{
- Contract.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!");
+ Debug.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!");
}
// Used by the serialization engine.
}
private void Resize(int newSize, bool forceNewHashCodes) {
- Contract.Assert(newSize >= entries.Length);
+ Debug.Assert(newSize >= entries.Length);
int[] newBuckets = new int[newSize];
for (int i = 0; i < newBuckets.Length; i++) newBuckets[i] = -1;
Entry[] newEntries = new Entry[newSize];
private void AddEnumerable(IEnumerable<T> enumerable)
{
- Contract.Assert(enumerable != null);
- Contract.Assert(!(enumerable is ICollection<T>), "We should have optimized for this beforehand.");
+ Debug.Assert(enumerable != null);
+ Debug.Assert(!(enumerable is ICollection<T>), "We should have optimized for this beforehand.");
using (IEnumerator<T> en = enumerable.GetEnumerator())
{
loadsize = (int)(this.loadFactor * hashsize);
isWriterInProgress = false;
// Based on the current algorithm, loadsize must be less than hashsize.
- Contract.Assert( loadsize < hashsize, "Invalid hashtable loadsize!");
+ Debug.Assert( loadsize < hashsize, "Invalid hashtable loadsize!");
}
// Constructs a new hashtable with the given initial capacity and load
// Removes all entries from this hashtable.
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public virtual void Clear() {
- Contract.Assert(!isWriterInProgress, "Race condition detected in usages of Hashtable - multiple threads appear to be writing to a Hashtable instance simultaneously! Don't do that - use Hashtable.Synchronized.");
+ Debug.Assert(!isWriterInProgress, "Race condition detected in usages of Hashtable - multiple threads appear to be writing to a Hashtable instance simultaneously! Don't do that - use Hashtable.Synchronized.");
if (count == 0 && occupancy == 0)
return;
isWriterInProgress = false;
// minimun size of hashtable is 3 now and maximum loadFactor is 0.72 now.
- Contract.Assert(loadsize < newsize, "Our current implementaion means this is not possible.");
+ Debug.Assert(loadsize < newsize, "Our current implementaion means this is not possible.");
return;
}
//
protected virtual bool KeyEquals(Object item, Object key)
{
- Contract.Assert(key != null, "key can't be null here!");
+ Debug.Assert(key != null, "key can't be null here!");
if( Object.ReferenceEquals(buckets, item)) {
return false;
}
// If you see this assert, make sure load factor & count are reasonable.
// Then verify that our double hash function (h2, described at top of file)
// meets the requirements described above. You should never see this assert.
- Contract.Assert(false, "hash table insert failed! Load factor too high, or our double hashing function is incorrect.");
+ Debug.Assert(false, "hash table insert failed! Load factor too high, or our double hashing function is incorrect.");
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_HashInsertFailed"));
}
private void putEntry (bucket[] newBuckets, Object key, Object nvalue, int hashcode)
{
- Contract.Assert(hashcode >= 0, "hashcode >= 0"); // make sure collision bit (sign bit) wasn't set.
+ Debug.Assert(hashcode >= 0, "hashcode >= 0"); // make sure collision bit (sign bit) wasn't set.
uint seed = (uint) hashcode;
uint incr = (uint)(1 + ((seed * HashPrime) % ((uint)newBuckets.Length - 1)));
throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
}
Contract.EndContractBlock();
- Contract.Assert(!isWriterInProgress, "Race condition detected in usages of Hashtable - multiple threads appear to be writing to a Hashtable instance simultaneously! Don't do that - use Hashtable.Synchronized.");
+ Debug.Assert(!isWriterInProgress, "Race condition detected in usages of Hashtable - multiple threads appear to be writing to a Hashtable instance simultaneously! Don't do that - use Hashtable.Synchronized.");
uint seed;
uint incr;
// Note that this check works even when _items.Length overflowed thanks to the (uint) cast
if ((uint)newSize > MaxPrimeArrayLength && MaxPrimeArrayLength > oldSize)
{
- Contract.Assert( MaxPrimeArrayLength == GetPrime(MaxPrimeArrayLength), "Invalid MaxPrimeArrayLength");
+ Debug.Assert( MaxPrimeArrayLength == GetPrime(MaxPrimeArrayLength), "Invalid MaxPrimeArrayLength");
return MaxPrimeArrayLength;
}
public static IEqualityComparer GetRandomizedEqualityComparer(object comparer)
{
- Contract.Assert(comparer == null || comparer == System.Collections.Generic.EqualityComparer<string>.Default || comparer is IWellKnownStringEqualityComparer);
+ Debug.Assert(comparer == null || comparer == System.Collections.Generic.EqualityComparer<string>.Default || comparer is IWellKnownStringEqualityComparer);
if(comparer == null) {
return new System.Collections.Generic.RandomizedObjectEqualityComparer();
return cmp.GetRandomizedEqualityComparer();
}
- Contract.Assert(false, "Missing case in GetRandomizedEqualityComparer!");
+ Debug.Assert(false, "Missing case in GetRandomizedEqualityComparer!");
return null;
}
if(data == null)
{
data = new byte[bufferSize];
- Contract.Assert(bufferSize % 8 == 0, "We increment our current index by 8, so our buffer size must be a multiple of 8");
+ Debug.Assert(bufferSize % 8 == 0, "We increment our current index by 8, so our buffer size must be a multiple of 8");
}
Microsoft.Win32.Win32Native.Random(true, data, data.Length);
/// </summary>
new private List<TItem> Items {
get {
- Contract.Assert(base.Items is List<TItem>);
+ Debug.Assert(base.Items is List<TItem>);
return (List<TItem>)base.Items;
}
}
private void RemoveKey(TKey key) {
- Contract.Assert(key != null, "key shouldn't be null!");
+ Debug.Assert(key != null, "key shouldn't be null!");
if (dict != null) {
dict.Remove(key);
}
}
else {
// size can only be zero here.
- Contract.Assert( _size == 0, "Size is not zero");
+ Debug.Assert( _size == 0, "Size is not zero");
keys = emptyArray;
values = emptyArray;
}
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
#if _DEBUG
private static bool TriggerAsserts = DoAsserts();
private static bool DoAsserts() {
- Contract.Assert(ConvertTypes!=null, "[Convert.cctor]ConvertTypes!=null");
- Contract.Assert(ConvertTypes.Length == ((int)TypeCode.String + 1), "[Convert.cctor]ConvertTypes.Length == ((int)TypeCode.String + 1)");
- Contract.Assert(ConvertTypes[(int)TypeCode.Empty]==typeof(System.Empty),
+ Debug.Assert(ConvertTypes!=null, "[Convert.cctor]ConvertTypes!=null");
+ Debug.Assert(ConvertTypes.Length == ((int)TypeCode.String + 1), "[Convert.cctor]ConvertTypes.Length == ((int)TypeCode.String + 1)");
+ Debug.Assert(ConvertTypes[(int)TypeCode.Empty]==typeof(System.Empty),
"[Convert.cctor]ConvertTypes[(int)TypeCode.Empty]==typeof(System.Empty)");
- Contract.Assert(ConvertTypes[(int)TypeCode.String]==typeof(String),
+ Debug.Assert(ConvertTypes[(int)TypeCode.String]==typeof(String),
"[Convert.cctor]ConvertTypes[(int)TypeCode.String]==typeof(System.String)");
- Contract.Assert(ConvertTypes[(int)TypeCode.Int32]==typeof(int),
+ Debug.Assert(ConvertTypes[(int)TypeCode.Int32]==typeof(int),
"[Convert.cctor]ConvertTypes[(int)TypeCode.Int32]==typeof(int)");
return true;
}
// The validity of parameters much be checked by callers, thus we are Critical here.
- Contract.Assert(0 <= inputLength);
+ Debug.Assert(0 <= inputLength);
// We need to get rid of any trailing white spaces.
// Otherwise we would be rejecting input such as "abc= ":
// Compute the output length:
Int32 resultLength = FromBase64_ComputeResultLength(inputPtr, inputLength);
- Contract.Assert(0 <= resultLength);
+ Debug.Assert(0 <= resultLength);
// resultLength can be zero. We will still enter FromBase64_Decode and process the input.
// It may either simply write no bytes (e.g. input = " ") or throw (e.g. input = "ab").
}} // unchecked while
// 'd be nice to have an assert that we never get here, but CS0162: Unreachable code detected.
- // Contract.Assert(false, "We only leave the above loop by jumping; should never get here.");
+ // Debug.Assert(false, "We only leave the above loop by jumping; should never get here.");
// We jump here out of the loop if we hit an '=':
_EqualityCharEncountered:
- Contract.Assert(currCode == intEq);
+ Debug.Assert(currCode == intEq);
// Recall that inputPtr is now one position past where '=' was read.
// '=' can only be at the last input pos:
const UInt32 intEq = (UInt32) '=';
const UInt32 intSpace = (UInt32) ' ';
- Contract.Assert(0 <= inputLength);
+ Debug.Assert(0 <= inputLength);
Char* inputEndPtr = inputPtr + inputLength;
Int32 usefulInputLength = inputLength;
}
}
- Contract.Assert(0 <= usefulInputLength);
+ Debug.Assert(0 <= usefulInputLength);
// For legal input, we can assume that 0 <= padding < 3. But it may be more for illegal input.
// We will notice it at decode when we see a '=' at the wrong place.
- Contract.Assert(0 <= padding);
+ Debug.Assert(0 <= padding);
// Perf: reuse the variable that stored the number of '=' to store the number of bytes encoded by the
// last group that contains the '=':
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Security.Permissions;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
// DateTimeOffset is a value type that consists of a DateTime and a time zone offset,
private static DateTime ValidateDate(DateTime dateTime, TimeSpan offset) {
// The key validation is that both the UTC and clock times fit. The clock time is validated
// by the DateTime constructor.
- Contract.Assert(offset.Ticks >= MinOffset && offset.Ticks <= MaxOffset, "Offset not validated.");
+ Debug.Assert(offset.Ticks >= MinOffset && offset.Ticks <= MaxOffset, "Offset not validated.");
// This operation cannot overflow because offset should have already been validated to be within
// 14 hours and the DateTime instance is more than that distance from the boundaries of Int64.
Int64 utcTicks = dateTime.Ticks - offset.Ticks;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using CultureInfo = System.Globalization.CultureInfo;
//Marked serializable even though it has no state.
int hierarchyDepth2 = GetHierarchyDepth(cur2.DeclaringType);
if (hierarchyDepth1 == hierarchyDepth2) {
- Contract.Assert(cur1.IsStatic != cur2.IsStatic, "hierarchyDepth1 == hierarchyDepth2");
+ Debug.Assert(cur1.IsStatic != cur2.IsStatic, "hierarchyDepth1 == hierarchyDepth2");
return 0;
}
else if (hierarchyDepth1 < hierarchyDepth2)
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[Serializable]
internal static Delegate CreateDelegateInternal(RuntimeType rtType, RuntimeMethodInfo rtMethod, Object firstArgument, DelegateBindingFlags flags, ref StackCrawlMark stackMark)
{
- Contract.Assert((flags & DelegateBindingFlags.SkipSecurityChecks) == 0);
+ Debug.Assert((flags & DelegateBindingFlags.SkipSecurityChecks) == 0);
#if FEATURE_APPX
bool nonW8PMethod = (rtMethod.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0;
using System;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
/// </summary>
/// <param name="condition">Expression to assume will always be true.</param>
/// <remarks>
- /// At runtime this is equivalent to an <seealso cref="System.Diagnostics.Contracts.Contract.Assert(bool)"/>.
+ /// At runtime this is equivalent to an <seealso cref="System.Diagnostics.Contracts.Debug.Assert(bool)"/>.
/// </remarks>
[Pure]
[Conditional("DEBUG")]
/// <param name="condition">Expression to assume will always be true.</param>
/// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param>
/// <remarks>
- /// At runtime this is equivalent to an <seealso cref="System.Diagnostics.Contracts.Contract.Assert(bool)"/>.
+ /// At runtime this is equivalent to an <seealso cref="System.Diagnostics.Contracts.Debug.Assert(bool)"/>.
/// </remarks>
[Pure]
[Conditional("DEBUG")]
}
- Contract.Assert((options & EventActivityOptions.Disable) == 0);
+ Debug.Assert((options & EventActivityOptions.Disable) == 0);
var currentActivity = m_current.Value;
var fullActivityName = NormalizeActivityName(providerName, activityName, task);
else
{
orphan.m_stopped = 1;
- Contract.Assert(orphan.m_stopped != 0);
+ Debug.Assert(orphan.m_stopped != 0);
}
orphan = orphan.m_creator;
}
/// </summary>
private static unsafe void WriteNibble(ref byte* ptr, byte* endPtr, uint value)
{
- Contract.Assert(0 <= value && value < 16);
- Contract.Assert(ptr < endPtr);
+ Debug.Assert(0 <= value && value < 16);
+ Debug.Assert(ptr < endPtr);
if (*ptr != 0)
*ptr++ |= (byte)value;
}
if (providerInstance->NextOffset == 0)
break;
- Contract.Assert(0 <= providerInstance->NextOffset && providerInstance->NextOffset < buffSize);
+ Debug.Assert(0 <= providerInstance->NextOffset && providerInstance->NextOffset < buffSize);
var structBase = (byte*)providerInstance;
providerInstance = (UnsafeNativeMethods.ManifestEtw.TRACE_PROVIDER_INSTANCE_INFO*)&structBase[providerInstance->NextOffset];
}
if (childActivityID != null)
{
// activity transfers are supported only for events that specify the Send or Receive opcode
- Contract.Assert((EventOpcode)eventDescriptor.Opcode == EventOpcode.Send ||
+ Debug.Assert((EventOpcode)eventDescriptor.Opcode == EventOpcode.Send ||
(EventOpcode)eventDescriptor.Opcode == EventOpcode.Receive ||
(EventOpcode)eventDescriptor.Opcode == EventOpcode.Start ||
(EventOpcode)eventDescriptor.Opcode == EventOpcode.Stop);
}
private static int bitindex(uint n)
{
- Contract.Assert(bitcount(n) == 1);
+ Debug.Assert(bitcount(n) == 1);
int idx = 0;
while ((n & (1 << idx)) == 0)
idx++;
{
try
{
- Contract.Assert(m_eventData != null); // You must have initialized this if you enabled the source.
+ Debug.Assert(m_eventData != null); // You must have initialized this if you enabled the source.
if (relatedActivityId != null)
ValidateEventOpcodeForTransfer(ref m_eventData[eventId], m_eventData[eventId].Name);
#if FEATURE_ACTIVITYSAMPLING
internal void WriteStringToListener(EventListener listener, string msg, SessionMask m)
{
- Contract.Assert(listener == null || (uint)m == (uint)SessionMask.FromId(0));
+ Debug.Assert(listener == null || (uint)m == (uint)SessionMask.FromId(0));
if (m_eventSourceEnabled)
{
}
#endif // FEATURE_MANAGED_ETW
- Contract.Assert(!m_eventSourceEnabled); // We can't be enabled until we are completely initted.
+ Debug.Assert(!m_eventSourceEnabled); // We can't be enabled until we are completely initted.
// We are logically completely initialized at this point.
m_completelyInited = true;
}
{
try
{
- Contract.Assert(m_eventData != null); // You must have initialized this if you enabled the source.
+ Debug.Assert(m_eventData != null); // You must have initialized this if you enabled the source.
if (childActivityID != null)
{
ValidateEventOpcodeForTransfer(ref m_eventData[eventId], m_eventData[eventId].Name);
Exception lastThrownException = null;
for (EventDispatcher dispatcher = m_Dispatchers; dispatcher != null; dispatcher = dispatcher.m_Next)
{
- Contract.Assert(dispatcher.m_EventEnabled != null);
+ Debug.Assert(dispatcher.m_EventEnabled != null);
if (eventId == -1 || dispatcher.m_EventEnabled[eventId])
{
#if FEATURE_ACTIVITYSAMPLING
{
// PRECONDITION: We should be holding the EventListener.EventListenersLock
// We defer commands until we are completely inited. This allows error messages to be sent.
- Contract.Assert(m_completelyInited);
+ Debug.Assert(m_completelyInited);
#if FEATURE_MANAGED_ETW
if (m_provider == null) // If we failed to construct
try
{
EnsureDescriptorsInitialized();
- Contract.Assert(m_eventData != null);
+ Debug.Assert(m_eventData != null);
// Find the per-EventSource dispatcher corresponding to registered dispatcher
commandArgs.dispatcher = GetDispatcher(commandArgs.listener);
// hasn't changed.
// sesisonId = SessionMask.MAX when one of the legacy ETW sessions changed
// 0 <= perEventSourceSessionId < SessionMask.MAX for activity-tracing aware sessions
- Contract.Assert(commandArgs.perEventSourceSessionId >= -1 && commandArgs.perEventSourceSessionId <= SessionMask.MAX);
+ Debug.Assert(commandArgs.perEventSourceSessionId >= -1 && commandArgs.perEventSourceSessionId <= SessionMask.MAX);
// Send the manifest if we are enabling an ETW session
if (bSessionEnable && commandArgs.dispatcher == null)
// things like log messages, or test if keywords are enabled in the callback.
if (commandArgs.enable)
{
- Contract.Assert(m_eventData != null);
+ Debug.Assert(m_eventData != null);
m_eventSourceEnabled = true;
}
}
// These are not used for non-update commands and thus should always be 'default' values
- // Contract.Assert(enable == true);
- // Contract.Assert(level == EventLevel.LogAlways);
- // Contract.Assert(matchAnyKeyword == EventKeywords.None);
+ // Debug.Assert(enable == true);
+ // Debug.Assert(level == EventLevel.LogAlways);
+ // Debug.Assert(matchAnyKeyword == EventKeywords.None);
this.OnEventCommand(commandArgs);
var eventCommandCallback = m_eventCommandExecuted;
private void EnsureDescriptorsInitialized()
{
#if !ES_BUILD_STANDALONE
- Contract.Assert(Monitor.IsEntered(EventListener.EventListenersLock));
+ Debug.Assert(Monitor.IsEntered(EventListener.EventListenersLock));
#endif
if (m_eventData == null)
{
if (eventSourceGuid.Equals(Guid.Empty) || eventSourceName == null || eventData == null || manifest == null)
{
// GetMetadata failed, so we have to set it via reflection.
- Contract.Assert(m_rawManifest == null);
+ Debug.Assert(m_rawManifest == null);
m_rawManifest = CreateManifestAndDescriptors(this.GetType(), Name, this);
- Contract.Assert(m_eventData != null);
+ Debug.Assert(m_eventData != null);
}
else
if (rawManifest == null)
return false;
- Contract.Assert(!SelfDescribingEvents);
+ Debug.Assert(!SelfDescribingEvents);
#if FEATURE_MANAGED_ETW
fixed (byte* dataPtr = rawManifest)
{
Attribute attr = null;
- Contract.Assert(data.ConstructorArguments.Count <= 1);
+ Debug.Assert(data.ConstructorArguments.Count <= 1);
if (data.ConstructorArguments.Count == 1)
{
int startEventId = eventAttribute.EventId - 1;
if (eventData != null && startEventId < eventData.Length)
{
- Contract.Assert(0 <= startEventId); // Since we reserve id 0, we know that id-1 is <= 0
+ Debug.Assert(0 <= startEventId); // Since we reserve id 0, we know that id-1 is <= 0
EventMetadata startEventMetadata = eventData[startEventId];
// If you remove the Stop and add a Start does that name match the Start Event's Name?
// We give a task to things if they don't have one.
// TODO this is moderately expensive (N*N). We probably should not even bother....
- Contract.Assert(eventAttribute.Task != EventTask.None || eventAttribute.Opcode != EventOpcode.Info);
+ Debug.Assert(eventAttribute.Task != EventTask.None || eventAttribute.Opcode != EventOpcode.Info);
for (int idx = 0; idx < eventData.Length; ++idx)
{
// skip unused Event IDs.
goto default;
break;
default:
- /* Contract.Assert(false, "Warning: User validation code sub-optimial: Unsuported opcode " + instrs[idx] +
+ /* Debug.Assert(false, "Warning: User validation code sub-optimial: Unsuported opcode " + instrs[idx] +
" at " + idx + " in method " + method.Name); */
return -1;
}
{
get
{
- Contract.Assert(((m_config & EventSourceSettings.EtwManifestEventFormat) != 0) !=
+ Debug.Assert(((m_config & EventSourceSettings.EtwManifestEventFormat) != 0) !=
((m_config & EventSourceSettings.EtwSelfDescribingEventFormat) != 0));
return (m_config & EventSourceSettings.EtwSelfDescribingEventFormat) != 0;
}
#if FEATURE_ACTIVITYSAMPLING
private void ReportActivitySamplingInfo(EventListener listener, SessionMask sessions)
{
- Contract.Assert(listener == null || (uint)sessions == (uint)SessionMask.FromId(0));
+ Debug.Assert(listener == null || (uint)sessions == (uint)SessionMask.FromId(0));
for (int perEventSourceSessionId = 0; perEventSourceSessionId < SessionMask.MAX; ++perEventSourceSessionId)
{
if (listener == null)
{
EtwSession etwSession = m_etwSessionIdMap[perEventSourceSessionId];
- Contract.Assert(etwSession != null);
+ Debug.Assert(etwSession != null);
af = etwSession.m_activityFilter;
}
else
private static void RemoveReferencesToListenerInEventSources(EventListener listenerToRemove)
{
#if !ES_BUILD_STANDALONE
- Contract.Assert(Monitor.IsEntered(EventListener.EventListenersLock));
+ Debug.Assert(Monitor.IsEntered(EventListener.EventListenersLock));
#endif
// Foreach existing EventSource in the appdomain
foreach (WeakReference eventSourceRef in s_EventSources)
EventDispatcher cur = prev.m_Next;
if (cur == null)
{
- Contract.Assert(false, "EventSource did not have a registered EventListener!");
+ Debug.Assert(false, "EventSource did not have a registered EventListener!");
break;
}
if (cur.m_Listener == listenerToRemove)
EventSource eventSource = eventSourceRef.Target as EventSource;
if (eventSource == null)
continue;
- Contract.Assert(eventSource.m_id == id, "Unexpected event source ID.");
+ Debug.Assert(eventSource.m_id == id, "Unexpected event source ID.");
// None listeners on eventSources exist in the dispatcher list.
EventDispatcher dispatcher = eventSource.m_Dispatchers;
while (dispatcher != null)
{
- Contract.Assert(allListeners.ContainsKey(dispatcher.m_Listener), "EventSource has a listener not on the global list.");
+ Debug.Assert(allListeners.ContainsKey(dispatcher.m_Listener), "EventSource has a listener not on the global list.");
dispatcher = dispatcher.m_Next;
}
dispatcher = eventSource.m_Dispatchers;
for (;;)
{
- Contract.Assert(dispatcher != null, "Listener is not on all eventSources.");
+ Debug.Assert(dispatcher != null, "Listener is not on all eventSources.");
if (dispatcher.m_Listener == listener)
break;
dispatcher = dispatcher.m_Next;
if (m_payloadNames == null)
{
// Self described events are identified by id -1.
- Contract.Assert(EventId != -1);
+ Debug.Assert(EventId != -1);
var names = new List<string>();
foreach (var parameter in m_eventSource.m_eventData[EventId].Parameters)
public static void DisableFilter(ref ActivityFilter filterList, EventSource source)
{
#if !ES_BUILD_STANDALONE
- Contract.Assert(Monitor.IsEntered(EventListener.EventListenersLock));
+ Debug.Assert(Monitor.IsEntered(EventListener.EventListenersLock));
#endif
if (filterList == null)
string startEvents)
{
#if !ES_BUILD_STANDALONE
- Contract.Assert(Monitor.IsEntered(EventListener.EventListenersLock));
+ Debug.Assert(Monitor.IsEntered(EventListener.EventListenersLock));
#endif
// first remove all filters associated with 'source'
EventSource source,
int eventId)
{
- Contract.Assert(filterList != null && filterList.m_activeActivities != null);
+ Debug.Assert(filterList != null && filterList.m_activeActivities != null);
bool shouldBeLogged = false;
if (triggeringEvent)
{
/// </summary>
unsafe public static void FlowActivityIfNeeded(ActivityFilter filterList, Guid* currentActivityId, Guid* childActivityID)
{
- Contract.Assert(childActivityID != null);
+ Debug.Assert(childActivityID != null);
var activeActivities = GetActiveActivities(filterList);
- Contract.Assert(activeActivities != null);
+ Debug.Assert(activeActivities != null);
// take currentActivityId == null to mean we *know* the current activity is "active"
if (currentActivityId != null && !activeActivities.ContainsKey(*currentActivityId))
public void Dispose()
{
#if !ES_BUILD_STANDALONE
- Contract.Assert(Monitor.IsEntered(EventListener.EventListenersLock));
+ Debug.Assert(Monitor.IsEntered(EventListener.EventListenersLock));
#endif
// m_myActivityDelegate is still alive (held by the static EventSource.s_activityDying).
// Therefore we are ok to take a dependency on m_myActivityDelegate being valid even
m_samplingFreq = samplingFreq;
m_next = existingFilter;
- Contract.Assert(existingFilter == null ||
+ Debug.Assert(existingFilter == null ||
(existingFilter.m_activeActivities == null) == (existingFilter.m_rootActiveActivities == null));
// if this is the first filter we add for this session, we need to create a new
private static bool EnableFilter(ref ActivityFilter filterList, EventSource source, int perEventSourceSessionId, int eventId, int samplingFreq)
{
#if !ES_BUILD_STANDALONE
- Contract.Assert(Monitor.IsEntered(EventListener.EventListenersLock));
+ Debug.Assert(Monitor.IsEntered(EventListener.EventListenersLock));
#endif
- Contract.Assert(samplingFreq > 0);
- Contract.Assert(eventId >= 0);
+ Debug.Assert(samplingFreq > 0);
+ Debug.Assert(eventId >= 0);
filterList = new ActivityFilter(source, perEventSourceSessionId, eventId, samplingFreq, filterList);
public static void RemoveEtwSession(EtwSession etwSession)
{
- Contract.Assert(etwSession != null);
+ Debug.Assert(etwSession != null);
if (s_etwSessions == null || etwSession == null)
return;
public static SessionMask FromId(int perEventSourceSessionId)
{
- Contract.Assert(perEventSourceSessionId < MAX);
+ Debug.Assert(perEventSourceSessionId < MAX);
return new SessionMask((uint)1 << perEventSourceSessionId);
}
{
get
{
- Contract.Assert(perEventSourceSessionId < MAX);
+ Debug.Assert(perEventSourceSessionId < MAX);
return (m_mask & (1 << perEventSourceSessionId)) != 0;
}
set
{
- Contract.Assert(perEventSourceSessionId < MAX);
+ Debug.Assert(perEventSourceSessionId < MAX);
if (value) m_mask |= ((uint)1 << perEventSourceSessionId);
else m_mask &= ~((uint)1 << perEventSourceSessionId);
}
private EventChannelType EventChannelToChannelType(EventChannel channel)
{
#if !ES_BUILD_STANDALONE
- Contract.Assert(channel >= EventChannel.Admin && channel <= EventChannel.Debug);
+ Debug.Assert(channel >= EventChannel.Admin && channel <= EventChannel.Debug);
#endif
return (EventChannelType)((int)channel - (int)EventChannel.Admin + (int)EventChannelType.Admin);
}
#endif
public void StartEvent(string eventName, EventAttribute eventAttribute)
{
- Contract.Assert(numParams == 0);
- Contract.Assert(this.eventName == null);
+ Debug.Assert(numParams == 0);
+ Debug.Assert(this.eventName == null);
this.eventName = eventName;
numParams = 0;
byteArrArgIndices = null;
using System.Collections.Generic;
using System.Collections;
+using System.Diagnostics;
#if !ES_BUILD_AGAINST_DOTNET_V35
using Contract = System.Diagnostics.Contracts.Contract;
{
internal EventPayload(List<string> payloadNames, List<object> payloadValues)
{
- Contract.Assert(payloadNames.Count == payloadValues.Count);
+ Debug.Assert(payloadNames.Count == payloadValues.Count);
m_names = payloadNames;
m_values = payloadValues;
using System.Reflection;
using System.Runtime.InteropServices;
+using System.Diagnostics;
#if !ES_BUILD_AGAINST_DOTNET_V35
using Contract = System.Diagnostics.Contracts.Contract;
{
get
{
- Contract.Assert(_scalarLength == 0, "This ReflectedValue refers to an unboxed value type, not a reference type or boxed value type.");
+ Debug.Assert(_scalarLength == 0, "This ReflectedValue refers to an unboxed value type, not a reference type or boxed value type.");
return _reference;
}
}
{
get
{
- Contract.Assert(_scalarLength > 0, "This ReflectedValue refers to a reference type or boxed value type, not an unboxed value type");
+ Debug.Assert(_scalarLength > 0, "This ReflectedValue refers to a reference type or boxed value type, not an unboxed value type");
return _scalar;
}
}
{
get
{
- Contract.Assert(_scalarLength > 0, "This ReflectedValue refers to a reference type or boxed value type, not an unboxed value type");
+ Debug.Assert(_scalarLength > 0, "This ReflectedValue refers to a reference type or boxed value type, not an unboxed value type");
return _scalarLength;
}
}
using System;
using System.Collections.Generic;
using System.Reflection;
+using System.Diagnostics;
#if !ES_BUILD_AGAINST_DOTNET_V35
using Contract = System.Diagnostics.Contracts.Contract;
: base(type)
{
var typeArgs = type.GenericTypeArguments;
- Contract.Assert(typeArgs.Length == 1);
+ Debug.Assert(typeArgs.Length == 1);
this.valueInfo = TraceLoggingTypeInfo.GetInstance(typeArgs[0], recursionCheck);
this.hasValueGetter = PropertyValue.GetPropertyGetter(type.GetTypeInfo().GetDeclaredProperty("HasValue"));
this.valueGetter = PropertyValue.GetPropertyGetter(type.GetTypeInfo().GetDeclaredProperty("Value"));
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System
case CorElementType.U8:
return (*(ulong*)pValue).ToString("X16", null);
default:
- Contract.Assert(false, "Invalid Object type in Format");
+ Debug.Assert(false, "Invalid Object type in Format");
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType"));
}
}
return ((UInt64)(Int64)value).ToString("X16", null);
// All unsigned types will be directly cast
default:
- Contract.Assert(false, "Invalid Object type in Format");
+ Debug.Assert(false, "Invalid Object type in Format");
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType"));
}
}
String[] names = entry.Names;
ulong[] values = entry.Values;
- Contract.Assert(names.Length == values.Length);
+ Debug.Assert(names.Length == values.Length);
int index = values.Length - 1;
StringBuilder retval = new StringBuilder();
break;
// All unsigned types will be directly cast
default:
- Contract.Assert(false, "Invalid Object type in ToUInt64");
+ Debug.Assert(false, "Invalid Object type in ToUInt64");
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType"));
}
return m_innerException;
default:
- Contract.Assert(false, "Unknown EnumParseFailure: " + m_failure);
+ Debug.Assert(false, "Unknown EnumParseFailure: " + m_failure);
return new ArgumentException(Environment.GetResourceString("Arg_EnumValueNotFound"));
}
}
case CorElementType.U:
return *(UIntPtr*)pValue;
default:
- Contract.Assert(false, "Invalid primitive type");
+ Debug.Assert(false, "Invalid primitive type");
return null;
}
}
return *(uint*)pValue;
}
default:
- Contract.Assert(false, "Invalid primitive type");
+ Debug.Assert(false, "Invalid primitive type");
return 0;
}
}
case CorElementType.U:
return (*(UIntPtr*)pValue).GetHashCode();
default:
- Contract.Assert(false, "Invalid primitive type");
+ Debug.Assert(false, "Invalid primitive type");
return 0;
}
}
else
{
// assert valid return code (3)
- Contract.Assert(ret == retInvalidEnumType, "Enum.InternalCompareTo return code was invalid");
+ Debug.Assert(ret == retInvalidEnumType, "Enum.InternalCompareTo return code was invalid");
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType"));
}
return TypeCode.Char;
}
- Contract.Assert(false, "Unknown underlying type.");
+ Debug.Assert(false, "Unknown underlying type.");
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType"));
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal String GetResourceString(String key) {
if (key == null || key.Length == 0) {
- Contract.Assert(false, "Environment::GetResourceString with null or empty key. Bug in caller, or weird recursive loading problem?");
+ Debug.Assert(false, "Environment::GetResourceString with null or empty key. Bug in caller, or weird recursive loading problem?");
return "[Resource lookup failed - null or empty resource name]";
}
String s = rh.SystemResMgr.GetString(key, null);
rh.currentlyLoading.RemoveAt(rh.currentlyLoading.Count - 1); // Pop
- Contract.Assert(s!=null, "Managed resource string lookup failed. Was your resource name misspelled? Did you rebuild mscorlib after adding a resource to resources.txt? Debug this w/ cordbg and bug whoever owns the code that called Environment.GetResourceString. Resource name was: \""+key+"\"");
+ Debug.Assert(s!=null, "Managed resource string lookup failed. Was your resource name misspelled? Did you rebuild mscorlib after adding a resource to resources.txt? Debug this w/ cordbg and bug whoever owns the code that called Environment.GetResourceString. Resource name was: \""+key+"\"");
userData.m_retVal = s;
}
get {
StringBuilder sb = new StringBuilder(Path.MaxPath);
int r = Win32Native.GetSystemDirectory(sb, Path.MaxPath);
- Contract.Assert(r < Path.MaxPath, "r < Path.MaxPath");
+ Debug.Assert(r < Path.MaxPath, "r < Path.MaxPath");
if (r==0) __Error.WinIOError();
String path = sb.ToString();
get {
StringBuilder sb = new StringBuilder(Path.MaxPath);
int r = Win32Native.GetWindowsDirectory(sb, Path.MaxPath);
- Contract.Assert(r < Path.MaxPath, "r < Path.MaxPath");
+ Debug.Assert(r < Path.MaxPath, "r < Path.MaxPath");
if (r==0) __Error.WinIOError();
String path = sb.ToString();
Version v = new Version(osvi.MajorVersion, osvi.MinorVersion, osvi.BuildNumber, (osviEx.ServicePackMajor << 16) |osviEx.ServicePackMinor);
m_os = new OperatingSystem(id, v, osvi.CSDVersion);
}
- Contract.Assert(m_os != null, "m_os != null");
+ Debug.Assert(m_os != null, "m_os != null");
return m_os;
}
}
result.Append(separator);
result.Append(rci.ToString());
} else {
- Contract.Assert(methBase is MethodInfo, "[Exception.GetExceptionMethodString]methBase is MethodInfo");
+ Debug.Assert(methBase is MethodInfo, "[Exception.GetExceptionMethodString]methBase is MethodInfo");
RuntimeMethodInfo rmi = (RuntimeMethodInfo)methBase;
Type t = rmi.DeclaringType;
result.Append((int)MemberTypes.Method);
}
private MethodBase GetExceptionMethodFromString() {
- Contract.Assert(_exceptionMethodString != null, "Method string cannot be NULL!");
+ Debug.Assert(_exceptionMethodString != null, "Method string cannot be NULL!");
String[] args = _exceptionMethodString.Split(new char[]{'\0', '\n'});
if (args.Length!=5) {
throw new SerializationException();
// often created in the VM with AllocateObject instead if the managed construtor)
// If you are adding code to use a SafeSerializationManager from an mscorlib exception, update
// this assert to ensure that it fails when that exception's _safeSerializationManager is NULL
- Contract.Assert(((_safeSerializationManager != null) || (this.GetType().Assembly == typeof(object).Assembly)),
+ Debug.Assert(((_safeSerializationManager != null) || (this.GetType().Assembly == typeof(object).Assembly)),
"User defined exceptions must have a valid _safeSerializationManager");
// Handle serializing any transparent or partial trust subclass data
using System.Runtime.CompilerServices;
using System.Globalization;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
// This abstract class represents a calendar. A calendar reckons time in
get {
// The following code assumes that the current era value can not be -1.
if (m_currentEraValue == -1) {
- Contract.Assert(BaseCalendarID > 0, "[Calendar.CurrentEraValue] Expected ID > 0");
+ Debug.Assert(BaseCalendarID > 0, "[Calendar.CurrentEraValue] Expected ID > 0");
m_currentEraValue = CalendarData.GetCalendarData(BaseCalendarID).iCurrentEra;
}
return (m_currentEraValue);
// this value can be less than 0. It's fine since we are making it positive again in calculating offset.
int dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7);
int offset = (dayForJan1 - firstDayOfWeek + 14) % 7;
- Contract.Assert(offset >= 0, "Calendar.GetFirstDayWeekOfYear(): offset >= 0");
+ Debug.Assert(offset >= 0, "Calendar.GetFirstDayWeekOfYear(): offset >= 0");
return ((dayOfYear + offset) / 7 + 1);
}
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
//
// List of calendar data
this.bUseUserOverrides = bUseUserOverrides;
if (!nativeGetCalendarData(this, localeName, calendarId))
{
- Contract.Assert(false, "[CalendarData] nativeGetCalendarData call isn't expected to fail for calendar " + calendarId + " locale " +localeName);
+ Debug.Assert(false, "[CalendarData] nativeGetCalendarData call isn't expected to fail for calendar " + calendarId + " locale " +localeName);
// Something failed, try invariant for missing parts
// This is really not good, but we don't want the callers to crash.
namespace System.Globalization
{
using System;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
internal class CalendricalCalculationsHelper
// the following formulas defines a polynomial function which gives us the amount that the earth is slowing down for specific year ranges
static double DefaultEphemerisCorrection(int gregorianYear)
{
- Contract.Assert(gregorianYear < 1620 || 2020 <= gregorianYear);
+ Debug.Assert(gregorianYear < 1620 || 2020 <= gregorianYear);
long january1stOfYear = GetNumberOfDays(new DateTime(gregorianYear, 1, 1));
double daysSinceStartOf1810 = january1stOfYear - StartOf1810;
double x = TwelveHours + daysSinceStartOf1810;
static double EphemerisCorrection1988to2019(int gregorianYear)
{
- Contract.Assert(1988 <= gregorianYear && gregorianYear <= 2019);
+ Debug.Assert(1988 <= gregorianYear && gregorianYear <= 2019);
return (double)(gregorianYear - 1933) / SecondsPerDay;
}
static double EphemerisCorrection1900to1987(int gregorianYear)
{
- Contract.Assert(1900 <= gregorianYear && gregorianYear <= 1987);
+ Debug.Assert(1900 <= gregorianYear && gregorianYear <= 1987);
double centuriesFrom1900 = CenturiesFrom1900(gregorianYear);
return PolynomialSum(Coefficients1900to1987, centuriesFrom1900);
}
static double EphemerisCorrection1800to1899(int gregorianYear)
{
- Contract.Assert(1800 <= gregorianYear && gregorianYear <= 1899);
+ Debug.Assert(1800 <= gregorianYear && gregorianYear <= 1899);
double centuriesFrom1900 = CenturiesFrom1900(gregorianYear);
return PolynomialSum(Coefficients1800to1899, centuriesFrom1900);
}
static double EphemerisCorrection1700to1799(int gregorianYear)
{
- Contract.Assert(1700 <= gregorianYear && gregorianYear <= 1799);
+ Debug.Assert(1700 <= gregorianYear && gregorianYear <= 1799);
double yearsSince1700 = gregorianYear - 1700;
return PolynomialSum(Coefficients1700to1799, yearsSince1700) / SecondsPerDay;
}
static double EphemerisCorrection1620to1699(int gregorianYear)
{
- Contract.Assert(1620 <= gregorianYear && gregorianYear <= 1699);
+ Debug.Assert(1620 <= gregorianYear && gregorianYear <= 1699);
double yearsSince1600 = gregorianYear - 1600;
return PolynomialSum(Coefficients1620to1699, yearsSince1600) / SecondsPerDay;
}
}
}
- Contract.Assert(false, "Not expected to come here");
+ Debug.Assert(false, "Not expected to come here");
return DefaultEphemerisCorrection(year);
}
break;
}
}
- Contract.Assert(day != upperBoundNewYearDay);
+ Debug.Assert(day != upperBoundNewYearDay);
return day - 1;
}
using System.Runtime.Versioning;
using System.Reflection;
using System.Security;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
////////////////////////////////////////////////////////////////////////
internal static int InternalConvertToUtf32(String s, int index) {
- Contract.Assert(s != null, "s != null");
- Contract.Assert(index >= 0 && index < s.Length, "index < s.Length");
+ Debug.Assert(s != null, "s != null");
+ Debug.Assert(index >= 0 && index < s.Length, "index < s.Length");
if (index < s.Length - 1) {
int temp1 = (int)s[index] - HIGH_SURROGATE_START;
if (temp1 >= 0 && temp1 <= 0x3ff) {
////////////////////////////////////////////////////////////////////////
internal static int InternalConvertToUtf32(String s, int index, out int charLength) {
- Contract.Assert(s != null, "s != null");
- Contract.Assert(s.Length > 0, "s.Length > 0");
- Contract.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length");
+ Debug.Assert(s != null, "s != null");
+ Debug.Assert(s.Length > 0, "s.Length > 0");
+ Debug.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length");
charLength = 1;
if (index < s.Length - 1) {
int temp1 = (int)s[index] - HIGH_SURROGATE_START;
internal static bool IsWhiteSpace(String s, int index)
{
- Contract.Assert(s != null, "s!=null");
- Contract.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length");
+ Debug.Assert(s != null, "s!=null");
+ Debug.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length");
UnicodeCategory uc = GetUnicodeCategory(s, index);
// In Unicode 3.0, U+2028 is the only character which is under the category "LineSeparator".
// Note that for ch in the range D800-DFFF we just treat it as any other non-numeric character
//
internal unsafe static double InternalGetNumericValue(int ch) {
- Contract.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
+ Debug.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
// Get the level 2 item from the highest 12 bit (8 - 19) of ch.
ushort index = s_pNumericLevel1Index[ch >> 8];
// Get the level 2 WORD offset from the 4 - 7 bit of ch. This provides the base offset of the level 3 table.
// Note that for ch in the range D800-DFFF we just treat it as any other non-numeric character
//
internal unsafe static DigitValues* InternalGetDigitValues(int ch) {
- Contract.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
+ Debug.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
// Get the level 2 item from the highest 12 bit (8 - 19) of ch.
ushort index = s_pNumericLevel1Index[ch >> 8];
// Get the level 2 WORD offset from the 4 - 7 bit of ch. This provides the base offset of the level 3 table.
////////////////////////////////////////////////////////////////////////
internal unsafe static byte InternalGetCategoryValue(int ch, int offset) {
- Contract.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
+ Debug.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
// Get the level 2 item from the highest 12 bit (8 - 19) of ch.
ushort index = s_pCategoryLevel1Index[ch >> 8];
// Get the level 2 WORD offset from the 4 - 7 bit of ch. This provides the base offset of the level 3 table.
// Make sure that OtherNotAssigned is the last category in UnicodeCategory.
// If that changes, change the following assertion as well.
//
- //Contract.Assert(uc >= 0 && uc <= UnicodeCategory.OtherNotAssigned, "Table returns incorrect Unicode category");
+ //Debug.Assert(uc >= 0 && uc <= UnicodeCategory.OtherNotAssigned, "Table returns incorrect Unicode category");
return (uc);
}
////////////////////////////////////////////////////////////////////////
internal static UnicodeCategory InternalGetUnicodeCategory(String value, int index) {
- Contract.Assert(value != null, "value can not be null");
- Contract.Assert(index < value.Length, "index < value.Length");
+ Debug.Assert(value != null, "value can not be null");
+ Debug.Assert(index < value.Length, "index < value.Length");
return (InternalGetUnicodeCategory(InternalConvertToUtf32(value, index)));
}
////////////////////////////////////////////////////////////////////////
internal static UnicodeCategory InternalGetUnicodeCategory(String str, int index, out int charLength) {
- Contract.Assert(str != null, "str can not be null");
- Contract.Assert(str.Length > 0, "str.Length > 0");;
- Contract.Assert(index >= 0 && index < str.Length, "index >= 0 && index < str.Length");
+ Debug.Assert(str != null, "str can not be null");
+ Debug.Assert(str.Length > 0, "str.Length > 0");;
+ Debug.Assert(index >= 0 && index < str.Length, "index >= 0 && index < str.Length");
return (InternalGetUnicodeCategory(InternalConvertToUtf32(str, index, out charLength)));
}
internal static bool IsCombiningCategory(UnicodeCategory uc) {
- Contract.Assert(uc >= 0, "uc >= 0");
+ Debug.Assert(uc >= 0, "uc >= 0");
return (
uc == UnicodeCategory.NonSpacingMark ||
uc == UnicodeCategory.SpacingCombiningMark ||
using System.Security.Permissions;
using Microsoft.Win32;
using System.Security;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
//
#if FEATURE_USE_LCID
// This is merely for serialization compatibility with Whidbey/Orcas, it can go away when we don't want that compat any more.
culture = CultureInfo.GetCultureInfo(this.Name).LCID; // This is the lcid of the constructing culture (still have to dereference to get target sort)
- Contract.Assert(m_name != null, "CompareInfo.OnSerializing - expected m_name to be set already");
+ Debug.Assert(m_name != null, "CompareInfo.OnSerializing - expected m_name to be set already");
#endif
}
{
get
{
- Contract.Assert(m_name != null, "CompareInfo.Name Expected m_name to be set");
+ Debug.Assert(m_name != null, "CompareInfo.Name Expected m_name to be set");
return (m_sortName);
}
}
// some NLS VM functions can handle COMPARE_OPTIONS_ORDINAL
// in which case options should be simply cast to int instead of using this function
// Does not look like the best approach to me but for now I am going to leave it as it is
- Contract.Assert(options != CompareOptions.OrdinalIgnoreCase, "[CompareInfo.GetNativeCompareFlags]CompareOptions.OrdinalIgnoreCase should be handled separately");
+ Debug.Assert(options != CompareOptions.OrdinalIgnoreCase, "[CompareInfo.GetNativeCompareFlags]CompareOptions.OrdinalIgnoreCase should be handled separately");
// Use "linguistic casing" by default (load the culture's casing exception tables)
int nativeCompareFlags = NORM_LINGUISTIC_CASING;
// Suffix & Prefix shouldn't use this, make sure to turn off the NORM_LINGUISTIC_CASING flag
if (options == CompareOptions.Ordinal) { nativeCompareFlags = COMPARE_OPTIONS_ORDINAL; }
- Contract.Assert(((options & ~(CompareOptions.IgnoreCase |
+ Debug.Assert(((options & ~(CompareOptions.IgnoreCase |
CompareOptions.IgnoreKanaType |
CompareOptions.IgnoreNonSpace |
CompareOptions.IgnoreSymbols |
CompareOptions.StringSort)) == 0) ||
(options == CompareOptions.Ordinal), "[CompareInfo.GetNativeCompareFlags]Expected all flags to be handled");
- Contract.Assert((nativeCompareFlags & RESERVED_FIND_ASCII_STRING) == 0, "[CompareInfo.GetNativeCompareFlags] RESERVED_FIND_ASCII_STRING shouldn't be set here");
+ Debug.Assert((nativeCompareFlags & RESERVED_FIND_ASCII_STRING) == 0, "[CompareInfo.GetNativeCompareFlags] RESERVED_FIND_ASCII_STRING shouldn't be set here");
return nativeCompareFlags;
}
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Security;
private static bool IsReplacementCultureName(String name)
{
- Contract.Assert(name != null, "IsReplacementCultureName(): name should not be null");
+ Debug.Assert(name != null, "IsReplacementCultureName(): name should not be null");
String[] replacementCultureNames = s_replacementCultureNames;
if (replacementCultureNames == null)
{
}
// Even if we don't have any replacement cultures, the returned replacementCultureNames will still an empty string array, not null.
- Contract.Assert(name != null, "IsReplacementCultureName(): replacementCultureNames should not be null");
+ Debug.Assert(name != null, "IsReplacementCultureName(): replacementCultureNames should not be null");
Array.Sort(replacementCultureNames);
s_replacementCultureNames = replacementCultureNames;
}
{
get
{
- Contract.Assert(this.sRealName != null, "[CultureData.CultureName] Expected this.sRealName to be populated by COMNlsInfo::nativeInitCultureData already");
+ Debug.Assert(this.sRealName != null, "[CultureData.CultureName] Expected this.sRealName to be populated by COMNlsInfo::nativeInitCultureData already");
// since windows doesn't know about zh-CHS and zh-CHT,
// we leave sRealName == zh-Hanx but we still need to
// pretend that it was zh-CHX.
{
get
{
- // Contract.Assert(this.sName != null,
+ // Debug.Assert(this.sName != null,
// "[CultureData.SNAME] Expected this.sName to be populated by COMNlsInfo::nativeInitCultureData already");
if (this.sName == null)
{
get
{
// This got populated when ComNlsInfo::nativeInitCultureData told us we had a culture
- Contract.Assert(this.sSpecificCulture != null, "[CultureData.SSPECIFICCULTURE] Expected this.sSpecificCulture to be populated by COMNlsInfo::nativeInitCultureData already");
+ Debug.Assert(this.sSpecificCulture != null, "[CultureData.SSPECIFICCULTURE] Expected this.sSpecificCulture to be populated by COMNlsInfo::nativeInitCultureData already");
return this.sSpecificCulture;
}
}
// We then have to copy that list to a new array of the right size.
// Default calendar should be first
int[] calendarInts = new int[23];
- Contract.Assert(this.sWindowsName != null, "[CultureData.CalendarIds] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
+ Debug.Assert(this.sWindowsName != null, "[CultureData.CalendarIds] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
int count = CalendarData.nativeGetCalendars(this.sWindowsName, this.bUseOverrides, calendarInts);
// See if we had a calendar to add.
internal CalendarData GetCalendar(int calendarId)
{
- Contract.Assert(calendarId > 0 && calendarId <= CalendarData.MAX_CALENDARS,
+ Debug.Assert(calendarId > 0 && calendarId <= CalendarData.MAX_CALENDARS,
"[CultureData.GetCalendar] Expect calendarId to be in a valid range");
// arrays are 0 based, calendarIds are 1 based
// Make sure that calendar has data
if (calendarData == null || UseUserOverride)
{
- Contract.Assert(this.sWindowsName != null, "[CultureData.GetCalendar] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
+ Debug.Assert(this.sWindowsName != null, "[CultureData.GetCalendar] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
calendarData = new CalendarData(this.sWindowsName, calendarId, this.UseUserOverride);
calendars[calendarIndex] = calendarData;
}
{
if (this.iReadingLayout == undef)
{
- Contract.Assert(this.sRealName != null, "[CultureData.IsRightToLeft] Expected this.sRealName to be populated by COMNlsInfo::nativeInitCultureData already");
+ Debug.Assert(this.sRealName != null, "[CultureData.IsRightToLeft] Expected this.sRealName to be populated by COMNlsInfo::nativeInitCultureData already");
this.iReadingLayout = DoGetLocaleInfoInt(LOCALE_IREADINGLAYOUT);
}
{
if (this.iLanguage == 0)
{
- Contract.Assert(this.sRealName != null, "[CultureData.ILANGUAGE] Expected this.sRealName to be populated by COMNlsInfo::nativeInitCultureData already");
+ Debug.Assert(this.sRealName != null, "[CultureData.ILANGUAGE] Expected this.sRealName to be populated by COMNlsInfo::nativeInitCultureData already");
this.iLanguage = LocaleNameToLCID(this.sRealName);
}
return this.iLanguage;
// All of our era names
internal String[] EraNames(int calendarId)
{
- Contract.Assert(calendarId > 0, "[CultureData.saEraNames] Expected Calendar.ID > 0");
+ Debug.Assert(calendarId > 0, "[CultureData.saEraNames] Expected Calendar.ID > 0");
return this.GetCalendar(calendarId).saEraNames;
}
internal String[] AbbrevEraNames(int calendarId)
{
- Contract.Assert(calendarId > 0, "[CultureData.saAbbrevEraNames] Expected Calendar.ID > 0");
+ Debug.Assert(calendarId > 0, "[CultureData.saAbbrevEraNames] Expected Calendar.ID > 0");
return this.GetCalendar(calendarId).saAbbrevEraNames;
}
internal String[] AbbreviatedEnglishEraNames(int calendarId)
{
- Contract.Assert(calendarId > 0, "[CultureData.saAbbrevEraNames] Expected Calendar.ID > 0");
+ Debug.Assert(calendarId > 0, "[CultureData.saAbbrevEraNames] Expected Calendar.ID > 0");
return this.GetCalendar(calendarId).saAbbrevEnglishEraNames;
}
private static int IndexOfTimePart(string format, int startIndex, string timeParts)
{
- Contract.Assert(startIndex >= 0, "startIndex cannot be negative");
- Contract.Assert(timeParts.IndexOfAny(new char[] { '\'', '\\' }) == -1, "timeParts cannot include quote characters");
+ Debug.Assert(startIndex >= 0, "startIndex cannot be negative");
+ Debug.Assert(timeParts.IndexOfAny(new char[] { '\'', '\\' }) == -1, "timeParts cannot include quote characters");
bool inQuote = false;
for (int i = startIndex; i < format.Length; ++i)
{
string DoGetLocaleInfo(uint lctype)
{
- Contract.Assert(this.sWindowsName != null, "[CultureData.DoGetLocaleInfo] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
+ Debug.Assert(this.sWindowsName != null, "[CultureData.DoGetLocaleInfo] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
return DoGetLocaleInfo(this.sWindowsName, lctype);
}
}
// Ask OS for data
- Contract.Assert(localeName != null, "[CultureData.DoGetLocaleInfo] Expected localeName to be not be null");
+ Debug.Assert(localeName != null, "[CultureData.DoGetLocaleInfo] Expected localeName to be not be null");
string result = CultureInfo.nativeGetLocaleInfoEx(localeName, lctype);
if (result == null)
{
// Ask OS for data, note that we presume it returns success, so we have to know that
// sWindowsName is valid before calling.
- Contract.Assert(this.sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
+ Debug.Assert(this.sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
int result = CultureInfo.nativeGetLocaleInfoExInt(this.sWindowsName, lctype);
return result;
String[] DoEnumTimeFormats()
{
// Note that this gets overrides for us all the time
- Contract.Assert(this.sWindowsName != null, "[CultureData.DoEnumTimeFormats] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
+ Debug.Assert(this.sWindowsName != null, "[CultureData.DoEnumTimeFormats] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
String[] result = ReescapeWin32Strings(nativeEnumTimeFormats(this.sWindowsName, 0, UseUserOverride));
return result;
String[] DoEnumShortTimeFormats()
{
// Note that this gets overrides for us all the time
- Contract.Assert(this.sWindowsName != null, "[CultureData.DoEnumShortTimeFormats] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
+ Debug.Assert(this.sWindowsName != null, "[CultureData.DoEnumShortTimeFormats] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
String[] result = ReescapeWin32Strings(nativeEnumTimeFormats(this.sWindowsName, TIME_NOSECONDS, UseUserOverride));
return result;
//
// Ask native side for our data.
//
- Contract.Assert(this.sWindowsName != null, "[CultureData.GetNFIValues] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
+ Debug.Assert(this.sWindowsName != null, "[CultureData.GetNFIValues] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
CultureData.nativeGetNumberFormatInfoValues(this.sWindowsName, nfi, UseUserOverride);
}
using System.Security.Permissions;
using System.Reflection;
using Microsoft.Win32;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Resources;
// e.g. for es-ES_tradnl: v2 puts es-ES in m_name; v4 puts es-ES_tradnl
if (m_name == null || IsAlternateSortLcid(cultureID))
{
- Contract.Assert(cultureID >=0, "[CultureInfo.OnDeserialized] cultureID >= 0");
+ Debug.Assert(cultureID >=0, "[CultureInfo.OnDeserialized] cultureID >= 0");
InitializeFromCultureId(cultureID, m_useUserOverride);
}
else
{
#endif
- Contract.Assert(m_name != null, "[CultureInfo.OnDeserialized] m_name != null");
+ Debug.Assert(m_name != null, "[CultureInfo.OnDeserialized] m_name != null");
this.m_cultureData = CultureData.GetCultureData(m_name, m_useUserOverride);
if (this.m_cultureData == null)
// For Silverlight, the answer is always no.
internal bool IsSafeCrossDomain {
get {
- Contract.Assert(m_createdDomainID != 0, "[CultureInfo.IsSafeCrossDomain] m_createdDomainID != 0");
+ Debug.Assert(m_createdDomainID != 0, "[CultureInfo.IsSafeCrossDomain] m_createdDomainID != 0");
return m_isSafeCrossDomain;
}
}
internal int CreatedDomainID {
get {
- Contract.Assert(m_createdDomainID != 0, "[CultureInfo.CreatedDomain] m_createdDomainID != 0");
+ Debug.Assert(m_createdDomainID != 0, "[CultureInfo.CreatedDomain] m_createdDomainID != 0");
return m_createdDomainID;
}
}
}
internal static bool VerifyCultureName(CultureInfo culture, bool throwException) {
- Contract.Assert(culture!=null, "[CultureInfo.VerifyCultureName]culture!=null");
+ Debug.Assert(culture!=null, "[CultureInfo.VerifyCultureName]culture!=null");
//If we have an instance of one of our CultureInfos, the user can't have changed the
//name and we know that all names are valid in files.
get
{
Contract.Ensures(Contract.Result<String>() != null);
- Contract.Assert(m_name != null, "[CultureInfo.DisplayName]Always expect m_name to be set");
+ Debug.Assert(m_name != null, "[CultureInfo.DisplayName]Always expect m_name to be set");
return m_cultureData.SLOCALIZEDDISPLAYNAME;
}
{
Contract.Ensures(Contract.Result<String>() != null);
- Contract.Assert(m_name != null, "[CultureInfo.ToString]Always expect m_name to be set");
+ Debug.Assert(m_name != null, "[CultureInfo.ToString]Always expect m_name to be set");
return m_name;
}
//This function exists as a shortcut to prevent us from loading all of the non-gregorian
//calendars unless they're required.
internal static Calendar GetCalendarInstanceRare(int calType) {
- Contract.Assert(calType!=Calendar.CAL_GREGORIAN, "calType!=Calendar.CAL_GREGORIAN");
+ Debug.Assert(calType!=Calendar.CAL_GREGORIAN, "calType!=Calendar.CAL_GREGORIAN");
switch (calType) {
case Calendar.CAL_GREGORIAN_US: // Gregorian (U.S.) calendar
get {
Contract.Ensures(Contract.Result<Calendar>() != null);
if (calendar == null) {
- Contract.Assert(this.m_cultureData.CalendarIds.Length > 0, "this.m_cultureData.CalendarIds.Length > 0");
+ Debug.Assert(this.m_cultureData.CalendarIds.Length > 0, "this.m_cultureData.CalendarIds.Length > 0");
// Get the default calendar for this culture. Note that the value can be
// from registry if this is a user default culture.
Calendar newObj = this.m_cultureData.DefaultCalendar;
private static String GetDefaultLocaleName(int localeType)
{
- Contract.Assert(localeType == LOCALE_USER_DEFAULT || localeType == LOCALE_SYSTEM_DEFAULT, "[CultureInfo.GetDefaultLocaleName] localeType must be LOCALE_USER_DEFAULT or LOCALE_SYSTEM_DEFAULT");
+ Debug.Assert(localeType == LOCALE_USER_DEFAULT || localeType == LOCALE_SYSTEM_DEFAULT, "[CultureInfo.GetDefaultLocaleName] localeType must be LOCALE_USER_DEFAULT or LOCALE_SYSTEM_DEFAULT");
string localeName = null;
if(InternalGetDefaultLocaleName(localeType, JitHelpers.GetStringHandleOnStack(ref localeName)))
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
/*
//
////////////////////////////////////////////////////////////////////////////
internal static void FormatDigits(StringBuilder outputBuffer, int value, int len) {
- Contract.Assert(value >= 0, "DateTimeFormat.FormatDigits(): value >= 0");
+ Debug.Assert(value >= 0, "DateTimeFormat.FormatDigits(): value >= 0");
FormatDigits(outputBuffer, value, len, false);
}
internal unsafe static void FormatDigits(StringBuilder outputBuffer, int value, int len, bool overrideLengthLimit) {
- Contract.Assert(value >= 0, "DateTimeFormat.FormatDigits(): value >= 0");
+ Debug.Assert(value >= 0, "DateTimeFormat.FormatDigits(): value >= 0");
// Limit the use of this function to be two-digits, so that we have the same behavior
// as RTM bits.
private static String FormatDayOfWeek(int dayOfWeek, int repeat, DateTimeFormatInfo dtfi)
{
- Contract.Assert(dayOfWeek >= 0 && dayOfWeek <= 6, "dayOfWeek >= 0 && dayOfWeek <= 6");
+ Debug.Assert(dayOfWeek >= 0 && dayOfWeek <= 6, "dayOfWeek >= 0 && dayOfWeek <= 6");
if (repeat == 3)
{
return (dtfi.GetAbbreviatedDayName((DayOfWeek)dayOfWeek));
private static String FormatMonth(int month, int repeatCount, DateTimeFormatInfo dtfi)
{
- Contract.Assert(month >=1 && month <= 12, "month >=1 && month <= 12");
+ Debug.Assert(month >=1 && month <= 12, "month >=1 && month <= 12");
if (repeatCount == 3)
{
return (dtfi.GetAbbreviatedMonthName(month));
*/
private static String FormatHebrewMonthName(DateTime time, int month, int repeatCount, DateTimeFormatInfo dtfi)
{
- Contract.Assert(repeatCount != 3 || repeatCount != 4, "repeateCount should be 3 or 4");
+ Debug.Assert(repeatCount != 3 || repeatCount != 4, "repeateCount should be 3 or 4");
if (dtfi.Calendar.IsLeapYear(dtfi.Calendar.GetYear(time))) {
// This month is in a leap year
return (dtfi.internalGetMonthName(month, MonthNameStyles.LeapYear, (repeatCount == 3)));
index++;
}
- Contract.Assert(val == 0, "DateTimeFormat.AppendNumber(): digits less than size of val");
+ Debug.Assert(val == 0, "DateTimeFormat.AppendNumber(): digits less than size of val");
}
internal static String[] GetAllDateTimes(DateTime dateTime, char format, DateTimeFormatInfo dtfi)
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
//
{
// Get the abbreviated day names for our current calendar
this.abbreviatedDayNames = this.m_cultureData.AbbreviatedDayNames(Calendar.ID);
- Contract.Assert(this.abbreviatedDayNames.Length == 7, "[DateTimeFormatInfo.GetAbbreviatedDayOfWeekNames] Expected 7 day names in a week");
+ Debug.Assert(this.abbreviatedDayNames.Length == 7, "[DateTimeFormatInfo.GetAbbreviatedDayOfWeekNames] Expected 7 day names in a week");
}
return (this.abbreviatedDayNames);
}
{
// Get the super short day names for our current calendar
this.m_superShortDayNames = this.m_cultureData.SuperShortDayNames(Calendar.ID);
- Contract.Assert(this.m_superShortDayNames.Length == 7, "[DateTimeFormatInfo.internalGetSuperShortDayNames] Expected 7 day names in a week");
+ Debug.Assert(this.m_superShortDayNames.Length == 7, "[DateTimeFormatInfo.internalGetSuperShortDayNames] Expected 7 day names in a week");
}
return (this.m_superShortDayNames);
}
{
// Get the day names for our current calendar
this.dayNames = this.m_cultureData.DayNames(Calendar.ID);
- Contract.Assert(this.dayNames.Length == 7, "[DateTimeFormatInfo.GetDayOfWeekNames] Expected 7 day names in a week");
+ Debug.Assert(this.dayNames.Length == 7, "[DateTimeFormatInfo.GetDayOfWeekNames] Expected 7 day names in a week");
}
return (this.dayNames);
}
{
// Get the month names for our current calendar
this.abbreviatedMonthNames = this.m_cultureData.AbbreviatedMonthNames(Calendar.ID);
- Contract.Assert(this.abbreviatedMonthNames.Length == 12 || this.abbreviatedMonthNames.Length == 13,
+ Debug.Assert(this.abbreviatedMonthNames.Length == 12 || this.abbreviatedMonthNames.Length == 13,
"[DateTimeFormatInfo.GetAbbreviatedMonthNames] Expected 12 or 13 month names in a year");
}
return (this.abbreviatedMonthNames);
{
// Get the month names for our current calendar
this.monthNames = this.m_cultureData.MonthNames(Calendar.ID);
- Contract.Assert(this.monthNames.Length == 12 || this.monthNames.Length == 13,
+ Debug.Assert(this.monthNames.Length == 12 || this.monthNames.Length == 13,
"[DateTimeFormatInfo.GetMonthNames] Expected 12 or 13 month names in a year");
}
// Silverlight 2.0 never took a snapshot of the user's overridable properties
// This has a substantial performance impact so skip when CoreCLR
Contract.Requires(cultureData != null);
- Contract.Assert(calendarID > 0, "[DateTimeFormatInfo.Populate] Expected Calendar.ID > 0");
+ Debug.Assert(calendarID > 0, "[DateTimeFormatInfo.Populate] Expected Calendar.ID > 0");
if (this.firstDayOfWeek == -1) { this.firstDayOfWeek = cultureData.IFIRSTDAYOFWEEK; }
if (this.calendarWeekRule == -1) { this.calendarWeekRule = cultureData.IFIRSTWEEKOFYEAR; }
if (this.dateSeparator == null) { this.dateSeparator = cultureData.DateSeparator(calendarID); }
this.allLongTimePatterns = this.m_cultureData.LongTimes;
- Contract.Assert(this.allLongTimePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some long time patterns");
+ Debug.Assert(this.allLongTimePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some long time patterns");
this.allShortTimePatterns = this.m_cultureData.ShortTimes;
- Contract.Assert(this.allShortTimePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some short time patterns");
+ Debug.Assert(this.allShortTimePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some short time patterns");
this.allLongDatePatterns = cultureData.LongDates(calendarID);
- Contract.Assert(this.allLongDatePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some long date patterns");
+ Debug.Assert(this.allLongDatePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some long date patterns");
this.allShortDatePatterns = cultureData.ShortDates(calendarID);
- Contract.Assert(this.allShortDatePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some short date patterns");
+ Debug.Assert(this.allShortDatePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some short date patterns");
this.allYearMonthPatterns = cultureData.YearMonths(calendarID);
- Contract.Assert(this.allYearMonthPatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some year month patterns");
+ Debug.Assert(this.allYearMonthPatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some year month patterns");
}
#region Serialization
this.amDesignator = this.m_cultureData.SAM1159;
}
- Contract.Assert(this.amDesignator != null, "DateTimeFormatInfo.AMDesignator, amDesignator != null");
+ Debug.Assert(this.amDesignator != null, "DateTimeFormatInfo.AMDesignator, amDesignator != null");
return (this.amDesignator);
}
get {
Contract.Ensures(Contract.Result<Calendar>() != null);
- Contract.Assert(this.calendar != null, "DateTimeFormatInfo.Calendar: calendar != null");
+ Debug.Assert(this.calendar != null, "DateTimeFormatInfo.Calendar: calendar != null");
return (this.calendar);
}
{
if (this.m_abbrevEnglishEraNames == null)
{
- Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.AbbreviatedEnglishEraNames] Expected Calendar.ID > 0");
+ Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.AbbreviatedEnglishEraNames] Expected Calendar.ID > 0");
this.m_abbrevEnglishEraNames = this.m_cultureData.AbbreviatedEnglishEraNames(Calendar.ID);
}
return (this.m_abbrevEnglishEraNames);
this.dateSeparator = this.m_cultureData.DateSeparator(Calendar.ID);
}
- Contract.Assert(this.dateSeparator != null, "DateTimeFormatInfo.DateSeparator, dateSeparator != null");
+ Debug.Assert(this.dateSeparator != null, "DateTimeFormatInfo.DateSeparator, dateSeparator != null");
return (this.dateSeparator);
}
this.firstDayOfWeek = this.m_cultureData.IFIRSTDAYOFWEEK;
}
- Contract.Assert(this.firstDayOfWeek != -1, "DateTimeFormatInfo.FirstDayOfWeek, firstDayOfWeek != -1");
+ Debug.Assert(this.firstDayOfWeek != -1, "DateTimeFormatInfo.FirstDayOfWeek, firstDayOfWeek != -1");
return ((DayOfWeek)this.firstDayOfWeek);
}
this.calendarWeekRule = this.m_cultureData.IFIRSTWEEKOFYEAR;
}
- Contract.Assert(this.calendarWeekRule != -1, "DateTimeFormatInfo.CalendarWeekRule, calendarWeekRule != -1");
+ Debug.Assert(this.calendarWeekRule != -1, "DateTimeFormatInfo.CalendarWeekRule, calendarWeekRule != -1");
return ((CalendarWeekRule)this.calendarWeekRule);
}
{
if (this.monthDayPattern == null)
{
- Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.MonthDayPattern] Expected calID > 0");
+ Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.MonthDayPattern] Expected calID > 0");
this.monthDayPattern = this.m_cultureData.MonthDay(Calendar.ID);
}
- Contract.Assert(this.monthDayPattern != null, "DateTimeFormatInfo.MonthDayPattern, monthDayPattern != null");
+ Debug.Assert(this.monthDayPattern != null, "DateTimeFormatInfo.MonthDayPattern, monthDayPattern != null");
return (this.monthDayPattern);
}
this.pmDesignator = this.m_cultureData.SPM2359;
}
- Contract.Assert(this.pmDesignator != null, "DateTimeFormatInfo.PMDesignator, pmDesignator != null");
+ Debug.Assert(this.pmDesignator != null, "DateTimeFormatInfo.PMDesignator, pmDesignator != null");
return (this.pmDesignator);
}
timeSeparator = this.m_cultureData.TimeSeparator;
}
- Contract.Assert(this.timeSeparator != null, "DateTimeFormatInfo.TimeSeparator, timeSeparator != null");
+ Debug.Assert(this.timeSeparator != null, "DateTimeFormatInfo.TimeSeparator, timeSeparator != null");
return (timeSeparator);
}
if (this.m_genitiveAbbreviatedMonthNames == null)
{
this.m_genitiveAbbreviatedMonthNames = this.m_cultureData.AbbreviatedGenitiveMonthNames(this.Calendar.ID);
- Contract.Assert(this.m_genitiveAbbreviatedMonthNames.Length == 13,
+ Debug.Assert(this.m_genitiveAbbreviatedMonthNames.Length == 13,
"[DateTimeFormatInfo.GetGenitiveMonthNames] Expected 13 abbreviated genitive month names in a year");
}
return (this.m_genitiveAbbreviatedMonthNames);
if (this.genitiveMonthNames == null)
{
this.genitiveMonthNames = this.m_cultureData.GenitiveMonthNames(this.Calendar.ID);
- Contract.Assert(this.genitiveMonthNames.Length == 13,
+ Debug.Assert(this.genitiveMonthNames.Length == 13,
"[DateTimeFormatInfo.GetGenitiveMonthNames] Expected 13 genitive month names in a year");
}
return (this.genitiveMonthNames);
internal String[] internalGetLeapYearMonthNames(/*bool abbreviated*/) {
if (this.leapYearMonthNames == null)
{
- Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.internalGetLeapYearMonthNames] Expected Calendar.ID > 0");
+ Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.internalGetLeapYearMonthNames] Expected Calendar.ID > 0");
this.leapYearMonthNames = this.m_cultureData.LeapYearMonthNames(Calendar.ID);
- Contract.Assert(this.leapYearMonthNames.Length == 13,
+ Debug.Assert(this.leapYearMonthNames.Length == 13,
"[DateTimeFormatInfo.internalGetLeapYearMonthNames] Expepcted 13 leap year month names");
}
return (leapYearMonthNames);
// The resulting [] can get returned to the calling app, so clone it.
private static string[] GetMergedPatterns(string [] patterns, string defaultPattern)
{
- Contract.Assert(patterns != null && patterns.Length > 0,
+ Debug.Assert(patterns != null && patterns.Length > 0,
"[DateTimeFormatInfo.GetMergedPatterns]Expected array of at least one pattern");
- Contract.Assert(defaultPattern != null,
+ Debug.Assert(defaultPattern != null,
"[DateTimeFormatInfo.GetMergedPatterns]Expected non null default string");
// If the default happens to be the first in the list just return (a cloned) copy
{
if (this.allYearMonthPatterns == null)
{
- Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedYearMonthPatterns] Expected Calendar.ID > 0");
+ Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedYearMonthPatterns] Expected Calendar.ID > 0");
this.allYearMonthPatterns = this.m_cultureData.YearMonths(this.Calendar.ID);
- Contract.Assert(this.allYearMonthPatterns.Length > 0,
+ Debug.Assert(this.allYearMonthPatterns.Length > 0,
"[DateTimeFormatInfo.UnclonedYearMonthPatterns] Expected some year month patterns");
}
{
if (allShortDatePatterns == null)
{
- Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedShortDatePatterns] Expected Calendar.ID > 0");
+ Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedShortDatePatterns] Expected Calendar.ID > 0");
this.allShortDatePatterns = this.m_cultureData.ShortDates(this.Calendar.ID);
- Contract.Assert(this.allShortDatePatterns.Length > 0,
+ Debug.Assert(this.allShortDatePatterns.Length > 0,
"[DateTimeFormatInfo.UnclonedShortDatePatterns] Expected some short date patterns");
}
{
if (allLongDatePatterns == null)
{
- Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedLongDatePatterns] Expected Calendar.ID > 0");
+ Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedLongDatePatterns] Expected Calendar.ID > 0");
this.allLongDatePatterns = this.m_cultureData.LongDates(this.Calendar.ID);
- Contract.Assert(this.allLongDatePatterns.Length > 0,
+ Debug.Assert(this.allLongDatePatterns.Length > 0,
"[DateTimeFormatInfo.UnclonedLongDatePatterns] Expected some long date patterns");
}
if (this.allShortTimePatterns == null)
{
this.allShortTimePatterns = this.m_cultureData.ShortTimes;
- Contract.Assert(this.allShortTimePatterns.Length > 0,
+ Debug.Assert(this.allShortTimePatterns.Length > 0,
"[DateTimeFormatInfo.UnclonedShortTimePatterns] Expected some short time patterns");
}
if (this.allLongTimePatterns == null)
{
this.allLongTimePatterns = this.m_cultureData.LongTimes;
- Contract.Assert(this.allLongTimePatterns.Length > 0,
+ Debug.Assert(this.allLongTimePatterns.Length > 0,
"[DateTimeFormatInfo.UnclonedLongTimePatterns] Expected some long time patterns");
}
} while (i < str.Value.Length && (state != HebrewNumberParsingState.FoundEndOfHebrewNumber));
// When we are here, we are either at the end of the string, or we find a valid Hebrew number.
- Contract.Assert(state == HebrewNumberParsingState.ContinueParsing || state == HebrewNumberParsingState.FoundEndOfHebrewNumber,
+ Debug.Assert(state == HebrewNumberParsingState.ContinueParsing || state == HebrewNumberParsingState.FoundEndOfHebrewNumber,
"Invalid returned state from HebrewNumber.ParseByChar()");
if (state != HebrewNumberParsingState.FoundEndOfHebrewNumber) {
tokenValue = 0;
TokenHashValue value;
- Contract.Assert(str.Index < str.Value.Length, "DateTimeFormatInfo.Tokenize(): start < value.Length");
+ Debug.Assert(str.Index < str.Value.Length, "DateTimeFormatInfo.Tokenize(): start < value.Length");
char ch = str.m_current;
bool isLetter = Char.IsLetter(ch);
}
previousNode = temp;
} ;
- Contract.Assert(false, "The hashtable is full. This should not happen.");
+ Debug.Assert(false, "The hashtable is full. This should not happen.");
}
void InsertHash(TokenHashValue[] hashTable, String str, TokenType tokenType, int tokenValue) {
hashcode += hashProbe;
if (hashcode >= TOKEN_HASH_SIZE) hashcode -= TOKEN_HASH_SIZE;
} while (i < TOKEN_HASH_SIZE);
- Contract.Assert(false, "The hashtable is full. This should not happen.");
+ Debug.Assert(false, "The hashtable is full. This should not happen.");
}
} // class DateTimeFormatInfo
return false;
}
- Contract.Assert(dtfi != null, "dtfi == null");
+ Debug.Assert(dtfi != null, "dtfi == null");
return DoStrictParse(s, format, style, dtfi, ref result);
}
return false;
}
- Contract.Assert(dtfi != null, "dtfi == null");
+ Debug.Assert(dtfi != null, "dtfi == null");
//
// Do a loop through the provided formats and see if we can parse succesfully in
// Wrong number of digits
return false;
}
- Contract.Assert(hourOffset >= 0 && hourOffset <= 99, "hourOffset >= 0 && hourOffset <= 99");
- Contract.Assert(minuteOffset >= 0 && minuteOffset <= 99, "minuteOffset >= 0 && minuteOffset <= 99");
+ Debug.Assert(hourOffset >= 0 && hourOffset <= 99, "hourOffset >= 0 && hourOffset <= 99");
+ Debug.Assert(minuteOffset >= 0 && minuteOffset <= 99, "minuteOffset >= 0 && minuteOffset <= 99");
if (minuteOffset < 0 || minuteOffset >= 60) {
return false;
}
private static Boolean GetTimeOfNN(DateTimeFormatInfo dtfi, ref DateTimeResult result, ref DateTimeRawInfo raw)
{
- Contract.Assert(raw.numCount >= 2, "raw.numCount >= 2");
+ Debug.Assert(raw.numCount >= 2, "raw.numCount >= 2");
if ((result.flags & ParseFlags.HaveTime) != 0) {
// Multiple times in the input string
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
return false;
}
- Contract.Assert(raw.numCount >= 3, "raw.numCount >= 3");
+ Debug.Assert(raw.numCount >= 3, "raw.numCount >= 3");
result.Hour = raw.GetNumber(0);
result.Minute = raw.GetNumber(1);
result.Second = raw.GetNumber(2);
return false;
}
- Contract.Assert(dtfi != null, "dtfi == null");
+ Debug.Assert(dtfi != null, "dtfi == null");
#if _LOGGING
DTFITrace(dtfi);
}
else {
// No time zone and no Assume flags, so DateTimeKind.Unspecified is fine
- Contract.Assert(result.parsedDate.Kind == DateTimeKind.Unspecified, "result.parsedDate.Kind == DateTimeKind.Unspecified");
+ Debug.Assert(result.parsedDate.Kind == DateTimeKind.Unspecified, "result.parsedDate.Kind == DateTimeKind.Unspecified");
return true;
}
}
}
internal static bool ParseDigits(ref __DTString str, int minDigitLen, int maxDigitLen, out int result) {
- Contract.Assert(minDigitLen > 0, "minDigitLen > 0");
- Contract.Assert(maxDigitLen < 9, "maxDigitLen < 9");
- Contract.Assert(minDigitLen <= maxDigitLen, "minDigitLen <= maxDigitLen");
+ Debug.Assert(minDigitLen > 0, "minDigitLen > 0");
+ Debug.Assert(maxDigitLen < 9, "maxDigitLen < 9");
+ Debug.Assert(minDigitLen <= maxDigitLen, "minDigitLen <= maxDigitLen");
result = 0;
int startingIndex = str.Index;
int tokenLength = 0;
case ParseFailureKind.FormatBadDateTimeCalendar:
return new FormatException(Environment.GetResourceString(result.failureMessageID, result.calendar));
default:
- Contract.Assert(false, "Unkown DateTimeParseFailure: " + result);
+ Debug.Assert(false, "Unkown DateTimeParseFailure: " + result);
return null;
}
}
internal bool Advance(int count) {
- Contract.Assert(Index + count <= len, "__DTString::Advance: Index + count <= len");
+ Debug.Assert(Index + count <= len, "__DTString::Advance: Index + count <= len");
Index += count;
if (Index < len) {
m_current = Value[Index];
// Get the current character.
//
internal char GetChar() {
- Contract.Assert(Index >= 0 && Index < len, "Index >= 0 && Index < len");
+ Debug.Assert(Index >= 0 && Index < len, "Index >= 0 && Index < len");
return (Value[Index]);
}
// Convert the current character to a digit, and return it.
//
internal int GetDigit() {
- Contract.Assert(Index >= 0 && Index < len, "Index >= 0 && Index < len");
- Contract.Assert(DateTimeParse.IsDigit(Value[Index]), "IsDigit(Value[Index])");
+ Debug.Assert(Index >= 0 && Index < len, "Index >= 0 && Index < len");
+ Debug.Assert(DateTimeParse.IsDigit(Value[Index]), "IsDigit(Value[Index])");
return (Value[Index] - '0');
}
return sub;
}
int number = ch - '0';
- Contract.Assert(number >= 0 && number <= 9, "number >= 0 && number <= 9");
+ Debug.Assert(number >= 0 && number <= 9, "number >= 0 && number <= 9");
sub.value = sub.value * 10 + number;
}
else {
}
internal void ConsumeSubString(DTSubString sub) {
- Contract.Assert(sub.index == Index, "sub.index == Index");
- Contract.Assert(sub.index + sub.length <= len, "sub.index + sub.length <= len");
+ Debug.Assert(sub.index == Index, "sub.index == Index");
+ Debug.Assert(sub.index + sub.length <= len, "sub.index + sub.length <= len");
Index = sub.index + sub.length;
if (Index < len) {
m_current = Value[Index];
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Text;
break;
}
- Contract.Assert(item == null || item.CodePage == codepage, "item.CodePage needs to equal the specified codepage");
+ Debug.Assert(item == null || item.CodePage == codepage, "item.CodePage needs to equal the specified codepage");
return item;
}
#if DEBUG
static EncodingTable()
{
- Contract.Assert(
+ Debug.Assert(
s_encodingDataTable.Count == EncodingTableCapacity,
string.Format(CultureInfo.InvariantCulture,
"EncodingTable s_encodingDataTable's initial capacity (EncodingTableCapacity) is incorrect.{0}Expected (s_encodingDataTable.Count): {1}, Actual (EncodingTableCapacity): {2}",
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using System.IO;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
//
// ----------------------------------------------------------------------------------------------------
internal unsafe static byte* GetGlobalizationResourceBytePtr(Assembly assembly, String tableName) {
- Contract.Assert(assembly != null, "assembly can not be null. This should be generally the "+System.CoreLib.Name+" assembly.");
- Contract.Assert(tableName != null, "table name can not be null");
+ Debug.Assert(assembly != null, "assembly can not be null. This should be generally the "+System.CoreLib.Name+" assembly.");
+ Debug.Assert(tableName != null, "table name can not be null");
Stream stream = assembly.GetManifestResourceStream(tableName);
UnmanagedMemoryStream bytesStream = stream as UnmanagedMemoryStream;
}
}
- Contract.Assert(
+ Debug.Assert(
false,
String.Format(
CultureInfo.CurrentCulture,
namespace System.Globalization {
using System;
using System.Text;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
////////////////////////////////////////////////////////////////////////////
// is true.
//
NumDays -= (long)(LunarMonthLen[hebrewYearType, lunarDate.month] - lunarDate.day);
- Contract.Assert(NumDays >= 1, "NumDays >= 1");
+ Debug.Assert(NumDays >= 1, "NumDays >= 1");
// If NumDays is 1, then we are done. Otherwise, find the correct Hebrew month
// and day.
int hebrewYearType = GetHebrewYearType(year, era);
CheckHebrewMonthValue(year, month, era);
- Contract.Assert(hebrewYearType>= 1 && hebrewYearType <= 6,
+ Debug.Assert(hebrewYearType>= 1 && hebrewYearType <= 6,
"hebrewYearType should be from 1 to 6, but now hebrewYearType = " + hebrewYearType + " for hebrew year " + year);
int monthDays = LunarMonthLen[hebrewYearType, month];
if (monthDays == 0) {
namespace System.Globalization {
using System;
using System.Text;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
////////////////////////////////////////////////////////////////////////////
Number -= 5000;
}
- Contract.Assert(Number > 0 && Number <= 999, "Number is out of range.");;
+ Debug.Assert(Number > 0 && Number <= 999, "Number is out of range.");;
//
// Get the Hundreds.
using System.Text;
using System.Runtime.Versioning;
using System.Runtime.InteropServices;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
// IdnMapping class used to map names to Punycode
// Cannot be null terminated (normalization won't help us with this one, and
// may have returned false before checking the whole string above)
- Contract.Assert(unicode.Length >= 1, "[IdnMapping.GetAscii]Expected 0 length strings to fail before now.");
+ Debug.Assert(unicode.Length >= 1, "[IdnMapping.GetAscii]Expected 0 length strings to fail before now.");
if (unicode[unicode.Length - 1] <= 0x1f)
{
throw new ArgumentException(
static char encode_digit(int d)
{
- Contract.Assert(d >= 0 && d < punycodeBase, "[IdnMapping.encode_digit]Expected 0 <= d < punycodeBase");
+ Debug.Assert(d >= 0 && d < punycodeBase, "[IdnMapping.encode_digit]Expected 0 <= d < punycodeBase");
// 26-35 map to ASCII 0-9
if (d > 25) return (char)(d - 26 + '0');
uint k;
delta = firsttime ? delta / damp : delta / 2;
- Contract.Assert(numpoints != 0, "[IdnMapping.adapt]Expected non-zero numpoints.");
+ Debug.Assert(numpoints != 0, "[IdnMapping.adapt]Expected non-zero numpoints.");
delta += delta / numpoints;
for (k = 0; delta > ((punycodeBase - tmin) * tmax) / 2; k += punycodeBase)
delta /= punycodeBase - tmin;
}
- Contract.Assert(delta + skew != 0, "[IdnMapping.adapt]Expected non-zero delta+skew.");
+ Debug.Assert(delta + skew != 0, "[IdnMapping.adapt]Expected non-zero delta+skew.");
return (int)(k + (punycodeBase - tmin + 1) * delta / (delta + skew));
}
{
// Find end of this segment
iNextDot = unicode.IndexOfAny(M_Dots, iAfterLastDot);
- Contract.Assert(iNextDot <= unicode.Length, "[IdnMapping.punycode_encode]IndexOfAny is broken");
+ Debug.Assert(iNextDot <= unicode.Length, "[IdnMapping.punycode_encode]IndexOfAny is broken");
if (iNextDot < 0)
iNextDot = unicode.Length;
for (basicCount = iAfterLastDot; basicCount < iNextDot; basicCount++)
{
// Can't be lonely surrogate because it would've thrown in normalization
- Contract.Assert(Char.IsLowSurrogate(unicode, basicCount) == false,
+ Debug.Assert(Char.IsLowSurrogate(unicode, basicCount) == false,
"[IdnMapping.punycode_encode]Unexpected low surrogate");
// Double check our bidi rules
/* Increase delta enough to advance the decoder's */
/* <n,i> state to <m,0>, but guard against overflow: */
delta += (int)((m - n) * ((numProcessed - numSurrogatePairs) + 1));
- Contract.Assert(delta > 0, "[IdnMapping.cs]1 punycode_encode - delta overflowed int");
+ Debug.Assert(delta > 0, "[IdnMapping.cs]1 punycode_encode - delta overflowed int");
n = m;
for (j = iAfterLastDot; j < iNextDot; j+= IsSupplementary(test) ? 2 : 1)
if (test < n)
{
delta++;
- Contract.Assert(delta > 0, "[IdnMapping.cs]2 punycode_encode - delta overflowed int");
+ Debug.Assert(delta > 0, "[IdnMapping.cs]2 punycode_encode - delta overflowed int");
}
if (test == n)
int t = k <= bias ? tmin :
k >= bias + tmax ? tmax : k - bias;
if (q < t) break;
- Contract.Assert(punycodeBase != t, "[IdnMapping.punycode_encode]Expected punycodeBase (36) to be != t");
+ Debug.Assert(punycodeBase != t, "[IdnMapping.punycode_encode]Expected punycodeBase (36) to be != t");
int mod;
q = Math.DivRem(q - t, punycodeBase - t, out mod);
}
++delta;
++n;
- Contract.Assert(delta > 0, "[IdnMapping.cs]3 punycode_encode - delta overflowed int");
+ Debug.Assert(delta > 0, "[IdnMapping.cs]3 punycode_encode - delta overflowed int");
}
}
// decode the digit from the next char
int digit = decode_digit(ascii[asciiIndex++]);
- Contract.Assert(w > 0, "[IdnMapping.punycode_decode]Expected w > 0");
+ Debug.Assert(w > 0, "[IdnMapping.punycode_decode]Expected w > 0");
if (digit > (maxint - i) / w)
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadPunycode"), nameof(ascii));
int t = k <= bias ? tmin :
k >= bias + tmax ? tmax : k - bias;
if (digit < t) break;
- Contract.Assert(punycodeBase != t, "[IdnMapping.punycode_decode]Expected t != punycodeBase (36)");
+ Debug.Assert(punycodeBase != t, "[IdnMapping.punycode_decode]Expected t != punycodeBase (36)");
if (w > maxint / (punycodeBase - t))
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadPunycode"), nameof(ascii));
/* i was supposed to wrap around from output.Length to 0, */
/* incrementing n each time, so we'll fix that now: */
- Contract.Assert((output.Length - iOutputAfterLastDot - numSurrogatePairs) + 1 > 0,
+ Debug.Assert((output.Length - iOutputAfterLastDot - numSurrogatePairs) + 1 > 0,
"[IdnMapping.punycode_decode]Expected to have added > 0 characters this segment");
if (i / ((output.Length - iOutputAfterLastDot - numSurrogatePairs) + 1) > maxint - n)
throw new ArgumentException(Environment.GetResourceString(
namespace System.Globalization {
using System;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
////////////////////////////////////////////////////////////////////////////
static int MonthFromOrdinalDay(int ordinalDay)
{
- Contract.Assert(ordinalDay <= 366);
+ Debug.Assert(ordinalDay <= 366);
int index = 0;
while (ordinalDay > DaysToMonth[index])
index++;
static int DaysInPreviousMonths(int month)
{
- Contract.Assert(1 <= month && month <= 12);
+ Debug.Assert(1 <= month && month <= 12);
--month; // months are one based but for calculations use 0 based
return DaysToMonth[month];
}
long yearStart = CalendricalCalculationsHelper.PersianNewYearOnOrBefore(NumDays);
int y = (int)(Math.Floor(((yearStart - PersianEpoch) / CalendricalCalculationsHelper.MeanTropicalYearInDays) + 0.5)) + 1;
- Contract.Assert(y >= 1);
+ Debug.Assert(y >= 1);
if (part == DatePartYear)
{
}
int m = MonthFromOrdinalDay(ordinalDay);
- Contract.Assert(ordinalDay >= 1);
- Contract.Assert(m >= 1 && m <= 12);
+ Debug.Assert(ordinalDay >= 1);
+ Debug.Assert(m >= 1 && m <= 12);
if (part == DatePartMonth)
{
return m;
}
int d = ordinalDay - DaysInPreviousMonths(m);
- Contract.Assert(1 <= d);
- Contract.Assert(d <= 31);
+ Debug.Assert(1 <= d);
+ Debug.Assert(d <= 31);
//
// Calculate the Persian Day.
int daysInMonth = DaysToMonth[month] - DaysToMonth[month - 1];
if ((month == MonthsPerYear) && !IsLeapYear(year))
{
- Contract.Assert(daysInMonth == 30);
+ Debug.Assert(daysInMonth == 30);
--daysInMonth;
}
return daysInMonth;
using System;
using System.Runtime.Serialization;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[Serializable]
////////////////////////////////////////////////////////////////////////
public virtual String Name {
get {
- Contract.Assert(m_name != null, "Expected RegionInfo.m_name to be populated already");
+ Debug.Assert(m_name != null, "Expected RegionInfo.m_name to be populated already");
return (m_name);
}
}
using System;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[System.Runtime.InteropServices.ComVisible(true)]
byte[] key1Data = sortkey1.m_KeyData;
byte[] key2Data = sortkey2.m_KeyData;
- Contract.Assert(key1Data!=null, "key1Data!=null");
- Contract.Assert(key2Data!=null, "key2Data!=null");
+ Debug.Assert(key1Data!=null, "key1Data!=null");
+ Debug.Assert(key2Data!=null, "key2Data!=null");
if (key1Data.Length == 0) {
if (key2Data.Length == 0) {
using System;
using System.Runtime.Serialization;
using System.Security.Permissions;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[Serializable]
internal static int GetCurrentTextElementLen(String str, int index, int len, ref UnicodeCategory ucCurrent, ref int currentCharCount)
{
- Contract.Assert(index >= 0 && len >= 0, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
- Contract.Assert(index < len, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
+ Debug.Assert(index >= 0 && len >= 0, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
+ Debug.Assert(index < len, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
if (index + currentCharCount == len)
{
// This is the last character/surrogate in the string.
namespace System.Globalization {
using System.Collections;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
//
internal TextElementEnumerator(String str, int startIndex, int strLen)
{
- Contract.Assert(str != null, "TextElementEnumerator(): str != null");
- Contract.Assert(startIndex >= 0 && strLen >= 0, "TextElementEnumerator(): startIndex >= 0 && strLen >= 0");
- Contract.Assert(strLen >= startIndex, "TextElementEnumerator(): strLen >= startIndex");
+ Debug.Assert(str != null, "TextElementEnumerator(): str != null");
+ Debug.Assert(startIndex >= 0 && strLen >= 0, "TextElementEnumerator(): startIndex >= 0 && strLen >= 0");
+ Debug.Assert(strLen >= startIndex, "TextElementEnumerator(): strLen >= startIndex");
this.str = str;
this.startIndex = startIndex;
this.strLen = strLen;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security.Permissions;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
// The underlying unmanaged code will assert the sanity of arguments.
internal static unsafe int CompareOrdinalIgnoreCaseEx(String strA, int indexA, String strB, int indexB, int lengthA, int lengthB )
{
- Contract.Assert(strA.Length >= indexA + lengthA, "[TextInfo.CompareOrdinalIgnoreCaseEx] Caller should've validated strA.Length >= indexA + lengthA");
- Contract.Assert(strB.Length >= indexB + lengthB, "[TextInfo.CompareOrdinalIgnoreCaseEx] Caller should've validated strB.Length >= indexB + lengthB");
+ Debug.Assert(strA.Length >= indexA + lengthA, "[TextInfo.CompareOrdinalIgnoreCaseEx] Caller should've validated strA.Length >= indexA + lengthA");
+ Debug.Assert(strB.Length >= indexB + lengthB, "[TextInfo.CompareOrdinalIgnoreCaseEx] Caller should've validated strB.Length >= indexB + lengthB");
return InternalCompareStringOrdinalIgnoreCase(strA, indexA, strB, indexB, lengthA, lengthB);
}
internal static int IndexOfStringOrdinalIgnoreCase(String source, String value, int startIndex, int count)
{
- Contract.Assert(source != null, "[TextInfo.IndexOfStringOrdinalIgnoreCase] Caller should've validated source != null");
- Contract.Assert(value != null, "[TextInfo.IndexOfStringOrdinalIgnoreCase] Caller should've validated value != null");
- Contract.Assert(startIndex + count <= source.Length, "[TextInfo.IndexOfStringOrdinalIgnoreCase] Caller should've validated startIndex + count <= source.Length");
+ Debug.Assert(source != null, "[TextInfo.IndexOfStringOrdinalIgnoreCase] Caller should've validated source != null");
+ Debug.Assert(value != null, "[TextInfo.IndexOfStringOrdinalIgnoreCase] Caller should've validated value != null");
+ Debug.Assert(startIndex + count <= source.Length, "[TextInfo.IndexOfStringOrdinalIgnoreCase] Caller should've validated startIndex + count <= source.Length");
// We return 0 if both inputs are empty strings
if (source.Length == 0 && value.Length == 0)
for (; startIndex <= maxStartIndex; startIndex++)
{
// We should always have the same or more characters left to search than our actual pattern
- Contract.Assert(end - startIndex >= value.Length);
+ Debug.Assert(end - startIndex >= value.Length);
// since this is an ordinal comparison, we can assume that the lengths must match
if (CompareOrdinalIgnoreCaseEx(source, startIndex, value, 0, value.Length, value.Length) == 0)
{
internal static int LastIndexOfStringOrdinalIgnoreCase(String source, String value, int startIndex, int count)
{
- Contract.Assert(source != null, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated source != null");
- Contract.Assert(value != null, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated value != null");
- Contract.Assert(startIndex - count+1 >= 0, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated startIndex - count+1 >= 0");
- Contract.Assert(startIndex <= source.Length, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated startIndex <= source.Length");
+ Debug.Assert(source != null, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated source != null");
+ Debug.Assert(value != null, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated value != null");
+ Debug.Assert(startIndex - count+1 >= 0, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated startIndex - count+1 >= 0");
+ Debug.Assert(startIndex <= source.Length, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated startIndex <= source.Length");
// If value is Empty, the return value is startIndex
if (value.Length == 0)
private static int AddNonLetter(ref StringBuilder result, ref String input, int inputIndex, int charLen)
{
- Contract.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddNonLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!");
+ Debug.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddNonLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!");
if (charLen == 2)
{
// Surrogate pair
private int AddTitlecaseLetter(ref StringBuilder result, ref String input, int inputIndex, int charLen)
{
- Contract.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddTitlecaseLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!");
+ Debug.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddTitlecaseLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!");
// for surrogate pairs do a simple ToUpper operation on the substring
if (charLen == 2)
namespace System.Globalization {
using System.Text;
using System;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
//
internal static String FormatCustomized(TimeSpan value, String format, DateTimeFormatInfo dtfi) {
- Contract.Assert(dtfi != null, "dtfi == null");
+ Debug.Assert(dtfi != null, "dtfi == null");
int day = (int)(value._ticks / TimeSpan.TicksPerDay);
long time = value._ticks % TimeSpan.TicksPerDay;
case '\"':
if (inQuote && (quote == format[i])) {
/* we were in a quote and found a matching exit quote, so we are outside a quote now */
- Contract.Assert(field >= 0 && field <= 5, "field >= 0 && field <= 5");
+ Debug.Assert(field >= 0 && field <= 5, "field >= 0 && field <= 5");
if (field >= 0 && field <= 5) {
literals[field] = sb.ToString();
sb.Length = 0;
}
break;
case '%':
- Contract.Assert(false, "Unexpected special token '%', Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
+ Debug.Assert(false, "Unexpected special token '%', Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
goto default;
case '\\':
if (!inQuote) {
goto default;
case 'd':
if (!inQuote) {
- Contract.Assert((field == 0 && sb.Length == 0) || field == 1,
+ Debug.Assert((field == 0 && sb.Length == 0) || field == 1,
"field == 0 || field == 1, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 1; // DayHourSep
dd++;
break;
case 'h':
if (!inQuote) {
- Contract.Assert((field == 1 && sb.Length == 0) || field == 2,
+ Debug.Assert((field == 1 && sb.Length == 0) || field == 2,
"field == 1 || field == 2, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 2; // HourMinuteSep
hh++;
break;
case 'm':
if (!inQuote) {
- Contract.Assert((field == 2 && sb.Length == 0) || field == 3,
+ Debug.Assert((field == 2 && sb.Length == 0) || field == 3,
"field == 2 || field == 3, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 3; // MinuteSecondSep
mm++;
break;
case 's':
if (!inQuote) {
- Contract.Assert((field == 3 && sb.Length == 0) || field == 4,
+ Debug.Assert((field == 3 && sb.Length == 0) || field == 4,
"field == 3 || field == 4, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 4; // SecondFractionSep
ss++;
case 'f':
case 'F':
if (!inQuote) {
- Contract.Assert((field == 4 && sb.Length == 0) || field == 5,
+ Debug.Assert((field == 4 && sb.Length == 0) || field == 5,
"field == 4 || field == 5, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 5; // End
ff++;
}
}
- Contract.Assert(field == 5);
+ Debug.Assert(field == 5);
AppCompatLiteral = MinuteSecondSep + SecondFractionSep;
- Contract.Assert(0 < dd && dd < 3, "0 < dd && dd < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
- Contract.Assert(0 < hh && hh < 3, "0 < hh && hh < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
- Contract.Assert(0 < mm && mm < 3, "0 < mm && mm < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
- Contract.Assert(0 < ss && ss < 3, "0 < ss && ss < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
- Contract.Assert(0 < ff && ff < 8, "0 < ff && ff < 8, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
+ Debug.Assert(0 < dd && dd < 3, "0 < dd && dd < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
+ Debug.Assert(0 < hh && hh < 3, "0 < hh && hh < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
+ Debug.Assert(0 < mm && mm < 3, "0 < mm && mm < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
+ Debug.Assert(0 < ss && ss < 3, "0 < ss && ss < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
+ Debug.Assert(0 < ff && ff < 8, "0 < ff && ff < 8, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
if (useInvariantFieldLengths) {
dd = 2;
namespace System.Globalization {
using System.Text;
using System;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
}
public bool IsInvalidNumber(int maxValue, int maxPrecision) {
- Contract.Assert(ttt == TTT.Num);
- Contract.Assert(num > -1);
- Contract.Assert(maxValue > 0);
- Contract.Assert(maxPrecision == maxFractionDigits || maxPrecision == unlimitedDigits);
+ Debug.Assert(ttt == TTT.Num);
+ Debug.Assert(num > -1);
+ Debug.Assert(maxValue > 0);
+ Debug.Assert(maxPrecision == maxFractionDigits || maxPrecision == unlimitedDigits);
if (num > maxValue)
return true;
}
// used by the parsing routines that operate on standard-formats
internal TimeSpanToken GetNextToken() {
- Contract.Assert(m_pos > -1);
+ Debug.Assert(m_pos > -1);
TimeSpanToken tok = new TimeSpanToken();
char ch = CurrentChar;
private const int MaxNumericTokens = 5;
internal void Init(DateTimeFormatInfo dtfi) {
- Contract.Assert(dtfi != null);
+ Debug.Assert(dtfi != null);
lastSeenTTT = TTT.None;
tokenCount = 0;
}
lastSeenTTT = tok.ttt;
- Contract.Assert(tokenCount == (SepCount + NumCount), "tokenCount == (SepCount + NumCount)");
+ Debug.Assert(tokenCount == (SepCount + NumCount), "tokenCount == (SepCount + NumCount)");
return true;
}
return new OverflowException(Environment.GetResourceString(m_failureMessageID));
default:
- Contract.Assert(false, "Unknown TimeSpanParseFailure: " + m_failure);
+ Debug.Assert(false, "Unknown TimeSpanParseFailure: " + m_failure);
return new FormatException(Environment.GetResourceString("Format_InvalidString"));
}
}
// Actions: Parse the TimeSpan instance using the specified format. Used by TryParseExactTimeSpan.
//
private static Boolean TryParseByFormat(String input, String format, TimeSpanStyles styles, ref TimeSpanResult result) {
- Contract.Assert(input != null, "input != null");
- Contract.Assert(format != null, "format != null");
+ Debug.Assert(input != null, "input != null");
+ Debug.Assert(format != null, "format != null");
bool seenDD = false; // already processed days?
bool seenHH = false; // already processed hours?
namespace System.Globalization {
using System;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
=========================ConvertHijriToGregorian============================*/
static void ConvertHijriToGregorian(int HijriYear, int HijriMonth, int HijriDay, ref int yg, ref int mg, ref int dg)
{
- Contract.Assert( (HijriYear >= MinCalendarYear) && (HijriYear <= MaxCalendarYear), "Hijri year is out of range.");
- Contract.Assert( HijriMonth >= 1, "Hijri month is out of range.");
- Contract.Assert( HijriDay >= 1, "Hijri day is out of range.");
+ Debug.Assert( (HijriYear >= MinCalendarYear) && (HijriYear <= MaxCalendarYear), "Hijri year is out of range.");
+ Debug.Assert( HijriMonth >= 1, "Hijri month is out of range.");
+ Debug.Assert( HijriDay >= 1, "Hijri day is out of range.");
int index, b, nDays = HijriDay-1;
DateTime dt;
TimeSpan ts;
int yh1=0, mh1=0, dh1=0;
- Contract.Assert((time.Ticks >= minDate.Ticks) && (time.Ticks <= maxDate.Ticks), "Gregorian date is out of range.");
+ Debug.Assert((time.Ticks >= minDate.Ticks) && (time.Ticks <= maxDate.Ticks), "Gregorian date is out of range.");
// Find the index where we should start our search by quessing the Hijri year that we will be in HijriYearInfo.
// A Hijri year is 354 or 355 days. Use 355 days so that we will search from a lower index.
{
int days = 0, b;
- Contract.Assert( (year >= MinCalendarYear) && (year <= MaxCalendarYear), "Hijri year is out of range.");
+ Debug.Assert( (year >= MinCalendarYear) && (year <= MaxCalendarYear), "Hijri year is out of range.");
b = HijriYearInfo[year-MinCalendarYear].HijriMonthsLengthFlags;
days += 29 + (b & 0x1);
b = b >> 1;
}
- Contract.Assert((days == 354)||(days == 355), "Hijri year has to be 354 or 355 days.");
+ Debug.Assert((days == 354)||(days == 355), "Hijri year has to be 354 or 355 days.");
return days;
}
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
// Represents a Globally Unique Identifier.
}
internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument,
string failureArgumentName, Exception innerException) {
- Contract.Assert(failure != ParseFailureKind.NativeException, "ParseFailureKind.NativeException should not be used with this overload");
+ Debug.Assert(failure != ParseFailureKind.NativeException, "ParseFailureKind.NativeException should not be used with this overload");
m_failure = failure;
m_failureMessageID = failureMessageID;
m_failureMessageFormatArgument = failureMessageFormatArgument;
return m_innerException;
default:
- Contract.Assert(false, "Unknown GuidParseFailure: " + m_failure);
+ Debug.Assert(false, "Unknown GuidParseFailure: " + m_failure);
return new FormatException(Environment.GetResourceString("Format_GuidUnrecognized"));
}
}
public void Paused()
{
- Contract.Assert(!isPaused);
+ Debug.Assert(!isPaused);
if(ResumeEvent == null)
ResumeEvent = new ManualResetEvent(false);
public void Resuming()
{
- Contract.Assert(isPaused);
+ Debug.Assert(isPaused);
isPaused = false;
ResumeEvent.Set();
}
using System.Runtime;
using System.Text;
using System.Globalization;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Security;
m_isMemoryStream = (m_stream.GetType() == typeof(MemoryStream));
m_leaveOpen = leaveOpen;
- Contract.Assert(m_decoder!=null, "[BinaryReader.ctor]m_decoder!=null");
+ Debug.Assert(m_decoder!=null, "[BinaryReader.ctor]m_decoder!=null");
}
public virtual Stream BaseStream {
if (m_stream==null) __Error.FileNotOpen();
// read directly from MemoryStream buffer
MemoryStream mStream = m_stream as MemoryStream;
- Contract.Assert(mStream != null, "m_stream as MemoryStream != null");
+ Debug.Assert(mStream != null, "m_stream as MemoryStream != null");
return mStream.InternalReadInt32();
}
private int InternalReadChars(char[] buffer, int index, int count) {
Contract.Requires(buffer != null);
Contract.Requires(index >= 0 && count >= 0);
- Contract.Assert(m_stream != null);
+ Debug.Assert(m_stream != null);
int numBytes = 0;
int charsRemaining = count;
if (m_isMemoryStream)
{
MemoryStream mStream = m_stream as MemoryStream;
- Contract.Assert(mStream != null, "m_stream as MemoryStream != null");
+ Debug.Assert(mStream != null, "m_stream as MemoryStream != null");
position = mStream.InternalGetPosition();
numBytes = mStream.InternalEmulateRead(numBytes);
return (count - charsRemaining);
}
- Contract.Assert(byteBuffer != null, "expected byteBuffer to be non-null");
+ Debug.Assert(byteBuffer != null, "expected byteBuffer to be non-null");
checked
{
}
// this should never fail
- Contract.Assert(charsRemaining >= 0, "We read too many characters.");
+ Debug.Assert(charsRemaining >= 0, "We read too many characters.");
// we may have read fewer than the number of characters requested if end of stream reached
// or if the encoding makes the char count too big for the buffer (e.g. fallback sequence)
return -1;
}
- Contract.Assert(numBytes == 1 || numBytes == 2, "BinaryReader::InternalReadOneChar assumes it's reading one or 2 bytes only.");
+ Debug.Assert(numBytes == 1 || numBytes == 2, "BinaryReader::InternalReadOneChar assumes it's reading one or 2 bytes only.");
try {
throw;
}
- Contract.Assert(charsRead < 2, "InternalReadOneChar - assuming we only got 0 or 1 char, not 2!");
+ Debug.Assert(charsRead < 2, "InternalReadOneChar - assuming we only got 0 or 1 char, not 2!");
// Console.WriteLine("That became: " + charsRead + " characters.");
}
if (charsRead == 0)
using System.Runtime;
using System.Runtime.Serialization;
using System.Text;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.IO {
throw new ArgumentException(Environment.GetResourceString("Arg_SurrogatesNotAllowedAsSingleChar"));
Contract.EndContractBlock();
- Contract.Assert(_encoding.GetMaxByteCount(1) <= 16, "_encoding.GetMaxByteCount(1) <= 16)");
+ Debug.Assert(_encoding.GetMaxByteCount(1) <= 16, "_encoding.GetMaxByteCount(1) <= 16)");
int numBytes = 0;
fixed(byte * pBytes = _buffer) {
numBytes = _encoder.GetBytes(&ch, 1, pBytes, _buffer.Length, flush: true);
if (len <= _largeByteBuffer.Length)
{
- //Contract.Assert(len == _encoding.GetBytes(chars, 0, chars.Length, _largeByteBuffer, 0), "encoding's GetByteCount & GetBytes gave different answers! encoding type: "+_encoding.GetType().Name);
+ //Debug.Assert(len == _encoding.GetBytes(chars, 0, chars.Length, _largeByteBuffer, 0), "encoding's GetByteCount & GetBytes gave different answers! encoding type: "+_encoding.GetType().Name);
_encoding.GetBytes(value, 0, value.Length, _largeByteBuffer, 0);
OutStream.Write(_largeByteBuffer, 0, len);
}
}
#if _DEBUG
totalBytes += byteLen;
- Contract.Assert (totalBytes <= len && byteLen <= _largeByteBuffer.Length, "BinaryWriter::Write(String) - More bytes encoded than expected!");
+ Debug.Assert (totalBytes <= len && byteLen <= _largeByteBuffer.Length, "BinaryWriter::Write(String) - More bytes encoded than expected!");
#endif
OutStream.Write(_largeByteBuffer, 0, byteLen);
charStart += charCount;
numLeft -= charCount;
}
#if _DEBUG
- Contract.Assert(totalBytes == len, "BinaryWriter::Write(String) - Didn't write out all the bytes!");
+ Debug.Assert(totalBytes == len, "BinaryWriter::Write(String) - Didn't write out all the bytes!");
#endif
}
}
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.IO
catch (IOException) { }
catch (UnauthorizedAccessException)
{
- Contract.Assert(false, "Ignore this assert and send a repro to Microsoft. This assert was tracking purposes only.");
+ Debug.Assert(false, "Ignore this assert and send a repro to Microsoft. This assert was tracking purposes only.");
}
return false;
}
using System.Globalization;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.IO
#endif //FEATURE_CORESYSTEM
internal DirectoryInfo(String fullPath, bool junk)
{
- Contract.Assert(PathInternal.GetRootLength(fullPath) > 0, "fullPath must be fully qualified!");
+ Debug.Assert(PathInternal.GetRootLength(fullPath) > 0, "fullPath must be fully qualified!");
// Fast path when we know a DirectoryInfo exists.
OriginalPath = Path.GetFileName(fullPath);
private static String GetDisplayName(String originalPath, String fullPath)
{
- Contract.Assert(originalPath != null);
- Contract.Assert(fullPath != null);
+ Debug.Assert(originalPath != null);
+ Debug.Assert(fullPath != null);
String displayName = "";
private static String GetDirName(String fullPath)
{
- Contract.Assert(fullPath != null);
+ Debug.Assert(fullPath != null);
String dirName = null;
if (fullPath.Length > 3)
using System.Text;
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.IO
// After normalizing, check whether path ends in directory separator.
// Otherwise, FillAttributeInfo removes it and we may return a false positive.
// GetFullPath should never return null
- Contract.Assert(path != null, "File.Exists: GetFullPath returned null");
+ Debug.Assert(path != null, "File.Exists: GetFullPath returned null");
if (path.Length > 0 && PathInternal.IsDirectorySeparator(path[path.Length - 1]))
{
return false;
catch {
// if we're already returning an error, don't throw another one.
if (!error) {
- Contract.Assert(false, "File::FillAttributeInfo - FindClose failed!");
+ Debug.Assert(false, "File::FillAttributeInfo - FindClose failed!");
__Error.WinIOError();
}
}
using System.Runtime.Serialization;
using System.Globalization;
using System.Runtime.Versioning;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.IO
#endif //FEATURE_CORESYSTEM
internal FileInfo(String fullPath, bool ignoreThis)
{
- Contract.Assert(PathInternal.GetRootLength(fullPath) > 0, "fullPath must be fully qualified!");
+ Debug.Assert(PathInternal.GetRootLength(fullPath) > 0, "fullPath must be fully qualified!");
_name = Path.GetFileName(fullPath);
OriginalPath = _name;
FullPath = fullPath;
using System.Runtime.InteropServices;
using System.Globalization;
using System.Runtime.Versioning;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Threading;
private void CommonInit()
{
- Contract.Assert(searchCriteria != null && searchData != null, "searchCriteria and searchData should be initialized");
+ Debug.Assert(searchCriteria != null && searchData != null, "searchCriteria and searchData should be initialized");
// Execute searchCriteria against the current directory
String searchPath = Path.Combine(searchData.fullPath, searchCriteria);
}
case STATE_SEARCH_NEXT_DIR:
{
- Contract.Assert(searchData.searchOption != SearchOption.TopDirectoryOnly, "should not reach this code path if searchOption == TopDirectoryOnly");
+ Debug.Assert(searchData.searchOption != SearchOption.TopDirectoryOnly, "should not reach this code path if searchOption == TopDirectoryOnly");
// Traverse directory structure. We need to get '*'
while (searchStack.Count > 0)
{
searchData = searchStack[0];
- Contract.Assert((searchData.fullPath != null), "fullpath can't be null!");
+ Debug.Assert((searchData.fullPath != null), "fullpath can't be null!");
searchStack.RemoveAt(0);
// Traverse the subdirs
}
else
{
- Contract.Assert(fullSearchString.Length > fullPathMod.Length);
+ Debug.Assert(fullSearchString.Length > fullPathMod.Length);
searchCriteria = fullSearchString.Substring(fullPathMod.Length + 1);
}
return searchCriteria;
{
bool includeFile = _includeFiles && FileSystemEnumerableHelpers.IsFile(result.FindData);
bool includeDir = _includeDirs && FileSystemEnumerableHelpers.IsDir(result.FindData);
- Contract.Assert(!(includeFile && includeDir), result.FindData.cFileName + ": current item can't be both file and dir!");
+ Debug.Assert(!(includeFile && includeDir), result.FindData.cFileName + ": current item can't be both file and dir!");
return (includeFile || includeDir);
}
{
bool includeFile = FileSystemEnumerableHelpers.IsFile(result.FindData);
bool includeDir = FileSystemEnumerableHelpers.IsDir(result.FindData);
- Contract.Assert(!(includeFile && includeDir), result.FindData.cFileName + ": current item can't be both file and dir!");
+ Debug.Assert(!(includeFile && includeDir), result.FindData.cFileName + ": current item can't be both file and dir!");
return (includeDir || includeFile);
}
}
else
{
- Contract.Assert(isFile);
+ Debug.Assert(isFile);
String name = result.FullPath;
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, name);
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Threading;
using System.Threading.Tasks;
if (n > count) n = count;
if (n < 0) n = 0;
- Contract.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1.
+ Debug.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1.
_position += n;
return n;
}
if (n <= 0)
return 0;
- Contract.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1.
+ Debug.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1.
if (n <= 8)
{
{
int n = Read(buffer, offset, count);
var t = _lastReadTask;
- Contract.Assert(t == null || t.Status == TaskStatus.RanToCompletion,
+ Debug.Assert(t == null || t.Status == TaskStatus.RanToCompletion,
"Expected that a stored last task completed successfully");
return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult<int>(n));
}
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSeekOrigin"));
}
- Contract.Assert(_position >= 0, "_position >= 0");
+ Debug.Assert(_position >= 0, "_position >= 0");
return _position;
}
EnsureWriteable();
// Origin wasn't publicly exposed above.
- Contract.Assert(MemStreamMaxLength == Int32.MaxValue); // Check parameter validation logic in this method if this fails.
+ Debug.Assert(MemStreamMaxLength == Int32.MaxValue); // Check parameter validation logic in this method if this fails.
if (value > (Int32.MaxValue - _origin)) {
throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
}
===========================================================*/
using System;
using System.Runtime.InteropServices;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.IO {
internal PinnedBufferMemoryStream(byte[] array)
{
- Contract.Assert(array != null, "Array can't be null");
+ Debug.Assert(array != null, "Array can't be null");
int len = array.Length;
// Handle 0 length byte arrays specially.
using System.Runtime.ExceptionServices;
using System.Security;
using System.Security.Permissions;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Reflection;
// As we're currently inside of it, we can get the current task
// and grab the parameters from it.
var thisTask = Task.InternalCurrent as ReadWriteTask;
- Contract.Assert(thisTask != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask");
+ Debug.Assert(thisTask != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask");
try
{
// As we're currently inside of it, we can get the current task
// and grab the parameters from it.
var thisTask = Task.InternalCurrent as ReadWriteTask;
- Contract.Assert(thisTask != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask");
+ Debug.Assert(thisTask != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask");
try
{
private void RunReadWriteTaskWhenReady(Task asyncWaiter, ReadWriteTask readWriteTask)
{
- Contract.Assert(readWriteTask != null); // Should be Contract.Requires, but CCRewrite is doing a poor job with
+ Debug.Assert(readWriteTask != null); // Should be Contract.Requires, but CCRewrite is doing a poor job with
// preconditions in async methods that await.
- Contract.Assert(asyncWaiter != null); // Ditto
+ Debug.Assert(asyncWaiter != null); // Ditto
// If the wait has already completed, run the task.
if (asyncWaiter.IsCompleted)
{
- Contract.Assert(asyncWaiter.IsRanToCompletion, "The semaphore wait should always complete successfully.");
+ Debug.Assert(asyncWaiter.IsRanToCompletion, "The semaphore wait should always complete successfully.");
RunReadWriteTask(readWriteTask);
}
else // Otherwise, wait for our turn, and then run the task.
{
asyncWaiter.ContinueWith((t, state) => {
- Contract.Assert(t.IsRanToCompletion, "The semaphore wait should always complete successfully.");
+ Debug.Assert(t.IsRanToCompletion, "The semaphore wait should always complete successfully.");
var rwt = (ReadWriteTask)state;
rwt._stream.RunReadWriteTask(rwt); // RunReadWriteTask(readWriteTask);
}, readWriteTask, default(CancellationToken), TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
private void RunReadWriteTask(ReadWriteTask readWriteTask)
{
Contract.Requires(readWriteTask != null);
- Contract.Assert(_activeReadWriteTask == null, "Expected no other readers or writers");
+ Debug.Assert(_activeReadWriteTask == null, "Expected no other readers or writers");
// Schedule the task. ScheduleAndStart must happen after the write to _activeReadWriteTask to avoid a race.
// Internally, we're able to directly call ScheduleAndStart rather than Start, avoiding
private void FinishTrackingAsyncOperation()
{
_activeReadWriteTask = null;
- Contract.Assert(_asyncActiveSemaphore != null, "Must have been initialized in order to get here.");
+ Debug.Assert(_asyncActiveSemaphore != null, "Must have been initialized in order to get here.");
_asyncActiveSemaphore.Release();
}
try
{
writeTask.GetAwaiter().GetResult(); // block until completion, then propagate any exceptions
- Contract.Assert(writeTask.Status == TaskStatus.RanToCompletion);
+ Debug.Assert(writeTask.Status == TaskStatus.RanToCompletion);
}
finally
{
using System.Text;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
+using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Security.Permissions;
// Trims n bytes from the front of the buffer.
private void CompressBuffer(int n)
{
- Contract.Assert(byteLen >= n, "CompressBuffer was called with a number of bytes greater than the current buffer length. Are two threads using this StreamReader at the same time?");
+ Debug.Assert(byteLen >= n, "CompressBuffer was called with a number of bytes greater than the current buffer length. Are two threads using this StreamReader at the same time?");
Buffer.InternalBlockCopy(byteBuffer, n, byteBuffer, 0, byteLen - n);
byteLen -= n;
}
if (!_checkPreamble)
return _checkPreamble;
- Contract.Assert(bytePos <= _preamble.Length, "_compressPreamble was called with the current bytePos greater than the preamble buffer length. Are two threads using this StreamReader at the same time?");
+ Debug.Assert(bytePos <= _preamble.Length, "_compressPreamble was called with the current bytePos greater than the preamble buffer length. Are two threads using this StreamReader at the same time?");
int len = (byteLen >= (_preamble.Length))? (_preamble.Length - bytePos) : (byteLen - bytePos);
for(int i=0; i<len; i++, bytePos++) {
}
}
- Contract.Assert(bytePos <= _preamble.Length, "possible bug in _compressPreamble. Are two threads using this StreamReader at the same time?");
+ Debug.Assert(bytePos <= _preamble.Length, "possible bug in _compressPreamble. Are two threads using this StreamReader at the same time?");
if (_checkPreamble) {
if (bytePos == _preamble.Length) {
byteLen = 0;
do {
if (_checkPreamble) {
- Contract.Assert(bytePos <= _preamble.Length, "possible bug in _compressPreamble. Are two threads using this StreamReader at the same time?");
+ Debug.Assert(bytePos <= _preamble.Length, "possible bug in _compressPreamble. Are two threads using this StreamReader at the same time?");
int len = stream.Read(byteBuffer, bytePos, byteBuffer.Length - bytePos);
- Contract.Assert(len >= 0, "Stream.Read returned a negative number! This is a bug in your stream class.");
+ Debug.Assert(len >= 0, "Stream.Read returned a negative number! This is a bug in your stream class.");
if (len == 0) {
// EOF but we might have buffered bytes from previous
byteLen += len;
}
else {
- Contract.Assert(bytePos == 0, "bytePos can be non zero only when we are trying to _checkPreamble. Are two threads using this StreamReader at the same time?");
+ Debug.Assert(bytePos == 0, "bytePos can be non zero only when we are trying to _checkPreamble. Are two threads using this StreamReader at the same time?");
byteLen = stream.Read(byteBuffer, 0, byteBuffer.Length);
- Contract.Assert(byteLen >= 0, "Stream.Read returned a negative number! This is a bug in your stream class.");
+ Debug.Assert(byteLen >= 0, "Stream.Read returned a negative number! This is a bug in your stream class.");
if (byteLen == 0) // We're at EOF
return charLen;
readToUserBuffer = desiredChars >= _maxCharsPerBuffer;
do {
- Contract.Assert(charsRead == 0);
+ Debug.Assert(charsRead == 0);
if (_checkPreamble) {
- Contract.Assert(bytePos <= _preamble.Length, "possible bug in _compressPreamble. Are two threads using this StreamReader at the same time?");
+ Debug.Assert(bytePos <= _preamble.Length, "possible bug in _compressPreamble. Are two threads using this StreamReader at the same time?");
int len = stream.Read(byteBuffer, bytePos, byteBuffer.Length - bytePos);
- Contract.Assert(len >= 0, "Stream.Read returned a negative number! This is a bug in your stream class.");
+ Debug.Assert(len >= 0, "Stream.Read returned a negative number! This is a bug in your stream class.");
if (len == 0) {
// EOF but we might have buffered bytes from previous
byteLen += len;
}
else {
- Contract.Assert(bytePos == 0, "bytePos can be non zero only when we are trying to _checkPreamble. Are two threads using this StreamReader at the same time?");
+ Debug.Assert(bytePos == 0, "bytePos can be non zero only when we are trying to _checkPreamble. Are two threads using this StreamReader at the same time?");
byteLen = stream.Read(byteBuffer, 0, byteBuffer.Length);
- Contract.Assert(byteLen >= 0, "Stream.Read returned a negative number! This is a bug in your stream class.");
+ Debug.Assert(byteLen >= 0, "Stream.Read returned a negative number! This is a bug in your stream class.");
if (byteLen == 0) // EOF
break;
// We break out of the loop if the stream is blocked (EOF is reached).
do
{
- Contract.Assert(n == 0);
+ Debug.Assert(n == 0);
if (CheckPreamble_Prop)
{
- Contract.Assert(BytePos_Prop <= Preamble_Prop.Length, "possible bug in _compressPreamble. Are two threads using this StreamReader at the same time?");
+ Debug.Assert(BytePos_Prop <= Preamble_Prop.Length, "possible bug in _compressPreamble. Are two threads using this StreamReader at the same time?");
int tmpBytePos = BytePos_Prop;
int len = await tmpStream.ReadAsync(tmpByteBuffer, tmpBytePos, tmpByteBuffer.Length - tmpBytePos).ConfigureAwait(false);
- Contract.Assert(len >= 0, "Stream.Read returned a negative number! This is a bug in your stream class.");
+ Debug.Assert(len >= 0, "Stream.Read returned a negative number! This is a bug in your stream class.");
if (len == 0)
{
}
// How can part of the preamble yield any chars?
- Contract.Assert(n == 0);
+ Debug.Assert(n == 0);
IsBlocked_Prop = true;
break;
}
else
{
- Contract.Assert(BytePos_Prop == 0, "_bytePos can be non zero only when we are trying to _checkPreamble. Are two threads using this StreamReader at the same time?");
+ Debug.Assert(BytePos_Prop == 0, "_bytePos can be non zero only when we are trying to _checkPreamble. Are two threads using this StreamReader at the same time?");
ByteLen_Prop = await tmpStream.ReadAsync(tmpByteBuffer, 0, tmpByteBuffer.Length).ConfigureAwait(false);
- Contract.Assert(ByteLen_Prop >= 0, "Stream.Read returned a negative number! This is a bug in your stream class.");
+ Debug.Assert(ByteLen_Prop >= 0, "Stream.Read returned a negative number! This is a bug in your stream class.");
if (ByteLen_Prop == 0) // EOF
{
readToUserBuffer = count >= MaxCharsPerBuffer_Prop;
}
- Contract.Assert(n == 0);
+ Debug.Assert(n == 0);
CharPos_Prop = 0;
if (readToUserBuffer)
n += Decoder_Prop.GetChars(tmpByteBuffer, 0, ByteLen_Prop, buffer, index + charsRead);
// Why did the bytes yield no chars?
- Contract.Assert(n > 0);
+ Debug.Assert(n > 0);
CharLen_Prop = 0; // StreamReader's buffer is empty.
}
n = Decoder_Prop.GetChars(tmpByteBuffer, 0, ByteLen_Prop, CharBuffer_Prop, 0);
// Why did the bytes yield no chars?
- Contract.Assert(n > 0);
+ Debug.Assert(n > 0);
CharLen_Prop += n; // Number of chars in StreamReader's buffer.
}
ByteLen_Prop = 0;
do {
if (CheckPreamble_Prop) {
- Contract.Assert(BytePos_Prop <= Preamble_Prop.Length, "possible bug in _compressPreamble. Are two threads using this StreamReader at the same time?");
+ Debug.Assert(BytePos_Prop <= Preamble_Prop.Length, "possible bug in _compressPreamble. Are two threads using this StreamReader at the same time?");
int tmpBytePos = BytePos_Prop;
int len = await tmpStream.ReadAsync(tmpByteBuffer, tmpBytePos, tmpByteBuffer.Length - tmpBytePos).ConfigureAwait(false);
- Contract.Assert(len >= 0, "Stream.Read returned a negative number! This is a bug in your stream class.");
+ Debug.Assert(len >= 0, "Stream.Read returned a negative number! This is a bug in your stream class.");
if (len == 0) {
// EOF but we might have buffered bytes from previous
ByteLen_Prop += len;
}
else {
- Contract.Assert(BytePos_Prop == 0, "_bytePos can be non zero only when we are trying to _checkPreamble. Are two threads using this StreamReader at the same time?");
+ Debug.Assert(BytePos_Prop == 0, "_bytePos can be non zero only when we are trying to _checkPreamble. Are two threads using this StreamReader at the same time?");
ByteLen_Prop = await tmpStream.ReadAsync(tmpByteBuffer, 0, tmpByteBuffer.Length).ConfigureAwait(false);
- Contract.Assert(ByteLen_Prop >= 0, "Stream.Read returned a negative number! Bug in stream class.");
+ Debug.Assert(ByteLen_Prop >= 0, "Stream.Read returned a negative number! Bug in stream class.");
if (ByteLen_Prop == 0) // We're at EOF
return CharLen_Prop;
using System.Runtime.Versioning;
using System.Security.Permissions;
using System.Runtime.Serialization;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
if (charPos == charLen) Flush(false, false);
int n = charLen - charPos;
if (n > count) n = count;
- Contract.Assert(n > 0, "StreamWriter::Write(char[]) isn't making progress! This is most likely a race condition in user code.");
+ Debug.Assert(n > 0, "StreamWriter::Write(char[]) isn't making progress! This is most likely a race condition in user code.");
Buffer.InternalBlockCopy(buffer, index * sizeof(char), charBuffer, charPos * sizeof(char), n * sizeof(char));
charPos += n;
index += n;
if (charPos == charLen) Flush(false, false);
int n = charLen - charPos;
if (n > count) n = count;
- Contract.Assert(n > 0, "StreamWriter::Write(char[], int, int) isn't making progress! This is most likely a race condition in user code.");
+ Debug.Assert(n > 0, "StreamWriter::Write(char[], int, int) isn't making progress! This is most likely a race condition in user code.");
Buffer.InternalBlockCopy(buffer, index * sizeof(char), charBuffer, charPos * sizeof(char), n * sizeof(char));
charPos += n;
index += n;
if (charPos == charLen) Flush(false, false);
int n = charLen - charPos;
if (n > count) n = count;
- Contract.Assert(n > 0, "StreamWriter::Write(String) isn't making progress! This is most likely a race condition in user code.");
+ Debug.Assert(n > 0, "StreamWriter::Write(String) isn't making progress! This is most likely a race condition in user code.");
value.CopyTo(index, charBuffer, charPos, n);
charPos += n;
index += n;
{
if (charPos == charLen) {
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
- Contract.Assert(_this.charPos == 0);
+ Debug.Assert(_this.charPos == 0);
charPos = 0;
}
{
if (charPos == charLen) {
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
- Contract.Assert(_this.charPos == 0);
+ Debug.Assert(_this.charPos == 0);
charPos = 0;
}
if (autoFlush) {
await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false);
- Contract.Assert(_this.charPos == 0);
+ Debug.Assert(_this.charPos == 0);
charPos = 0;
}
{
if (charPos == charLen) {
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
- Contract.Assert(_this.charPos == 0);
+ Debug.Assert(_this.charPos == 0);
charPos = 0;
}
if (n > count)
n = count;
- Contract.Assert(n > 0, "StreamWriter::Write(String) isn't making progress! This is most likely a race condition in user code.");
+ Debug.Assert(n > 0, "StreamWriter::Write(String) isn't making progress! This is most likely a race condition in user code.");
value.CopyTo(index, charBuffer, charPos, n);
{
if (charPos == charLen) {
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
- Contract.Assert(_this.charPos == 0);
+ Debug.Assert(_this.charPos == 0);
charPos = 0;
}
if (autoFlush) {
await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false);
- Contract.Assert(_this.charPos == 0);
+ Debug.Assert(_this.charPos == 0);
charPos = 0;
}
{
if (charPos == charLen) {
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
- Contract.Assert(_this.charPos == 0);
+ Debug.Assert(_this.charPos == 0);
charPos = 0;
}
int n = charLen - charPos;
if (n > count) n = count;
- Contract.Assert(n > 0, "StreamWriter::Write(char[], int, int) isn't making progress! This is most likely a race condition in user code.");
+ Debug.Assert(n > 0, "StreamWriter::Write(char[], int, int) isn't making progress! This is most likely a race condition in user code.");
Buffer.InternalBlockCopy(buffer, index * sizeof(char), charBuffer, charPos * sizeof(char), n * sizeof(char));
{
if (charPos == charLen) {
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
- Contract.Assert(_this.charPos == 0);
+ Debug.Assert(_this.charPos == 0);
charPos = 0;
}
if (autoFlush) {
await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false);
- Contract.Assert(_this.charPos == 0);
+ Debug.Assert(_this.charPos == 0);
charPos = 0;
}
using System.Runtime.Versioning;
using System.Security.Permissions;
using Microsoft.Win32.SafeHandles;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.IO {
}
private byte InternalReadByte(Int64 position) {
- Contract.Assert(CanRead, "UMA not readable");
- Contract.Assert(position >= 0, "position less than 0");
- Contract.Assert(position <= _capacity - sizeof(byte), "position is greater than capacity - sizeof(byte)");
+ Debug.Assert(CanRead, "UMA not readable");
+ Debug.Assert(position >= 0, "position less than 0");
+ Debug.Assert(position <= _capacity - sizeof(byte), "position is greater than capacity - sizeof(byte)");
byte result;
unsafe {
}
private void InternalWrite(Int64 position, byte value) {
- Contract.Assert(CanWrite, "UMA not writable");
- Contract.Assert(position >= 0, "position less than 0");
- Contract.Assert(position <= _capacity - sizeof(byte), "position is greater than capacity - sizeof(byte)");
+ Debug.Assert(CanWrite, "UMA not writable");
+ Debug.Assert(position >= 0, "position less than 0");
+ Debug.Assert(position <= _capacity - sizeof(byte), "position is greater than capacity - sizeof(byte)");
unsafe {
byte* pointer = null;
using System.Security;
using System.Security.Permissions;
using System.Threading;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Threading.Tasks;
int nInt = (int) n; // Safe because n <= count, which is an Int32
if (nInt < 0)
return 0; // _position could be beyond EOF
- Contract.Assert(pos + nInt >= 0, "_position + n >= 0"); // len is less than 2^63 -1.
+ Debug.Assert(pos + nInt >= 0, "_position + n >= 0"); // len is less than 2^63 -1.
unsafe
{
} catch (Exception ex) {
- Contract.Assert(! (ex is OperationCanceledException));
+ Debug.Assert(! (ex is OperationCanceledException));
return Task.FromException<Int32>(ex);
}
}
}
long finalPos = Interlocked.Read(ref _position);
- Contract.Assert(finalPos >= 0, "_position >= 0");
+ Debug.Assert(finalPos >= 0, "_position >= 0");
return finalPos;
}
} catch (Exception ex) {
- Contract.Assert(! (ex is OperationCanceledException));
+ Debug.Assert(! (ex is OperationCanceledException));
return Task.FromException<Int32>(ex);
}
}
// 2- Flag to m_threadSafeObj if ExecutionAndPublication mode and the value is known to be initialized
static readonly Func<T> ALREADY_INVOKED_SENTINEL = delegate
{
- Contract.Assert(false, "ALREADY_INVOKED_SENTINEL should never be invoked.");
+ Debug.Assert(false, "ALREADY_INVOKED_SENTINEL should never be invoked.");
return default(T);
};
}
LazyInternalExceptionHolder exc = m_boxed as LazyInternalExceptionHolder;
- Contract.Assert(exc != null);
+ Debug.Assert(exc != null);
exc.m_edi.Throw();
}
if (threadSafeObj != (object)ALREADY_INVOKED_SENTINEL)
Monitor.Enter(threadSafeObj, ref lockTaken);
else
- Contract.Assert(m_boxed != null);
+ Debug.Assert(m_boxed != null);
if (m_boxed == null)
{
if (boxed == null) // it is not Boxed, so it is a LazyInternalExceptionHolder
{
LazyInternalExceptionHolder exHolder = m_boxed as LazyInternalExceptionHolder;
- Contract.Assert(exHolder != null);
+ Debug.Assert(exHolder != null);
exHolder.m_edi.Throw();
}
}
Monitor.Exit(threadSafeObj);
}
}
- Contract.Assert(boxed != null);
+ Debug.Assert(boxed != null);
return boxed.m_value;
}
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Reflection.Emit;
// Since this is a MulticastDelegate and we know
// the types are the same, obj should also be a
// MulticastDelegate
- Contract.Assert(obj is MulticastDelegate, "Shouldn't have failed here since we already checked the types are the same!");
+ Debug.Assert(obj is MulticastDelegate, "Shouldn't have failed here since we already checked the types are the same!");
var d = JitHelpers.UnsafeCast<MulticastDelegate>(obj);
if (_invocationCount != (IntPtr)0)
}
else
{
- Contract.Assert((_invocationList as Object[]) != null, "empty invocation list on multicast delegate");
+ Debug.Assert((_invocationList as Object[]) != null, "empty invocation list on multicast delegate");
return InvocationListEquals(d);
}
}
// Recursive function which will check for equality of the invocation list.
private bool InvocationListEquals(MulticastDelegate d)
{
- Contract.Assert(d != null && (_invocationList as Object[]) != null, "bogus delegate in multicast list comparison");
+ Debug.Assert(d != null && (_invocationList as Object[]) != null, "bogus delegate in multicast list comparison");
Object[] invocationList = _invocationList as Object[];
if (d._invocationCount != _invocationCount)
return false;
{
if (_invocationCount != (IntPtr)0)
{
- Contract.Assert(!IsUnmanagedFunctionPtr(), "dynamic method and unmanaged fntptr delegate combined");
+ Debug.Assert(!IsUnmanagedFunctionPtr(), "dynamic method and unmanaged fntptr delegate combined");
// must be a secure/wrapper one, unwrap and save
MulticastDelegate d = (MulticastDelegate)_invocationList;
d._methodBase = dynamicMethod;
using System.Runtime.Versioning;
using System.Security;
using System.Text;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
// The Number class implements methods for formatting and parsing
return false;
}
Char* p = number.digits;
- Contract.Assert(p != null, "");
+ Debug.Assert(p != null, "");
UInt32 n = 0;
while (--i >= 0) {
newN += (UInt32)((*p - 'A') + 10);
}
else {
- Contract.Assert(*p >= 'a' && *p <= 'f', "");
+ Debug.Assert(*p >= 'a' && *p <= 'f', "");
newN += (UInt32)((*p - 'a') + 10);
}
}
return false;
}
Char* p = number.digits;
- Contract.Assert(p != null, "");
+ Debug.Assert(p != null, "");
UInt64 n = 0;
while (--i >= 0) {
newN += (UInt64)((*p - 'A') + 10);
}
else {
- Contract.Assert(*p >= 'a' && *p <= 'f', "");
+ Debug.Assert(*p >= 'a' && *p <= 'f', "");
newN += (UInt64)((*p - 'a') + 10);
}
}
return false;
}
char * p = number.digits;
- Contract.Assert(p != null, "");
+ Debug.Assert(p != null, "");
Int32 n = 0;
while (--i >= 0) {
if ((UInt32)n > (0x7FFFFFFF / 10)) {
return false;
}
char* p = number.digits;
- Contract.Assert(p != null, "");
+ Debug.Assert(p != null, "");
Int64 n = 0;
while (--i >= 0) {
if ((UInt64)n > (0x7FFFFFFFFFFFFFFF / 10)) {
return false;
}
char* p = number.digits;
- Contract.Assert(p != null, "");
+ Debug.Assert(p != null, "");
UInt32 n = 0;
while (--i >= 0) {
if (n > (0xFFFFFFFF / 10)) {
return false;
}
char * p = number.digits;
- Contract.Assert(p != null, "");
+ Debug.Assert(p != null, "");
UInt64 n = 0;
while (--i >= 0) {
if (n > (0xFFFFFFFFFFFFFFFF / 10)) {
}
}
private unsafe static char * MatchChars(char* p, char* str) {
- Contract.Assert(p != null && str != null, "");
+ Debug.Assert(p != null && str != null, "");
if (*str == '\0') {
return null;
throw new ArgumentNullException(nameof(String));
}
Contract.EndContractBlock();
- Contract.Assert(info != null, "");
+ Debug.Assert(info != null, "");
fixed (char* stringPointer = str) {
char * p = stringPointer;
if (!ParseNumber(ref p, options, ref number, null, info , parseDecimal)
if (str == null) {
return false;
}
- Contract.Assert(numfmt != null, "");
+ Debug.Assert(numfmt != null, "");
fixed (char* stringPointer = str) {
char * p = stringPointer;
// sync ctx reference identity issues where the sync ctx for one thread could be Current on another.
// If there is no current context, we use a default instance targeting the ThreadPool.
m_synchronizationContext = SynchronizationContext.CurrentNoFlow ?? ProgressStatics.DefaultContext;
- Contract.Assert(m_synchronizationContext != null);
+ Debug.Assert(m_synchronizationContext != null);
m_invokeHandlers = new SendOrPostCallback(InvokeHandlers);
}
{
using System;
using System.Collections.Generic;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
internal static class Associates
if (MetadataToken.IsNullToken(tkMethod))
return null;
- Contract.Assert(declaredType != null);
- Contract.Assert(reflectedType != null);
+ Debug.Assert(declaredType != null);
+ Debug.Assert(reflectedType != null);
bool isInherited = declaredType != reflectedType;
}
RuntimeMethodHandleInternal associateMethodHandle = ModuleHandle.ResolveMethodHandleInternalCore(RuntimeTypeHandle.GetModule(declaredType), tkMethod, genericArgumentHandles, genericArgumentCount, null, 0);
- Contract.Assert(!associateMethodHandle.IsNullHandle(), "Failed to resolve associateRecord methodDef token");
+ Debug.Assert(!associateMethodHandle.IsNullHandle(), "Failed to resolve associateRecord methodDef token");
if (isInherited)
{
#region Internal Static Members
internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeType target)
{
- Contract.Assert(target != null);
+ Debug.Assert(target != null);
IList<CustomAttributeData> cad = GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken);
internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeFieldInfo target)
{
- Contract.Assert(target != null);
+ Debug.Assert(target != null);
IList<CustomAttributeData> cad = GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken);
internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeMethodInfo target)
{
- Contract.Assert(target != null);
+ Debug.Assert(target != null);
IList<CustomAttributeData> cad = GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken);
internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeConstructorInfo target)
{
- Contract.Assert(target != null);
+ Debug.Assert(target != null);
return GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken);
}
internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeEventInfo target)
{
- Contract.Assert(target != null);
+ Debug.Assert(target != null);
return GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken);
}
internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimePropertyInfo target)
{
- Contract.Assert(target != null);
+ Debug.Assert(target != null);
return GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken);
}
internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeModule target)
{
- Contract.Assert(target != null);
+ Debug.Assert(target != null);
if (target.IsResource())
return new List<CustomAttributeData>();
internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeAssembly target)
{
- Contract.Assert(target != null);
+ Debug.Assert(target != null);
IList<CustomAttributeData> cad = GetCustomAttributes((RuntimeModule)target.ManifestModule, RuntimeAssembly.GetToken(target.GetNativeHandle()));
internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeParameterInfo target)
{
- Contract.Assert(target != null);
+ Debug.Assert(target != null);
IList<CustomAttributeData> cad = GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken);
private static object CanonicalizeValue(object value)
{
- Contract.Assert(value != null);
+ Debug.Assert(value != null);
if (value.GetType().IsEnum)
{
throw new ArgumentNullException(nameof(customAttributeModule));
Contract.EndContractBlock();
- Contract.Assert(customAttributeCtorParameters != null);
- Contract.Assert(customAttributeNamedParameters != null);
+ Debug.Assert(customAttributeCtorParameters != null);
+ Debug.Assert(customAttributeNamedParameters != null);
if (customAttributeCtorParameters.Length != 0 || customAttributeNamedParameters.Length != 0)
{
else
{
type = type.DeclaringType as RuntimeType;
- Contract.Assert(type != null);
+ Debug.Assert(type != null);
}
}
if (attributeFilterType != null)
{
- Contract.Assert(attributeCtorToken == 0);
+ Debug.Assert(attributeCtorToken == 0);
MetadataImport scope = decoratedModule.MetadataImport;
RuntimeType attributeType;
}
else
{
- Contract.Assert(attributeFilterType == null);
- Contract.Assert(!MetadataToken.IsNullToken(attributeCtorToken));
+ Debug.Assert(attributeFilterType == null);
+ Debug.Assert(!MetadataToken.IsNullToken(attributeCtorToken));
for (int i = 0; i < car.Length; i++)
{
else
{
// We need to relax this when we add support for other types of decorated tokens.
- Contract.Assert(decoratedToken.IsModule || decoratedToken.IsAssembly,
+ Debug.Assert(decoratedToken.IsModule || decoratedToken.IsAssembly,
"The decoratedToken must be either an assembly, a module, a type, or a member.");
}
{
// If any of these are invariants are no longer true will have to
// re-architect the PCA product logic and test cases -- you've been warned!
- Contract.Assert(pca.BaseType == (RuntimeType)typeof(Attribute), "Pseudo CA Error");
+ Debug.Assert(pca.BaseType == (RuntimeType)typeof(Attribute), "Pseudo CA Error");
AttributeUsageAttribute usage = CustomAttribute.GetAttributeUsage(pca);
- Contract.Assert(usage.Inherited == false, "Pseudo CA Error");
+ Debug.Assert(usage.Inherited == false, "Pseudo CA Error");
//AllowMultiple is true for TypeForwardedToAttribute
- //Contract.Assert(usage.AllowMultiple == false, "Pseudo CA Error");
+ //Debug.Assert(usage.AllowMultiple == false, "Pseudo CA Error");
}
#endregion
internal ModuleBuilder GetModuleBuilder(InternalModuleBuilder module)
{
Contract.Requires(module != null);
- Contract.Assert(this.InternalAssembly == module.Assembly);
+ Debug.Assert(this.InternalAssembly == module.Assembly);
lock(SyncRoot)
{
BCLDebug.Log("DYNIL", "## DYNIL LOGGING: AssemblyBuilder.DefineDynamicModule( " + name + " )");
- Contract.Assert(m_assemblyData != null, "m_assemblyData is null in DefineDynamicModuleInternal");
+ Debug.Assert(m_assemblyData != null, "m_assemblyData is null in DefineDynamicModuleInternal");
ModuleBuilder dynModule;
ISymbolWriter writer = null;
using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Globalization;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[HostProtection(MayLeakOnAbort = true)]
writer.Write((byte)CustomAttributeEncoding.Double);
break;
default:
- Contract.Assert(false, "Invalid primitive type");
+ Debug.Assert(false, "Invalid primitive type");
break;
}
}
writer.Write((ulong)value);
break;
default:
- Contract.Assert(false, "Invalid enum base type");
+ Debug.Assert(false, "Invalid enum base type");
break;
}
}
writer.Write((double)value);
break;
default:
- Contract.Assert(false, "Invalid primitive type");
+ Debug.Assert(false, "Invalid primitive type");
break;
}
}
using System.Collections.Generic;
using System.Security.Permissions;
using System.Threading;
+ using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Security;
// SignatureHelper.
if (opcode.StackBehaviourPop == StackBehaviour.Varpop)
{
- Contract.Assert(opcode.Equals(OpCodes.Calli),
+ Debug.Assert(opcode.Equals(OpCodes.Calli),
"Unexpected opcode encountered for StackBehaviour VarPop.");
// Pop the arguments..
stackchange -= signature.ArgumentCount;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
if (transparentMethod)
{
- Contract.Assert(owner == null && m == null, "owner and m cannot be set for transparent methods");
+ Debug.Assert(owner == null && m == null, "owner and m cannot be set for transparent methods");
m_module = GetDynamicMethodsModule();
if (skipVisibility)
{
}
else
{
- Contract.Assert(m != null || owner != null, "PerformSecurityCheck should ensure that either m or owner is set");
- Contract.Assert(m == null || !m.Equals(s_anonymouslyHostedDynamicMethodsModule), "The user cannot explicitly use this assembly");
- Contract.Assert(m == null || owner == null, "m and owner cannot both be set");
+ Debug.Assert(m != null || owner != null, "PerformSecurityCheck should ensure that either m or owner is set");
+ Debug.Assert(m == null || !m.Equals(s_anonymouslyHostedDynamicMethodsModule), "The user cannot explicitly use this assembly");
+ Debug.Assert(m == null || owner == null, "m and owner cannot both be set");
if (m != null)
m_module = m.ModuleHandle.GetRuntimeModule(); // this returns the underlying module for all RuntimeModule and ModuleBuilder objects.
using System.Reflection;
using System.Security.Permissions;
using System.Globalization;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[ClassInterface(ClassInterfaceType.None)]
{
if (m_RelocFixupCount == 0)
{
- Contract.Assert(m_RelocFixupList == null);
+ Debug.Assert(m_RelocFixupList == null);
return null;
}
// SignatureHelper.
if (opcode.StackBehaviourPop == StackBehaviour.Varpop)
{
- Contract.Assert(opcode.Equals(OpCodes.Calli),
+ Debug.Assert(opcode.Equals(OpCodes.Calli),
"Unexpected opcode encountered for StackBehaviour VarPop.");
// Pop the arguments..
stackchange -= signature.ArgumentCount;
if (opcode.StackBehaviourPush == StackBehaviour.Varpush)
{
// Instruction must be one of call or callvirt.
- Contract.Assert(opcode.Equals(OpCodes.Call) ||
+ Debug.Assert(opcode.Equals(OpCodes.Call) ||
opcode.Equals(OpCodes.Callvirt),
"Unexpected opcode encountered for StackBehaviour of VarPush.");
stackchange++;
if (opcode.StackBehaviourPop == StackBehaviour.Varpop)
{
// Instruction must be one of call, callvirt or newobj.
- Contract.Assert(opcode.Equals(OpCodes.Call) ||
+ Debug.Assert(opcode.Equals(OpCodes.Call) ||
opcode.Equals(OpCodes.Callvirt) ||
opcode.Equals(OpCodes.Newobj),
"Unexpected opcode encountered for StackBehaviour of VarPop.");
m_catchAddr[m_currentCatch] = -1;
if (m_currentCatch > 0)
{
- Contract.Assert(m_catchEndAddr[m_currentCatch-1] == -1,"m_catchEndAddr[m_currentCatch-1] == -1");
+ Debug.Assert(m_catchEndAddr[m_currentCatch-1] == -1,"m_catchEndAddr[m_currentCatch-1] == -1");
m_catchEndAddr[m_currentCatch-1] = catchorfilterAddr;
}
}
{
if (m_type[m_currentCatch] != Filter)
{
- Contract.Assert(m_catchEndAddr[m_currentCatch-1] == -1,"m_catchEndAddr[m_currentCatch-1] == -1");
+ Debug.Assert(m_catchEndAddr[m_currentCatch-1] == -1,"m_catchEndAddr[m_currentCatch-1] == -1");
m_catchEndAddr[m_currentCatch-1] = catchEndAddr;
}
}
}
internal void Done(int endAddr) {
- Contract.Assert(m_currentCatch > 0,"m_currentCatch > 0");
- Contract.Assert(m_catchAddr[m_currentCatch-1] > 0,"m_catchAddr[m_currentCatch-1] > 0");
- Contract.Assert(m_catchEndAddr[m_currentCatch-1] == -1,"m_catchEndAddr[m_currentCatch-1] == -1");
+ Debug.Assert(m_currentCatch > 0,"m_currentCatch > 0");
+ Debug.Assert(m_catchAddr[m_currentCatch-1] > 0,"m_catchAddr[m_currentCatch-1] > 0");
+ Debug.Assert(m_catchEndAddr[m_currentCatch-1] == -1,"m_catchEndAddr[m_currentCatch-1] == -1");
m_catchEndAddr[m_currentCatch-1] = endAddr;
m_currentState = State_Done;
}
// not having a nesting relation.
internal bool IsInner(__ExceptionInfo exc) {
Contract.Requires(exc != null);
- Contract.Assert(m_currentCatch > 0,"m_currentCatch > 0");
- Contract.Assert(exc.m_currentCatch > 0,"exc.m_currentCatch > 0");
+ Debug.Assert(m_currentCatch > 0,"m_currentCatch > 0");
+ Debug.Assert(exc.m_currentCatch > 0,"exc.m_currentCatch > 0");
int exclast = exc.m_currentCatch - 1;
int last = m_currentCatch - 1;
return true;
else if (exc.m_catchEndAddr[exclast] == m_catchEndAddr[last])
{
- Contract.Assert(exc.GetEndAddress() != GetEndAddress(),
+ Debug.Assert(exc.GetEndAddress() != GetEndAddress(),
"exc.GetEndAddress() != GetEndAddress()");
if (exc.GetEndAddress() > GetEndAddress())
return true;
// make sure that arrays are large enough to hold addition info
i = FindDocument(document);
- Contract.Assert(i < m_DocumentCount, "Bad document look up!");
+ Debug.Assert(i < m_DocumentCount, "Bad document look up!");
m_Documents[i].AddLineNumberInfo(document, iOffset, iStartLine, iStartColumn, iEndLine, iEndColumn);
}
int iEndLine,
int iEndColumn)
{
- Contract.Assert(document == m_document, "Bad document look up!");
+ Debug.Assert(document == m_document, "Bad document look up!");
// make sure that arrays are large enough to hold addition info
EnsureCapacity();
using System.Collections.Generic;
using System.Security.Permissions;
using System.Runtime.InteropServices;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[HostProtection(MayLeakOnAbort = true)]
}
else
{
- Contract.Assert(false, "We should never get here!");
+ Debug.Assert(false, "We should never get here!");
return null;
}
}
m_containingType.m_lastTokenizedMethod = i;
}
- Contract.Assert(currentMethod == this, "We should have found this method in m_containingType.m_listMethods");
- Contract.Assert(currentToken.Token != 0, "The token should not be 0");
+ Debug.Assert(currentMethod == this, "We should have found this method in m_containingType.m_listMethods");
+ Debug.Assert(currentToken.Token != 0, "The token should not be 0");
return currentToken;
}
private MethodToken GetTokenNoLock()
{
- Contract.Assert(m_tkMethod.Token == 0, "m_tkMethod should not have been initialized");
+ Debug.Assert(m_tkMethod.Token == 0, "m_tkMethod should not have been initialized");
int sigLength;
byte[] sigBytes = GetMethodSignature().InternalGetSignature(out sigLength);
internal ExceptionHandler(int tryStartOffset, int tryEndOffset, int filterOffset, int handlerStartOffset, int handlerEndOffset,
int kind, int exceptionTypeToken)
{
- Contract.Assert(tryStartOffset >= 0);
- Contract.Assert(tryEndOffset >= 0);
- Contract.Assert(filterOffset >= 0);
- Contract.Assert(handlerStartOffset >= 0);
- Contract.Assert(handlerEndOffset >= 0);
- Contract.Assert(IsValidKind((ExceptionHandlingClauseOptions)kind));
- Contract.Assert(kind != (int)ExceptionHandlingClauseOptions.Clause || (exceptionTypeToken & 0x00FFFFFF) != 0);
+ Debug.Assert(tryStartOffset >= 0);
+ Debug.Assert(tryEndOffset >= 0);
+ Debug.Assert(filterOffset >= 0);
+ Debug.Assert(handlerStartOffset >= 0);
+ Debug.Assert(handlerEndOffset >= 0);
+ Debug.Assert(IsValidKind((ExceptionHandlingClauseOptions)kind));
+ Debug.Assert(kind != (int)ExceptionHandlingClauseOptions.Clause || (exceptionTypeToken & 0x00FFFFFF) != 0);
m_tryStartOffset = tryStartOffset;
m_tryEndOffset = tryEndOffset;
using System.Diagnostics.SymbolStore;
using System.Globalization;
using System.Reflection;
- using System.Diagnostics;
using System.IO;
using System.Resources;
using System.Security;
using System.Threading;
using System.Runtime.Versioning;
using System.Runtime.CompilerServices;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
internal sealed class InternalModuleBuilder : RuntimeModule
private int GetMemberRefOfMethodInfo(int tr, RuntimeMethodInfo method)
{
- Contract.Assert(method != null);
+ Debug.Assert(method != null);
#if FEATURE_APPX
if (ContainingAssemblyBuilder.ProfileAPICheck)
private int GetMemberRefOfMethodInfo(int tr, RuntimeConstructorInfo method)
{
- Contract.Assert(method != null);
+ Debug.Assert(method != null);
#if FEATURE_APPX
if (ContainingAssemblyBuilder.ProfileAPICheck)
private int GetMemberRefOfFieldInfo(int tkType, RuntimeTypeHandle declaringType, RuntimeFieldInfo runtimeField)
{
- Contract.Assert(runtimeField != null);
+ Debug.Assert(runtimeField != null);
#if FEATURE_APPX
if (ContainingAssemblyBuilder.ProfileAPICheck)
typeName = UnmangleTypeName(typeName);
}
- Contract.Assert(!type.IsByRef, "Must not be ByRef.");
- Contract.Assert(!type.IsGenericType || type.IsGenericTypeDefinition, "Must not have generic arguments.");
+ Debug.Assert(!type.IsByRef, "Must not be ByRef.");
+ Debug.Assert(!type.IsGenericType || type.IsGenericTypeDefinition, "Must not have generic arguments.");
#if FEATURE_APPX
if (ContainingAssemblyBuilder.ProfileAPICheck)
}
else
{
- Contract.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo);
+ Debug.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo);
if (method.IsGenericMethod)
{
- Contract.Assert(masmi != null);
+ Debug.Assert(masmi != null);
methDef = masmi.GetGenericMethodDefinition();
methDef = methDef.Module.ResolveMethod(
EnumBuilder enumBuilder = DefineEnumNoLock(name, visibility, underlyingType);
// This enum is not generic, nested, and cannot have any element type.
- Contract.Assert(name == enumBuilder.FullName);
+ Debug.Assert(name == enumBuilder.FullName);
// Replace the TypeBuilder object in m_TypeBuilderDict with this EnumBuilder object.
- Contract.Assert(enumBuilder.m_typeBuilder == m_TypeBuilderDict[name]);
+ Debug.Assert(enumBuilder.m_typeBuilder == m_TypeBuilderDict[name]);
m_TypeBuilderDict[name] = enumBuilder;
return enumBuilder;
if (method.IsGenericMethod)
{
// Constructors cannot be generic.
- Contract.Assert(methodInfo != null);
+ Debug.Assert(methodInfo != null);
// Given M<Bar> unbind to M<S>
MethodInfo methodInfoUnbound = methodInfo;
namespace System.Reflection.Emit
{
using System;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.IO;
// each assembly).
internal virtual void ModifyModuleName(String strModuleName)
{
- Contract.Assert(m_strModuleName == AssemblyBuilder.MANIFEST_MODULE_NAME, "Changing names for non-manifest module");
+ Debug.Assert(m_strModuleName == AssemblyBuilder.MANIFEST_MODULE_NAME, "Changing names for non-manifest module");
InitNames(strModuleName, null /*strFileName*/);
}
{
using System.Text;
using System;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Reflection;
using System.Runtime.CompilerServices;
AddElementType(CorElementType.CModOpt);
int token = m_module.GetTypeToken(t).Token;
- Contract.Assert(!MetadataToken.IsNullToken(token));
+ Debug.Assert(!MetadataToken.IsNullToken(token));
AddToken(token);
}
}
AddElementType(CorElementType.CModReqd);
int token = m_module.GetTypeToken(t).Token;
- Contract.Assert(!MetadataToken.IsNullToken(token));
+ Debug.Assert(!MetadataToken.IsNullToken(token));
AddToken(token);
}
}
using System.Reflection;
using System.Security;
using System.Security.Permissions;
- using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Collections.Generic;
using CultureInfo = System.Globalization.CultureInfo;
using System.Threading;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
}
else // must be a runtime Enum Type
{
- Contract.Assert(destType is RuntimeType, "destType is not a runtime type, an EnumBuilder, or a TypeBuilder.");
+ Debug.Assert(destType is RuntimeType, "destType is not a runtime type, an EnumBuilder, or a TypeBuilder.");
underlyingType = Enum.GetUnderlyingType(destType);
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
internal sealed class MethodOnTypeBuilderInstantiation : MethodInfo
#region Constructor
internal MethodOnTypeBuilderInstantiation(MethodInfo method, TypeBuilderInstantiation type)
{
- Contract.Assert(method is MethodBuilder || method is RuntimeMethodInfo);
+ Debug.Assert(method is MethodBuilder || method is RuntimeMethodInfo);
m_method = method;
m_type = type;
return mb.MetadataTokenInternal;
else
{
- Contract.Assert(m_method is RuntimeMethodInfo);
+ Debug.Assert(m_method is RuntimeMethodInfo);
return m_method.MetadataToken;
}
}
#region Constructor
internal ConstructorOnTypeBuilderInstantiation(ConstructorInfo constructor, TypeBuilderInstantiation type)
{
- Contract.Assert(constructor is ConstructorBuilder || constructor is RuntimeConstructorInfo);
+ Debug.Assert(constructor is ConstructorBuilder || constructor is RuntimeConstructorInfo);
m_ctor = constructor;
m_type = type;
return cb.MetadataTokenInternal;
else
{
- Contract.Assert(m_ctor is RuntimeConstructorInfo);
+ Debug.Assert(m_ctor is RuntimeConstructorInfo);
return m_ctor.MetadataToken;
}
}
#region Constructor
internal FieldOnTypeBuilderInstantiation(FieldInfo field, TypeBuilderInstantiation type)
{
- Contract.Assert(field is FieldBuilder || field is RuntimeFieldInfo);
+ Debug.Assert(field is FieldBuilder || field is RuntimeFieldInfo);
m_field = field;
m_type = type;
return fb.MetadataTokenInternal;
else
{
- Contract.Assert(m_field is RuntimeFieldInfo);
+ Debug.Assert(m_field is RuntimeFieldInfo);
return m_field.MetadataToken;
}
}
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotSupportedOnWinRTEvent"));
// Must be a normal non-WinRT event
- Contract.Assert(addMethod.ReturnType == typeof(void));
+ Debug.Assert(addMethod.ReturnType == typeof(void));
#endif // FEATURE_COMINTEROP
addMethod.Invoke(target, new object[] { handler });
#if FEATURE_COMINTEROP
ParameterInfo[] parameters = removeMethod.GetParametersNoCopy();
- Contract.Assert(parameters != null && parameters.Length == 1);
+ Debug.Assert(parameters != null && parameters.Length == 1);
if (parameters[0].ParameterType == typeof(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken))
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotSupportedOnWinRTEvent"));
// Must be a normal non-WinRT event
- Contract.Assert(parameters[0].ParameterType.BaseType == typeof(MulticastDelegate));
+ Debug.Assert(parameters[0].ParameterType.BaseType == typeof(MulticastDelegate));
#endif // FEATURE_COMINTEROP
removeMethod.Invoke(target, new object[] { handler });
{
Contract.Requires(declaredType != null);
Contract.Requires(reflectedTypeCache != null);
- Contract.Assert(!reflectedTypeCache.IsGlobal);
+ Debug.Assert(!reflectedTypeCache.IsGlobal);
MetadataImport scope = declaredType.GetRuntimeModule().MetadataImport;
using System;
using System.Globalization;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Reflection
#endregion
#region Public Members
- public virtual Type LocalType { get { Contract.Assert(m_type != null, "type must be set!"); return m_type; } }
+ public virtual Type LocalType { get { Debug.Assert(m_type != null, "type must be set!"); return m_type; } }
public virtual bool IsPinned { get { return m_isPinned != 0; } }
public virtual int LocalIndex { get { return m_localIndex; } }
#endregion
{
Contract.Ensures(!m_handle.IsNull());
- Contract.Assert(!handle.IsNullHandle());
- Contract.Assert(methodAttributes == RuntimeMethodHandle.GetAttributes(handle));
+ Debug.Assert(!handle.IsNullHandle());
+ Debug.Assert(methodAttributes == RuntimeMethodHandle.GetAttributes(handle));
m_bindingFlags = bindingFlags;
m_declaringType = declaringType;
{
using System;
using System.Collections.Generic;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
#region Static Members
internal unsafe static ParameterInfo[] GetParameters(IRuntimeMethodInfo method, MemberInfo member, Signature sig)
{
- Contract.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo);
+ Debug.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo);
ParameterInfo dummy;
return GetParameters(method, member, sig, out dummy, false);
internal unsafe static ParameterInfo GetReturnParameter(IRuntimeMethodInfo method, MemberInfo member, Signature sig)
{
- Contract.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo);
+ Debug.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo);
ParameterInfo returnParameter;
GetParameters(method, member, sig, out returnParameter, true);
get
{
MethodBase result = m_originalMember != null ? m_originalMember : MemberImpl as MethodBase;
- Contract.Assert(result != null);
+ Debug.Assert(result != null);
return result;
}
}
// The original owner should always be a method, because this method is only used to
// change the owner from a method to a property.
m_originalMember = accessor.MemberImpl as MethodBase;
- Contract.Assert(m_originalMember != null);
+ Debug.Assert(m_originalMember != null);
// Populate all the caches -- we inherit this behavior from RTM
NameImpl = accessor.Name;
int position, ParameterAttributes attributes, MemberInfo member)
{
Contract.Requires(member != null);
- Contract.Assert(MdToken.IsNullToken(tkParamDef) == scope.Equals(MetadataImport.EmptyImport));
- Contract.Assert(MdToken.IsNullToken(tkParamDef) || MdToken.IsTokenOfType(tkParamDef, MetadataTokenType.ParamDef));
+ Debug.Assert(MdToken.IsNullToken(tkParamDef) == scope.Equals(MetadataImport.EmptyImport));
+ Debug.Assert(MdToken.IsNullToken(tkParamDef) || MdToken.IsTokenOfType(tkParamDef, MetadataTokenType.ParamDef));
PositionImpl = position;
MemberImpl = member;
else
parameterType = m_signature.Arguments[PositionImpl];
- Contract.Assert(parameterType != null);
+ Debug.Assert(parameterType != null);
// different thread could only write ClassImpl to the same value, so a race condition is not a problem here
ClassImpl = parameterType;
}
// returns DBNull.Value if the parameter doesn't have a default value
private Object GetDefaultValueInternal(bool raw)
{
- Contract.Assert(!m_noMetadata);
+ Debug.Assert(!m_noMetadata);
if (m_noDefaultValue)
return DBNull.Value;
{
Contract.Requires(declaredType != null);
Contract.Requires(reflectedTypeCache != null);
- Contract.Assert(!reflectedTypeCache.IsGlobal);
+ Debug.Assert(!reflectedTypeCache.IsGlobal);
MetadataImport scope = declaredType.GetRuntimeModule().MetadataImport;
using System.Runtime.Versioning;
using System.Text;
using System.Threading;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
internal class FileBasedResourceGroveler : IResourceGroveler
public FileBasedResourceGroveler(ResourceManager.ResourceManagerMediator mediator)
{
- Contract.Assert(mediator != null, "mediator shouldn't be null; check caller");
+ Debug.Assert(mediator != null, "mediator shouldn't be null; check caller");
_mediator = mediator;
}
// manifest-based classes. Want to continue tightening the design to get rid of unused params.
public ResourceSet GrovelForResourceSet(CultureInfo culture, Dictionary<String, ResourceSet> localResourceSets, bool tryParents, bool createIfNotExists, ref StackCrawlMark stackMark)
{
- Contract.Assert(culture != null, "culture shouldn't be null; check caller");
+ Debug.Assert(culture != null, "culture shouldn't be null; check caller");
String fileName = null;
ResourceSet rs = null;
private String FindResourceFile(CultureInfo culture, String fileName)
{
- Contract.Assert(culture != null, "culture shouldn't be null; check caller");
- Contract.Assert(fileName != null, "fileName shouldn't be null; check caller");
+ Debug.Assert(culture != null, "culture shouldn't be null; check caller");
+ Debug.Assert(fileName != null, "fileName shouldn't be null; check caller");
// If we have a moduleDir, check there first. Get module fully
// qualified name, append path to that.
// for perf and working set reasons.
private ResourceSet CreateResourceSet(String file)
{
- Contract.Assert(file != null, "file shouldn't be null; check caller");
+ Debug.Assert(file != null, "file shouldn't be null; check caller");
if (_mediator.UserResourceSet == null)
{
using System.Runtime.Versioning;
using System.Text;
using System.Threading;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using Microsoft.Win32;
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public ResourceSet GrovelForResourceSet(CultureInfo culture, Dictionary<String, ResourceSet> localResourceSets, bool tryParents, bool createIfNotExists, ref StackCrawlMark stackMark)
{
- Contract.Assert(culture != null, "culture shouldn't be null; check caller");
- Contract.Assert(localResourceSets != null, "localResourceSets shouldn't be null; check caller");
+ Debug.Assert(culture != null, "culture shouldn't be null; check caller");
+ Debug.Assert(localResourceSets != null, "localResourceSets shouldn't be null; check caller");
ResourceSet rs = null;
Stream stream = null;
internal static CultureInfo GetNeutralResourcesLanguage(Assembly a, ref UltimateResourceFallbackLocation fallbackLocation)
{
- Contract.Assert(a != null, "assembly != null");
+ Debug.Assert(a != null, "assembly != null");
string cultureName = null;
short fallback = 0;
if (GetNeutralResourcesLanguageAttribute(((RuntimeAssembly)a).GetNativeHandle(),
// fires, please fix the build process for the BCL directory.
if (a == typeof(Object).Assembly)
{
- Contract.Assert(false, System.CoreLib.Name+"'s NeutralResourcesLanguageAttribute is a malformed culture name! name: \"" + cultureName + "\" Exception: " + e);
+ Debug.Assert(false, System.CoreLib.Name+"'s NeutralResourcesLanguageAttribute is a malformed culture name! name: \"" + cultureName + "\" Exception: " + e);
return CultureInfo.InvariantCulture;
}
// This method could use some refactoring. One thing at a time.
internal ResourceSet CreateResourceSet(Stream store, Assembly assembly)
{
- Contract.Assert(store != null, "I need a Stream!");
+ Debug.Assert(store != null, "I need a Stream!");
// Check to see if this is a Stream the ResourceManager understands,
// and check for the correct resource reader type.
if (store.CanSeek && store.Length > 4)
Type resSetType;
if (_mediator.UserResourceSet == null)
{
- Contract.Assert(resSetTypeName != null, "We should have a ResourceSet type name from the custom resource file here.");
+ Debug.Assert(resSetTypeName != null, "We should have a ResourceSet type name from the custom resource file here.");
resSetType = Type.GetType(resSetTypeName, true, false);
}
else
int hr = fle._HResult;
if (hr != Win32Native.MakeHRFromErrorCode(Win32Native.ERROR_ACCESS_DENIED))
{
- Contract.Assert(false, "[This assert catches satellite assembly build/deployment problems - report this message to your build lab & loc engineer]" + Environment.NewLine + "GetSatelliteAssembly failed for culture " + lookForCulture.Name + " and version " + (_mediator.SatelliteContractVersion == null ? _mediator.MainAssembly.GetVersion().ToString() : _mediator.SatelliteContractVersion.ToString()) + " of assembly " + _mediator.MainAssembly.GetSimpleName() + " with error code 0x" + hr.ToString("X", CultureInfo.InvariantCulture) + Environment.NewLine + "Exception: " + fle);
+ Debug.Assert(false, "[This assert catches satellite assembly build/deployment problems - report this message to your build lab & loc engineer]" + Environment.NewLine + "GetSatelliteAssembly failed for culture " + lookForCulture.Name + " and version " + (_mediator.SatelliteContractVersion == null ? _mediator.MainAssembly.GetVersion().ToString() : _mediator.SatelliteContractVersion.ToString()) + " of assembly " + _mediator.MainAssembly.GetSimpleName() + " with error code 0x" + hr.ToString("X", CultureInfo.InvariantCulture) + Environment.NewLine + "Exception: " + fle);
}
}
// Don't throw for zero-length satellite assemblies, for compat with v1
catch (BadImageFormatException bife)
{
- Contract.Assert(false, "[This assert catches satellite assembly build/deployment problems - report this message to your build lab & loc engineer]" + Environment.NewLine + "GetSatelliteAssembly failed for culture " + lookForCulture.Name + " and version " + (_mediator.SatelliteContractVersion == null ? _mediator.MainAssembly.GetVersion().ToString() : _mediator.SatelliteContractVersion.ToString()) + " of assembly " + _mediator.MainAssembly.GetSimpleName() + Environment.NewLine + "Exception: " + bife);
+ Debug.Assert(false, "[This assert catches satellite assembly build/deployment problems - report this message to your build lab & loc engineer]" + Environment.NewLine + "GetSatelliteAssembly failed for culture " + lookForCulture.Name + " and version " + (_mediator.SatelliteContractVersion == null ? _mediator.MainAssembly.GetVersion().ToString() : _mediator.SatelliteContractVersion.ToString()) + " of assembly " + _mediator.MainAssembly.GetSimpleName() + Environment.NewLine + "Exception: " + bife);
}
return satellite;
// and causes partially trusted localized apps to fail.
private bool CanUseDefaultResourceClasses(String readerTypeName, String resSetTypeName)
{
- Contract.Assert(readerTypeName != null, "readerTypeName shouldn't be null; check caller");
- Contract.Assert(resSetTypeName != null, "resSetTypeName shouldn't be null; check caller");
+ Debug.Assert(readerTypeName != null, "readerTypeName shouldn't be null; check caller");
+ Debug.Assert(resSetTypeName != null, "resSetTypeName shouldn't be null; check caller");
if (_mediator.UserResourceSet != null)
return false;
if (_mediator.MainAssembly == typeof(Object).Assembly && _mediator.BaseName.Equals(System.CoreLib.Name))
{
// This would break CultureInfo & all our exceptions.
- Contract.Assert(false, "Couldn't get " + System.CoreLib.Name+ResourceManager.ResFileExtension + " from "+System.CoreLib.Name+"'s assembly" + Environment.NewLine + Environment.NewLine + "Are you building the runtime on your machine? Chances are the BCL directory didn't build correctly. Type 'build -c' in the BCL directory. If you get build errors, look at buildd.log. If you then can't figure out what's wrong (and you aren't changing the assembly-related metadata code), ask a BCL dev.\n\nIf you did NOT build the runtime, you shouldn't be seeing this and you've found a bug.");
+ Debug.Assert(false, "Couldn't get " + System.CoreLib.Name+ResourceManager.ResFileExtension + " from "+System.CoreLib.Name+"'s assembly" + Environment.NewLine + Environment.NewLine + "Are you building the runtime on your machine? Chances are the BCL directory didn't build correctly. Type 'build -c' in the BCL directory. If you get build errors, look at buildd.log. If you then can't figure out what's wrong (and you aren't changing the assembly-related metadata code), ask a BCL dev.\n\nIf you did NOT build the runtime, you shouldn't be seeing this and you've found a bug.");
// We cannot continue further - simply FailFast.
string mesgFailFast = System.CoreLib.Name + ResourceManager.ResFileExtension + " couldn't be found! Large parts of the BCL won't work!";
using Microsoft.Win32;
using System.Collections.Generic;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
#if FEATURE_APPX
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
protected virtual ResourceSet InternalGetResourceSet(CultureInfo culture, bool createIfNotExists, bool tryParents)
{
- Contract.Assert(culture != null, "culture != null");
+ Debug.Assert(culture != null, "culture != null");
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return InternalGetResourceSet(culture,createIfNotExists,tryParents, ref stackMark);
Object[] attrs = a.GetCustomAttributes(typeof(SatelliteContractVersionAttribute), false);
if (attrs.Length == 0)
return null;
- Contract.Assert(attrs.Length == 1, "Cannot have multiple instances of SatelliteContractVersionAttribute on an assembly!");
+ Debug.Assert(attrs.Length == 1, "Cannot have multiple instances of SatelliteContractVersionAttribute on an assembly!");
v = ((SatelliteContractVersionAttribute)attrs[0]).Version;
}
Version ver;
// If this assert fires, please fix the build process for the
// BCL directory.
if (a == typeof(Object).Assembly) {
- Contract.Assert(false, System.CoreLib.Name+"'s SatelliteContractVersionAttribute is a malformed version string!");
+ Debug.Assert(false, System.CoreLib.Name+"'s SatelliteContractVersionAttribute is a malformed version string!");
return null;
}
String typeName2,
AssemblyName asmName2)
{
- Contract.Assert(asmTypeName1 != null, "asmTypeName1 was unexpectedly null");
+ Debug.Assert(asmTypeName1 != null, "asmTypeName1 was unexpectedly null");
// First, compare type names
int comma = asmTypeName1.IndexOf(',');
#if FEATURE_APPX
private string GetStringFromPRI(String stringName, String startingCulture, String neutralResourcesCulture) {
- Contract.Assert(_bUsingModernResourceManagement);
- Contract.Assert(_WinRTResourceManager != null);
- Contract.Assert(_PRIonAppXInitialized);
- Contract.Assert(AppDomain.IsAppXModel());
+ Debug.Assert(_bUsingModernResourceManagement);
+ Debug.Assert(_WinRTResourceManager != null);
+ Debug.Assert(_PRIonAppXInitialized);
+ Debug.Assert(AppDomain.IsAppXModel());
if (stringName.Length == 0)
return null;
private void SetAppXConfiguration()
{
- Contract.Assert(_bUsingModernResourceManagement == false); // Only this function writes to this member
+ Debug.Assert(_bUsingModernResourceManagement == false); // Only this function writes to this member
#if FEATURE_APPX
- Contract.Assert(_WinRTResourceManager == null); // Only this function writes to this member
- Contract.Assert(_PRIonAppXInitialized == false); // Only this function writes to this member
- Contract.Assert(_PRIExceptionInfo == null); // Only this function writes to this member
+ Debug.Assert(_WinRTResourceManager == null); // Only this function writes to this member
+ Debug.Assert(_PRIonAppXInitialized == false); // Only this function writes to this member
+ Debug.Assert(_PRIExceptionInfo == null); // Only this function writes to this member
bool bUsingSatelliteAssembliesUnderAppX = false;
using System.Globalization;
using System.Configuration.Assemblies;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
// Provides the default implementation of IResourceReader, reading
internal static bool CanCache(ResourceTypeCode value)
{
- Contract.Assert(value >= 0, "negative ResourceTypeCode. What?");
+ Debug.Assert(value >= 0, "negative ResourceTypeCode. What?");
return value <= ResourceTypeCode.LastPrimitive;
}
}
private unsafe int GetNameHash(int index)
{
- Contract.Assert(index >=0 && index < _numResources, "Bad index into hash array. index: "+index);
- Contract.Assert((_ums == null && _nameHashes != null && _nameHashesPtr == null) ||
+ Debug.Assert(index >=0 && index < _numResources, "Bad index into hash array. index: "+index);
+ Debug.Assert((_ums == null && _nameHashes != null && _nameHashesPtr == null) ||
(_ums != null && _nameHashes == null && _nameHashesPtr != null), "Internal state mangled.");
if (_ums == null)
return _nameHashes[index];
private unsafe int GetNamePosition(int index)
{
- Contract.Assert(index >=0 && index < _numResources, "Bad index into name position array. index: "+index);
- Contract.Assert((_ums == null && _namePositions != null && _namePositionsPtr == null) ||
+ Debug.Assert(index >=0 && index < _numResources, "Bad index into name position array. index: "+index);
+ Debug.Assert((_ums == null && _namePositions != null && _namePositionsPtr == null) ||
(_ums != null && _namePositions == null && _namePositionsPtr != null), "Internal state mangled.");
int r;
if (_ums == null)
// This does a binary search through the names.
internal int FindPosForResource(String name)
{
- Contract.Assert(_store != null, "ResourceReader is closed!");
+ Debug.Assert(_store != null, "ResourceReader is closed!");
int hash = FastResourceComparer.HashFunction(name);
BCLDebug.Log("RESMGRFILEFORMAT", "FindPosForResource for "+name+" hash: "+hash.ToString("x", CultureInfo.InvariantCulture));
// Binary search over the hashes. Use the _namePositions array to
// so no one else can cause us to seek in the stream.
private unsafe bool CompareStringEqualsName(String name)
{
- Contract.Assert(_store != null, "ResourceReader is closed!");
+ Debug.Assert(_store != null, "ResourceReader is closed!");
int byteLen = _store.Read7BitEncodedInt();
if (byteLen < 0) {
throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_NegativeStringLength"));
// index. The parameter is NOT a virtual offset.
private unsafe String AllocateStringForNameIndex(int index, out int dataOffset)
{
- Contract.Assert(_store != null, "ResourceReader is closed!");
+ Debug.Assert(_store != null, "ResourceReader is closed!");
byte[] bytes;
int byteLen;
long nameVA = GetNamePosition(index);
// index. The parameter is NOT a virtual offset.
private Object GetValueForNameIndex(int index)
{
- Contract.Assert(_store != null, "ResourceReader is closed!");
+ Debug.Assert(_store != null, "ResourceReader is closed!");
long nameVA = GetNamePosition(index);
lock(this) {
_store.BaseStream.Seek(nameVA + _nameSectionOffset, SeekOrigin.Begin);
// no one can cause us to do a seek in here.
internal String LoadString(int pos)
{
- Contract.Assert(_store != null, "ResourceReader is closed!");
+ Debug.Assert(_store != null, "ResourceReader is closed!");
_store.BaseStream.Seek(_dataSectionOffset+pos, SeekOrigin.Begin);
String s = null;
int typeIndex = _store.Read7BitEncodedInt();
// no one can cause us to do a seek in here.
internal Object LoadObjectV1(int pos)
{
- Contract.Assert(_store != null, "ResourceReader is closed!");
- Contract.Assert(_version == 1, ".resources file was not a V1 .resources file!");
+ Debug.Assert(_store != null, "ResourceReader is closed!");
+ Debug.Assert(_version == 1, ".resources file was not a V1 .resources file!");
try {
// mega try-catch performs exceptionally bad on x64; factored out body into
internal Object LoadObjectV2(int pos, out ResourceTypeCode typeCode)
{
- Contract.Assert(_store != null, "ResourceReader is closed!");
- Contract.Assert(_version >= 2, ".resources file was not a V2 (or higher) .resources file!");
+ Debug.Assert(_store != null, "ResourceReader is closed!");
+ Debug.Assert(_version >= 2, ".resources file was not a V2 (or higher) .resources file!");
try {
// mega try-catch performs exceptionally bad on x64; factored out body into
byte[] bytes = new byte[len];
int r = _ums.Read(bytes, 0, len);
- Contract.Assert(r == len, "ResourceReader needs to use a blocking read here. (Call _store.ReadBytes(len)?)");
+ Debug.Assert(r == len, "ResourceReader needs to use a blocking read here. (Call _store.ReadBytes(len)?)");
return bytes;
}
// for the default resource file format.
private void ReadResources()
{
- Contract.Assert(_store != null, "ResourceReader is closed!");
+ Debug.Assert(_store != null, "ResourceReader is closed!");
#if FEATURE_SERIALIZATION
BinaryFormatter bf = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.File | StreamingContextStates.Persistence));
_typeLimitingBinder = new TypeLimitingDeserializationBinder();
_store.BaseStream.Position = oldPos;
}
}
- Contract.Assert(_typeTable[typeIndex] != null, "Should have found a type!");
+ Debug.Assert(_typeTable[typeIndex] != null, "Should have found a type!");
return _typeTable[typeIndex];
}
Array.Sort(sortedDataPositions);
int index = Array.BinarySearch(sortedDataPositions, dataPos);
- Contract.Assert(index >= 0 && index < _numResources, "Couldn't find data position within sorted data positions array!");
+ Debug.Assert(index >= 0 && index < _numResources, "Couldn't find data position within sorted data positions array!");
long nextData = (index < _numResources - 1) ? sortedDataPositions[index + 1] + _dataSectionOffset : _store.BaseStream.Length;
int len = (int) (nextData - (dataPos + _dataSectionOffset));
- Contract.Assert(len >= 0 && len <= (int) _store.BaseStream.Length - dataPos + _dataSectionOffset, "Length was negative or outside the bounds of the file!");
+ Debug.Assert(len >= 0 && len <= (int) _store.BaseStream.Length - dataPos + _dataSectionOffset, "Length was negative or outside the bounds of the file!");
// Read type code then byte[]
_store.BaseStream.Position = _dataSectionOffset + dataPos;
{
Contract.Requires(typeCode >= 0, "can't be negative");
if (typeCode < ResourceTypeCode.StartOfUserTypes) {
- Contract.Assert(!String.Equals(typeCode.ToString(), "LastPrimitive"), "Change ResourceTypeCode metadata order so LastPrimitive isn't what Enum.ToString prefers.");
+ Debug.Assert(!String.Equals(typeCode.ToString(), "LastPrimitive"), "Change ResourceTypeCode metadata order so LastPrimitive isn't what Enum.ToString prefers.");
return "ResourceTypeCode." + typeCode.ToString();
}
else {
int typeIndex = typeCode - ResourceTypeCode.StartOfUserTypes;
- Contract.Assert(typeIndex >= 0 && typeIndex < _typeTable.Length, "TypeCode is broken or corrupted!");
+ Debug.Assert(typeIndex >= 0 && typeIndex < _typeTable.Length, "TypeCode is broken or corrupted!");
long oldPos = _store.BaseStream.Position;
try {
_store.BaseStream.Position = _typeNamePositions[typeIndex];
using System.Globalization;
using System.Reflection;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
// A RuntimeResourceSet stores all the resources defined in one
}
if (dataPos != -1 && value == null) {
- Contract.Assert(dataPos >= 0, "data section offset cannot be negative!");
+ Debug.Assert(dataPos >= 0, "data section offset cannot be negative!");
// Normally calling LoadString or LoadObject requires
// taking a lock. Note that in this case, we took a
// lock on the entire RuntimeResourceSet, which is
Reader.Close();
}
else {
- Contract.Assert(ignoreCase, "This should only happen for case-insensitive lookups");
+ Debug.Assert(ignoreCase, "This should only happen for case-insensitive lookups");
ResourceReader.ResourceEnumerator en = _defaultReader.GetEnumeratorInternal();
while (en.MoveNext()) {
// Note: Always ask for the resource key before the data position.
using System;
using System.Collections;
using System.Collections.Generic;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
internal sealed class FastResourceComparer : IComparer, IEqualityComparer, IComparer<String>, IEqualityComparer<String>
// little endian unicode. Pass in the number of valid chars.
public unsafe static int CompareOrdinal(String a, byte[] bytes, int bCharLength)
{
- Contract.Assert(a != null && bytes != null, "FastResourceComparer::CompareOrdinal must have non-null params");
- Contract.Assert(bCharLength * 2 <= bytes.Length, "FastResourceComparer::CompareOrdinal - numChars is too big!");
+ Debug.Assert(a != null && bytes != null, "FastResourceComparer::CompareOrdinal must have non-null params");
+ Debug.Assert(bCharLength * 2 <= bytes.Length, "FastResourceComparer::CompareOrdinal - numChars is too big!");
// This is a managed version of strcmp, but I can't take advantage
// of a terminating 0, unlike strcmp in C.
int i = 0;
// The byte* must point to little endian Unicode characters.
internal unsafe static int CompareOrdinal(byte* a, int byteLen, String b)
{
- Contract.Assert((byteLen & 1) == 0, "CompareOrdinal is expecting a UTF-16 string length, which must be even!");
- Contract.Assert(a != null && b != null, "Null args not allowed.");
- Contract.Assert(byteLen >= 0, "byteLen must be non-negative.");
+ Debug.Assert((byteLen & 1) == 0, "CompareOrdinal is expecting a UTF-16 string length, which must be even!");
+ Debug.Assert(a != null && b != null, "Null args not allowed.");
+ Debug.Assert(byteLen >= 0, "byteLen must be non-negative.");
int r = 0;
int i = 0;
// Currently the callers of UsesStringComparison assume that if it returns false
// then the match always succeeds and can be skipped. Assert that this is maintained.
- Contract.Assert(retVal || RequiresStringComparison());
+ Debug.Assert(retVal || RequiresStringComparison());
return retVal;
}
public uint GetHashToMatch()
{
- Contract.Assert(RequiresStringComparison());
+ Debug.Assert(RequiresStringComparison());
return m_nameHash;
}
// Grow the list by exactly one element in this case to avoid null entries at the end.
//
- Contract.Assert(false);
+ Debug.Assert(false);
newSize = cachedMembers.Length + 1;
}
cachedMembers = cachedMembers2;
}
- Contract.Assert(cachedMembers[freeSlotIndex] == null);
+ Debug.Assert(cachedMembers[freeSlotIndex] == null);
cachedMembers[freeSlotIndex] = newMemberInfo;
freeSlotIndex++;
}
ListBuilder<RuntimeMethodInfo> list = new ListBuilder<RuntimeMethodInfo>();
RuntimeType declaringType = ReflectedType;
- Contract.Assert(declaringType != null);
+ Debug.Assert(declaringType != null);
if (RuntimeTypeHandle.IsInterface(declaringType))
{
{
if (!RuntimeMethodHandle.MatchesNameHash(methodHandle, filter.GetHashToMatch()))
{
- Contract.Assert(!filter.Match(RuntimeMethodHandle.GetUtf8Name(methodHandle)));
+ Debug.Assert(!filter.Match(RuntimeMethodHandle.GetUtf8Name(methodHandle)));
continue;
}
}
#region Loop through all methods on the interface
- Contract.Assert(!methodHandle.IsNullHandle());
+ Debug.Assert(!methodHandle.IsNullHandle());
// Except for .ctor, .cctor, IL_STUB*, and static methods, all interface methods should be abstract, virtual, and non-RTSpecialName.
// Note that this assumption will become invalid when we add support for non-abstract or static methods on interfaces.
- Contract.Assert(
+ Debug.Assert(
(RuntimeMethodHandle.GetAttributes(methodHandle) & (MethodAttributes.RTSpecialName | MethodAttributes.Abstract | MethodAttributes.Virtual)) == (MethodAttributes.Abstract | MethodAttributes.Virtual) ||
(RuntimeMethodHandle.GetAttributes(methodHandle) & MethodAttributes.Static) == MethodAttributes.Static ||
RuntimeMethodHandle.GetName(methodHandle).Equals(".ctor") ||
{
if (!RuntimeMethodHandle.MatchesNameHash(methodHandle, filter.GetHashToMatch()))
{
- Contract.Assert(!filter.Match(RuntimeMethodHandle.GetUtf8Name(methodHandle)));
+ Debug.Assert(!filter.Match(RuntimeMethodHandle.GetUtf8Name(methodHandle)));
continue;
}
}
#region Loop through all methods on the current type
- Contract.Assert(!methodHandle.IsNullHandle());
+ Debug.Assert(!methodHandle.IsNullHandle());
MethodAttributes methodAttributes = RuntimeMethodHandle.GetAttributes(methodHandle);
MethodAttributes methodAccess = methodAttributes & MethodAttributes.MemberAccessMask;
#region Continue if this is a constructor
- Contract.Assert(
+ Debug.Assert(
(RuntimeMethodHandle.GetAttributes(methodHandle) & MethodAttributes.RTSpecialName) == 0 ||
RuntimeMethodHandle.GetName(methodHandle).Equals(".ctor") ||
RuntimeMethodHandle.GetName(methodHandle).Equals(".cctor"));
#region Continue if this is a virtual and is already overridden
if (isVirtual)
{
- Contract.Assert(
+ Debug.Assert(
(methodAttributes & MethodAttributes.Abstract) != 0 ||
(methodAttributes & MethodAttributes.Virtual) != 0 ||
RuntimeMethodHandle.GetDeclaringType(methodHandle) != declaringType);
}
else
{
- Contract.Assert((methodAttributes & (MethodAttributes.Virtual | MethodAttributes.Abstract)) == 0);
+ Debug.Assert((methodAttributes & (MethodAttributes.Virtual | MethodAttributes.Abstract)) == 0);
}
#endregion
{
if (!RuntimeMethodHandle.MatchesNameHash(methodHandle, filter.GetHashToMatch()))
{
- Contract.Assert(!filter.Match(RuntimeMethodHandle.GetUtf8Name(methodHandle)));
+ Debug.Assert(!filter.Match(RuntimeMethodHandle.GetUtf8Name(methodHandle)));
continue;
}
MethodAttributes methodAttributes = RuntimeMethodHandle.GetAttributes(methodHandle);
- Contract.Assert(!methodHandle.IsNullHandle());
+ Debug.Assert(!methodHandle.IsNullHandle());
if ((methodAttributes & MethodAttributes.RTSpecialName) == 0)
continue;
// Constructors should not be virtual or abstract
- Contract.Assert(
+ Debug.Assert(
(methodAttributes & MethodAttributes.Abstract) == 0 &&
(methodAttributes & MethodAttributes.Virtual) == 0);
{
if (!RuntimeFieldHandle.MatchesNameHash(runtimeFieldHandle, filter.GetHashToMatch()))
{
- Contract.Assert(!filter.Match(RuntimeFieldHandle.GetUtf8Name(runtimeFieldHandle)));
+ Debug.Assert(!filter.Match(RuntimeFieldHandle.GetUtf8Name(runtimeFieldHandle)));
continue;
}
continue;
}
- Contract.Assert(!runtimeFieldHandle.IsNullHandle());
+ Debug.Assert(!runtimeFieldHandle.IsNullHandle());
FieldAttributes fieldAttributes = RuntimeFieldHandle.GetAttributes(runtimeFieldHandle);
FieldAttributes fieldAccess = fieldAttributes & FieldAttributes.FieldAccessMask;
for (int i = 0; i < tkFields.Length; i++)
{
int tkField = tkFields[i];
- Contract.Assert(MdToken.IsTokenOfType(tkField, MetadataTokenType.FieldDef));
- Contract.Assert(!MdToken.IsNullToken(tkField));
+ Debug.Assert(MdToken.IsTokenOfType(tkField, MetadataTokenType.FieldDef));
+ Debug.Assert(!MdToken.IsNullToken(tkField));
FieldAttributes fieldAttributes;
scope.GetFieldDefProps(tkField, out fieldAttributes);
continue;
}
- Contract.Assert(interfaceType.IsInterface);
+ Debug.Assert(interfaceType.IsInterface);
list.Add(interfaceType);
}
}
int tkEvent = tkEvents[i];
bool isPrivate;
- Contract.Assert(!MdToken.IsNullToken(tkEvent));
- Contract.Assert(MdToken.IsTokenOfType(tkEvent, MetadataTokenType.Event));
+ Debug.Assert(!MdToken.IsNullToken(tkEvent));
+ Debug.Assert(MdToken.IsTokenOfType(tkEvent, MetadataTokenType.Event));
if (filter.RequiresStringComparison())
{
// is called in Populate after this returns.
RuntimeType declaringType = ReflectedType;
- Contract.Assert(declaringType != null);
+ Debug.Assert(declaringType != null);
ListBuilder<RuntimePropertyInfo> list = new ListBuilder<RuntimePropertyInfo>();
int numVirtuals = RuntimeTypeHandle.GetNumVirtuals(declaringType);
- Contract.Assert((declaringType.IsInterface && usedSlots == null && csPropertyInfos == null) ||
+ Debug.Assert((declaringType.IsInterface && usedSlots == null && csPropertyInfos == null) ||
(!declaringType.IsInterface && usedSlots != null && usedSlots.Length >= numVirtuals));
for (int i = 0; i < tkProperties.Length; i++)
int tkProperty = tkProperties[i];
bool isPrivate;
- Contract.Assert(!MdToken.IsNullToken(tkProperty));
- Contract.Assert(MdToken.IsTokenOfType(tkProperty, MetadataTokenType.Property));
+ Debug.Assert(!MdToken.IsNullToken(tkProperty));
+ Debug.Assert(MdToken.IsTokenOfType(tkProperty, MetadataTokenType.Property));
if (filter.RequiresStringComparison())
{
if (!ModuleHandle.ContainsPropertyMatchingHash(declaringModuleHandle, tkProperty, filter.GetHashToMatch()))
{
- Contract.Assert(!filter.Match(declaringType.GetRuntimeModule().MetadataImport.GetName(tkProperty)));
+ Debug.Assert(!filter.Match(declaringType.GetRuntimeModule().MetadataImport.GetName(tkProperty)));
continue;
}
if (slot < numVirtuals)
{
- Contract.Assert(associateMethod.IsVirtual);
+ Debug.Assert(associateMethod.IsVirtual);
if (usedSlots[slot] == true)
continue;
else
return Populate(name, listType, cacheType);
default:
- Contract.Assert(listType == MemberListType.All);
+ Debug.Assert(listType == MemberListType.All);
if (Volatile.Read(ref m_cacheComplete))
return m_allMembers;
{
// Use void as a marker of null enclosing type
RuntimeType enclosingType = RuntimeTypeHandle.GetDeclaringType(GetRuntimeType());
- Contract.Assert(enclosingType != typeof(void));
+ Debug.Assert(enclosingType != typeof(void));
m_enclosingType = enclosingType ?? (RuntimeType)typeof(void);
}
internal unsafe static MethodBase GetMethodBase(RuntimeType reflectedType, RuntimeMethodHandleInternal methodHandle)
{
- Contract.Assert(!methodHandle.IsNullHandle());
+ Debug.Assert(!methodHandle.IsNullHandle());
if (RuntimeMethodHandle.IsDynamicMethod(methodHandle))
{
name = fullname.Substring(nsDelimiter + 1, nameLength);
else
name = "";
- Contract.Assert(fullname.Equals(ns + "." + name));
+ Debug.Assert(fullname.Equals(ns + "." + name));
}
else
{
// Most of the plural GetXXX methods allow prefix lookups while the singular GetXXX methods mostly do not.
private static bool FilterApplyPrefixLookup(MemberInfo memberInfo, string name, bool ignoreCase)
{
- Contract.Assert(name != null);
+ Debug.Assert(name != null);
if (ignoreCase)
{
Type type, BindingFlags bindingFlags, string name, bool prefixLookup, string ns)
{
Contract.Requires((object)type != null);
- Contract.Assert(type is RuntimeType);
+ Debug.Assert(type is RuntimeType);
bool isPublic = type.IsNestedPublic || type.IsPublic;
bool isStatic = false;
{
// If Binding flags did not include varargs we would have filtered this vararg method.
// This Invariant established during callConv check.
- Contract.Assert((callConv & CallingConventions.VarArgs) != 0);
+ Debug.Assert((callConv & CallingConventions.VarArgs) != 0);
}
#endregion
}
cache = existingCache;
}
- Contract.Assert(cache != null);
+ Debug.Assert(cache != null);
return cache;
}
}
events.CopyTo(members, i); i += events.Count;
fields.CopyTo(members, i); i += fields.Count;
nestedTypes.CopyTo(members, i); i += nestedTypes.Count;
- Contract.Assert(i == members.Length);
+ Debug.Assert(i == members.Length);
return members;
}
RuntimeTypeHandle ifaceRtTypeHandle = ifaceRtType.GetTypeHandleInternal();
GetTypeHandleInternal().VerifyInterfaceIsImplemented(ifaceRtTypeHandle);
- Contract.Assert(ifaceType.IsInterface); // VerifyInterfaceIsImplemented enforces this invariant
- Contract.Assert(!IsInterface); // VerifyInterfaceIsImplemented enforces this invariant
+ Debug.Assert(ifaceType.IsInterface); // VerifyInterfaceIsImplemented enforces this invariant
+ Debug.Assert(!IsInterface); // VerifyInterfaceIsImplemented enforces this invariant
// SZArrays implement the methods on IList`1, IEnumerable`1, and ICollection`1 with
// SZArrayHelper and some runtime magic. We don't have accurate interface maps for them.
// GetMethodBase will convert this to the instantiating/unboxing stub if necessary
MethodBase ifaceMethodBase = RuntimeType.GetMethodBase(ifaceRtType, ifaceRtMethodHandle);
- Contract.Assert(ifaceMethodBase is RuntimeMethodInfo);
+ Debug.Assert(ifaceMethodBase is RuntimeMethodInfo);
im.InterfaceMethods[i] = (MethodInfo)ifaceMethodBase;
// If the slot is -1, then virtual stub dispatch is active.
// GetMethodBase will convert this to the instantiating/unboxing stub if necessary
MethodBase rtTypeMethodBase = RuntimeType.GetMethodBase(this, classRtMethodHandle);
// a class may not implement all the methods of an interface (abstract class) so null is a valid value
- Contract.Assert(rtTypeMethodBase == null || rtTypeMethodBase is RuntimeMethodInfo);
+ Debug.Assert(rtTypeMethodBase == null || rtTypeMethodBase is RuntimeMethodInfo);
im.TargetMethods[i] = (MethodInfo)rtTypeMethodBase;
}
events.CopyTo(compressMembers, i); i += events.Count;
fields.CopyTo(compressMembers, i); i += fields.Count;
nestedTypes.CopyTo(compressMembers, i); i += nestedTypes.Count;
- Contract.Assert(i == compressMembers.Length);
+ Debug.Assert(i == compressMembers.Length);
return compressMembers;
}
{
// Since this cannot be a generic parameter, we use RuntimeTypeHandle.IsValueType here
// because it is faster than RuntimeType.IsValueType
- Contract.Assert(!IsGenericParameter);
+ Debug.Assert(!IsGenericParameter);
Type type = value.GetType();
}
else
{
- Contract.Assert(IsSetField);
+ Debug.Assert(IsSetField);
if (providedArgs == null)
throw new ArgumentNullException(nameof(providedArgs));
FieldInfo selFld = null;
FieldInfo[] flds = GetMember(name, MemberTypes.Field, bindingFlags) as FieldInfo[];
- Contract.Assert(flds != null);
+ Debug.Assert(flds != null);
if (flds.Length == 1)
{
#region Preconditions
if (isGetProperty)
{
- Contract.Assert(!IsSetField);
+ Debug.Assert(!IsSetField);
if (isSetProperty)
throw new ArgumentException(Environment.GetResourceString("Arg_PropSetGet"), nameof(bindingFlags));
}
else
{
- Contract.Assert(isSetProperty);
+ Debug.Assert(isSetProperty);
- Contract.Assert(!IsGetField);
+ Debug.Assert(!IsGetField);
if ((bindingFlags & BindingFlags.InvokeMethod) != 0)
throw new ArgumentException(Environment.GetResourceString("Arg_PropSetInvoke"), nameof(bindingFlags));
for(int i = 0; i < semiFinalists.Length; i ++)
{
MethodInfo semiFinalist = semiFinalists[i];
- Contract.Assert(semiFinalist != null);
+ Debug.Assert(semiFinalist != null);
if (!FilterApplyMethodInfo((RuntimeMethodInfo)semiFinalist, bindingFlags, CallingConventions.Any, new Type[argCnt]))
continue;
if (results != null)
{
- Contract.Assert(results.Count > 1);
+ Debug.Assert(results.Count > 1);
finalists = new MethodInfo[results.Count];
results.CopyTo(finalists);
}
}
#endregion
- Contract.Assert(finalists == null || finalist != null);
+ Debug.Assert(finalists == null || finalist != null);
#region BindingFlags.GetProperty or BindingFlags.SetProperty
if (finalist == null && isGetProperty || isSetProperty)
if (results != null)
{
- Contract.Assert(results.Count > 1);
+ Debug.Assert(results.Count > 1);
finalists = new MethodInfo[results.Count];
results.CopyTo(finalists);
}
if (args.Length != 0)
{
- Contract.Assert((invokeMethod.CallingConvention & CallingConventions.VarArgs) ==
+ Debug.Assert((invokeMethod.CallingConvention & CallingConventions.VarArgs) ==
CallingConventions.VarArgs);
throw new NotSupportedException(String.Format(CultureInfo.CurrentCulture,
Environment.GetResourceString("NotSupported_CallToVarArg")));
{
if (!ace.m_type.IsValueType)
{
- Contract.Assert(!ace.m_hCtorMethodHandle.IsNullHandle(), "Expected the default ctor method handle for a reference type.");
+ Debug.Assert(!ace.m_hCtorMethodHandle.IsNullHandle(), "Expected the default ctor method handle for a reference type.");
if (delegateCtorInfo == null)
InitializeDelegateCreator();
Object instance = RuntimeTypeHandle.Allocate(this);
// if m_ctor is null, this type doesn't have a default ctor
- Contract.Assert(ace.m_ctor != null || this.IsValueType);
+ Debug.Assert(ace.m_ctor != null || this.IsValueType);
if (ace.m_ctor != null)
{
}
else
{
- Contract.Assert(!hit.Equals(key), "Key was already in CerHashtable! Potential race condition (or bug) in the Reflection cache?");
+ Debug.Assert(!hit.Equals(key), "Key was already in CerHashtable! Potential race condition (or bug) in the Reflection cache?");
index++;
if (index >= keys.Length)
{
AsyncMethodBuilderCore.MoveNextRunner runnerToInitialize = null;
var continuation = m_coreState.GetCompletionAction(AsyncCausalityTracer.LoggingOn ? this.Task : null, ref runnerToInitialize);
- Contract.Assert(continuation != null, "GetCompletionAction should always return a valid action.");
+ Debug.Assert(continuation != null, "GetCompletionAction should always return a valid action.");
// If this is our first await, such that we've not yet boxed the state machine, do so now.
if (m_coreState.m_stateMachine == null)
{
AsyncMethodBuilderCore.MoveNextRunner runnerToInitialize = null;
var continuation = m_coreState.GetCompletionAction(AsyncCausalityTracer.LoggingOn ? this.Task : null, ref runnerToInitialize);
- Contract.Assert(continuation != null, "GetCompletionAction should always return a valid action.");
+ Debug.Assert(continuation != null, "GetCompletionAction should always return a valid action.");
// If this is our first await, such that we've not yet boxed the state machine, do so now.
if (m_coreState.m_stateMachine == null)
/// <summary>Notifies the current synchronization context that the operation completed.</summary>
private void NotifySynchronizationContextOfCompletion()
{
- Contract.Assert(m_synchronizationContext != null, "Must only be used with a non-null context.");
+ Debug.Assert(m_synchronizationContext != null, "Must only be used with a non-null context.");
try
{
m_synchronizationContext.OperationCompleted();
{
AsyncMethodBuilderCore.MoveNextRunner runnerToInitialize = null;
var continuation = m_coreState.GetCompletionAction(AsyncCausalityTracer.LoggingOn ? this.Task : null, ref runnerToInitialize);
- Contract.Assert(continuation != null, "GetCompletionAction should always return a valid action.");
+ Debug.Assert(continuation != null, "GetCompletionAction should always return a valid action.");
// If this is our first await, such that we've not yet boxed the state machine, do so now.
if (m_coreState.m_stateMachine == null)
{
AsyncMethodBuilderCore.MoveNextRunner runnerToInitialize = null;
var continuation = m_coreState.GetCompletionAction(AsyncCausalityTracer.LoggingOn ? this.Task : null, ref runnerToInitialize);
- Contract.Assert(continuation != null, "GetCompletionAction should always return a valid action.");
+ Debug.Assert(continuation != null, "GetCompletionAction should always return a valid action.");
// If this is our first await, such that we've not yet boxed the state machine, do so now.
if (m_coreState.m_stateMachine == null)
if (task == null)
{
m_task = GetTaskForResult(result);
- Contract.Assert(m_task != null, "GetTaskForResult should never return null");
+ Debug.Assert(m_task != null, "GetTaskForResult should never return null");
}
// Slow path: complete the existing task.
else
/// <summary>Creates an array of cached tasks for the values in the range [INCLUSIVE_MIN,EXCLUSIVE_MAX).</summary>
private static Task<Int32>[] CreateInt32Tasks()
{
- Contract.Assert(EXCLUSIVE_INT32_MAX >= INCLUSIVE_INT32_MIN, "Expected max to be at least min");
+ Debug.Assert(EXCLUSIVE_INT32_MAX >= INCLUSIVE_INT32_MIN, "Expected max to be at least min");
var tasks = new Task<Int32>[EXCLUSIVE_INT32_MAX - INCLUSIVE_INT32_MIN];
for (int i = 0; i < tasks.Length; i++)
{
/// <returns>An Action to provide to the awaiter.</returns>
internal Action GetCompletionAction(Task taskForTracing, ref MoveNextRunner runnerToInitialize)
{
- Contract.Assert(m_defaultContextAction == null || m_stateMachine != null,
+ Debug.Assert(m_defaultContextAction == null || m_stateMachine != null,
"Expected non-null m_stateMachine on non-null m_defaultContextAction");
// Alert a listening debugger that we can't make forward progress unless it slips threads.
action = m_defaultContextAction;
if (action != null)
{
- Contract.Assert(m_stateMachine != null, "If the delegate was set, the state machine should have been as well.");
+ Debug.Assert(m_stateMachine != null, "If the delegate was set, the state machine should have been as well.");
return action;
}
m_stateMachine = stateMachine;
m_stateMachine.SetStateMachine(m_stateMachine);
- Contract.Assert(runner.m_stateMachine == null, "The runner's state machine should not yet have been populated.");
- Contract.Assert(m_stateMachine != null, "The builder's state machine field should have been initialized.");
+ Debug.Assert(runner.m_stateMachine == null, "The runner's state machine should not yet have been populated.");
+ Debug.Assert(m_stateMachine != null, "The builder's state machine field should have been initialized.");
// Now that we have the state machine, store it into the runner that the action delegate points to.
// And return the action.
/// <summary>Invokes MoveNext under the provided context.</summary>
internal void RunWithCapturedContext()
{
- Contract.Assert(m_stateMachine != null, "The state machine must have been set before calling Run.");
+ Debug.Assert(m_stateMachine != null, "The state machine must have been set before calling Run.");
if (m_context != null)
{
/// <summary>Invokes MoveNext under the default context.</summary>
internal void RunWithDefaultContext()
{
- Contract.Assert(m_stateMachine != null, "The state machine must have been set before calling Run.");
+ Debug.Assert(m_stateMachine != null, "The state machine must have been set before calling Run.");
ExecutionContext.Run(ExecutionContext.PreAllocatedDefault, InvokeMoveNextCallback, m_stateMachine, preserveSyncCtx: true);
}
// Note: If you add a new ctor overloads you need to update ParameterInfo.RawDefaultValue
using System.Reflection;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Collections.Generic;
if (namedArgument.MemberInfo.Name.Equals("Value"))
{
// This is not possible because Decimal cannot be represented directly in the metadata.
- Contract.Assert(false, "Decimal cannot be represented directly in the metadata.");
+ Debug.Assert(false, "Decimal cannot be represented directly in the metadata.");
return (Decimal)namedArgument.TypedValue.Value;
}
}
ParameterInfo[] parameters = attr.Constructor.GetParameters();
- Contract.Assert(parameters.Length == 5);
+ Debug.Assert(parameters.Length == 5);
System.Collections.Generic.IList<CustomAttributeTypedArgument> args = attr.ConstructorArguments;
- Contract.Assert(args.Count == 5);
+ Debug.Assert(args.Count == 5);
if (parameters[2].ParameterType == typeof(uint))
{
if (!task.IsCompleted)
{
bool taskCompleted = task.InternalWait(Timeout.Infinite, default(CancellationToken));
- Contract.Assert(taskCompleted, "With an infinite timeout, the task should have always completed.");
+ Debug.Assert(taskCompleted, "With an infinite timeout, the task should have always completed.");
}
// Now that we're done, alert the debugger if so requested
if (oceEdi != null)
{
oceEdi.Throw();
- Contract.Assert(false, "Throw() should have thrown");
+ Debug.Assert(false, "Throw() should have thrown");
}
throw new TaskCanceledException(task);
if (edis.Count > 0)
{
edis[0].Throw();
- Contract.Assert(false, "Throw() should have thrown");
+ Debug.Assert(false, "Throw() should have thrown");
break; // Necessary to compile: non-reachable, but compiler can't determine that
}
else
{
- Contract.Assert(false, "There should be exceptions if we're Faulted.");
+ Debug.Assert(false, "There should be exceptions if we're Faulted.");
throw task.Exception;
}
}
using System.Threading;
using System.Runtime;
using System.Runtime.Versioning;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Security;
static internal T UnsafeCast<T>(Object o) where T : class
{
T ret = UnsafeCastInternal<T>(o);
- Contract.Assert(ret == (o as T), "Invalid use of JitHelpers.UnsafeCast!");
+ Debug.Assert(ret == (o as T), "Invalid use of JitHelpers.UnsafeCast!");
return ret;
}
static internal int UnsafeEnumCast<T>(T val) where T : struct // Actually T must be 4 byte (or less) enum
{
- Contract.Assert(typeof(T).IsEnum
+ Debug.Assert(typeof(T).IsEnum
&& (Enum.GetUnderlyingType(typeof(T)) == typeof(int)
|| Enum.GetUnderlyingType(typeof(T)) == typeof(uint)
|| Enum.GetUnderlyingType(typeof(T)) == typeof(short)
static internal long UnsafeEnumCastLong<T>(T val) where T : struct // Actually T must be 8 byte enum
{
- Contract.Assert(typeof(T).IsEnum
+ Debug.Assert(typeof(T).IsEnum
&& (Enum.GetUnderlyingType(typeof(T)) == typeof(long)
|| Enum.GetUnderlyingType(typeof(T)) == typeof(ulong)),
"Error, T must be an 8 byte enum JitHelpers.UnsafeEnumCastLong!");
static internal IntPtr UnsafeCastToStackPointer<T>(ref T val)
{
IntPtr p = UnsafeCastToStackPointerInternal<T>(ref val);
- Contract.Assert(IsAddressInStack(p), "Pointer not in the stack!");
+ Debug.Assert(IsAddressInStack(p), "Pointer not in the stack!");
return p;
}
using System;
using System.Reflection;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[AttributeUsage(AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
{
// The user may have supplied a bad type name string causing this TypeLoadException
// Regardless, we return the bad type name
- Contract.Assert(marshalTypeName != null);
+ Debug.Assert(marshalTypeName != null);
}
return new MarshalAsAttribute(
using System.Runtime.Versioning;
using Win32Native = Microsoft.Win32.Win32Native;
using Microsoft.Win32.SafeHandles;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices.ComTypes;
{
// Retrieve the PROGID string from the ProgIdAttribute.
IList<CustomAttributeTypedArgument> caConstructorArgs = cas[i].ConstructorArguments;
- Contract.Assert(caConstructorArgs.Count == 1, "caConstructorArgs.Count == 1");
+ Debug.Assert(caConstructorArgs.Count == 1, "caConstructorArgs.Count == 1");
CustomAttributeTypedArgument progIdConstructorArg = caConstructorArgs[0];
- Contract.Assert(progIdConstructorArg.ArgumentType == typeof(String), "progIdConstructorArg.ArgumentType == typeof(String)");
+ Debug.Assert(progIdConstructorArg.ArgumentType == typeof(String), "progIdConstructorArg.ArgumentType == typeof(String)");
String strProgId = (String)progIdConstructorArg.Value;
using System.Runtime.CompilerServices;
using System.Globalization;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[Flags]
// If the type is derived from a tdImport class and has the same GUID as the
// imported class, then it represents a COM type.
Type baseComImportType = GetBaseComImportType(type);
- Contract.Assert(baseComImportType != null, "baseComImportType != null");
+ Debug.Assert(baseComImportType != null, "baseComImportType != null");
if (Marshal.GenerateGuidForType(type) == Marshal.GenerateGuidForType(baseComImportType))
return true;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using Microsoft.Win32.SafeHandles;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private static InvalidOperationException NotInitialized()
{
- Contract.Assert(false, "Uninitialized SafeBuffer! Someone needs to call Initialize before using this instance!");
+ Debug.Assert(false, "Uninitialized SafeBuffer! Someone needs to call Initialize before using this instance!");
return new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MustCallInitialize"));
}
using System.Reflection.Emit;
using System.Collections;
using System.Threading;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
internal class EventProviderWriter
// Find the delegate on the event sink helper.
FieldInfo DelegateField = SinkHelperClass.GetField( "m_" + SrcItfMethod.Name + "Delegate" );
- Contract.Assert(DelegateField != null, "Unable to find the field m_" + SrcItfMethod.Name + "Delegate on the sink helper");
+ Debug.Assert(DelegateField != null, "Unable to find the field m_" + SrcItfMethod.Name + "Delegate on the sink helper");
// Find the cookie on the event sink helper.
FieldInfo CookieField = SinkHelperClass.GetField( "m_dwCookie" );
- Contract.Assert(CookieField != null, "Unable to find the field m_dwCookie on the sink helper");
+ Debug.Assert(CookieField != null, "Unable to find the field m_dwCookie on the sink helper");
// Retrieve the sink helper's constructor.
ConstructorInfo SinkHelperCons = SinkHelperClass.GetConstructor(EventProviderWriter.DefaultLookup | BindingFlags.NonPublic, null, Array.Empty<Type>(), null );
- Contract.Assert(SinkHelperCons != null, "Unable to find the constructor for the sink helper");
+ Debug.Assert(SinkHelperCons != null, "Unable to find the constructor for the sink helper");
// Retrieve the IConnectionPoint.Advise method.
MethodInfo CPAdviseMethod = typeof(IConnectionPoint).GetMethod( "Advise" );
- Contract.Assert(CPAdviseMethod != null, "Unable to find the method ConnectionPoint.Advise");
+ Debug.Assert(CPAdviseMethod != null, "Unable to find the method ConnectionPoint.Advise");
// Retrieve the ArrayList.Add method.
aParamTypes = new Type[1];
aParamTypes[0] = typeof(Object);
MethodInfo ArrayListAddMethod = typeof(ArrayList).GetMethod( "Add", aParamTypes, null );
- Contract.Assert(ArrayListAddMethod != null, "Unable to find the method ArrayList.Add");
+ Debug.Assert(ArrayListAddMethod != null, "Unable to find the method ArrayList.Add");
// Retrieve the Monitor.Enter() method.
MethodInfo MonitorEnterMethod = typeof(Monitor).GetMethod( "Enter", MonitorEnterParamTypes, null );
- Contract.Assert(MonitorEnterMethod != null, "Unable to find the method Monitor.Enter()");
+ Debug.Assert(MonitorEnterMethod != null, "Unable to find the method Monitor.Enter()");
// Retrieve the Monitor.Exit() method.
aParamTypes[0] = typeof(Object);
MethodInfo MonitorExitMethod = typeof(Monitor).GetMethod( "Exit", aParamTypes, null );
- Contract.Assert(MonitorExitMethod != null, "Unable to find the method Monitor.Exit()");
+ Debug.Assert(MonitorExitMethod != null, "Unable to find the method Monitor.Exit()");
// Define the add_XXX method.
Type[] parameterTypes;
// Find the delegate on the event sink helper.
FieldInfo DelegateField = SinkHelperClass.GetField( "m_" + SrcItfMethod.Name + "Delegate" );
- Contract.Assert(DelegateField != null, "Unable to find the field m_" + SrcItfMethod.Name + "Delegate on the sink helper");
+ Debug.Assert(DelegateField != null, "Unable to find the field m_" + SrcItfMethod.Name + "Delegate on the sink helper");
// Find the cookie on the event sink helper.
FieldInfo CookieField = SinkHelperClass.GetField( "m_dwCookie" );
- Contract.Assert(CookieField != null, "Unable to find the field m_dwCookie on the sink helper");
+ Debug.Assert(CookieField != null, "Unable to find the field m_dwCookie on the sink helper");
// Retrieve the ArrayList.RemoveAt method.
aParamTypes = new Type[1];
aParamTypes[0] = typeof(Int32);
MethodInfo ArrayListRemoveMethod = typeof(ArrayList).GetMethod( "RemoveAt", aParamTypes, null );
- Contract.Assert(ArrayListRemoveMethod != null, "Unable to find the method ArrayList.RemoveAt()");
+ Debug.Assert(ArrayListRemoveMethod != null, "Unable to find the method ArrayList.RemoveAt()");
// Retrieve the ArrayList.Item property get method.
PropertyInfo ArrayListItemProperty = typeof(ArrayList).GetProperty( "Item" );
- Contract.Assert(ArrayListItemProperty != null, "Unable to find the property ArrayList.Item");
+ Debug.Assert(ArrayListItemProperty != null, "Unable to find the property ArrayList.Item");
MethodInfo ArrayListItemGetMethod = ArrayListItemProperty.GetGetMethod();
- Contract.Assert(ArrayListItemGetMethod != null, "Unable to find the get method for property ArrayList.Item");
+ Debug.Assert(ArrayListItemGetMethod != null, "Unable to find the get method for property ArrayList.Item");
// Retrieve the ArrayList.Count property get method.
PropertyInfo ArrayListSizeProperty = typeof(ArrayList).GetProperty( "Count" );
- Contract.Assert(ArrayListSizeProperty != null, "Unable to find the property ArrayList.Count");
+ Debug.Assert(ArrayListSizeProperty != null, "Unable to find the property ArrayList.Count");
MethodInfo ArrayListSizeGetMethod = ArrayListSizeProperty.GetGetMethod();
- Contract.Assert(ArrayListSizeGetMethod != null, "Unable to find the get method for property ArrayList.Count");
+ Debug.Assert(ArrayListSizeGetMethod != null, "Unable to find the get method for property ArrayList.Count");
// Retrieve the Delegate.Equals() method.
aParamTypes[0] = typeof(Delegate);
MethodInfo DelegateEqualsMethod = typeof(Delegate).GetMethod( "Equals", aParamTypes, null );
- Contract.Assert(DelegateEqualsMethod != null, "Unable to find the method Delegate.Equlals()");
+ Debug.Assert(DelegateEqualsMethod != null, "Unable to find the method Delegate.Equlals()");
// Retrieve the Monitor.Enter() method.
MethodInfo MonitorEnterMethod = typeof(Monitor).GetMethod("Enter", MonitorEnterParamTypes, null);
- Contract.Assert(MonitorEnterMethod != null, "Unable to find the method Monitor.Enter()");
+ Debug.Assert(MonitorEnterMethod != null, "Unable to find the method Monitor.Enter()");
// Retrieve the Monitor.Exit() method.
aParamTypes[0] = typeof(Object);
MethodInfo MonitorExitMethod = typeof(Monitor).GetMethod( "Exit", aParamTypes, null );
- Contract.Assert(MonitorExitMethod != null, "Unable to find the method Monitor.Exit()");
+ Debug.Assert(MonitorExitMethod != null, "Unable to find the method Monitor.Exit()");
// Retrieve the ConnectionPoint.Unadvise() method.
MethodInfo CPUnadviseMethod = typeof(IConnectionPoint).GetMethod( "Unadvise" );
- Contract.Assert(CPUnadviseMethod != null, "Unable to find the method ConnectionPoint.Unadvise()");
+ Debug.Assert(CPUnadviseMethod != null, "Unable to find the method ConnectionPoint.Unadvise()");
// Retrieve the Marshal.ReleaseComObject() method.
MethodInfo ReleaseComObjectMethod = typeof(Marshal).GetMethod( "ReleaseComObject" );
- Contract.Assert(ReleaseComObjectMethod != null, "Unable to find the method Marshal.ReleaseComObject()");
+ Debug.Assert(ReleaseComObjectMethod != null, "Unable to find the method Marshal.ReleaseComObject()");
// Define the remove_XXX method.
Type[] parameterTypes;
{
// Retrieve the constructor info for the array list's default constructor.
ConstructorInfo DefaultArrayListCons = typeof(ArrayList).GetConstructor(EventProviderWriter.DefaultLookup, null, Array.Empty<Type>(), null );
- Contract.Assert(DefaultArrayListCons != null, "Unable to find the constructor for class ArrayList");
+ Debug.Assert(DefaultArrayListCons != null, "Unable to find the constructor for class ArrayList");
// Temp byte array for Guid
ubyte[] rgByteGuid = new ubyte[16];
Type[] aParamTypes = new Type[1];
aParamTypes[0] = typeof(Byte[]);
ConstructorInfo ByteArrayGUIDCons = typeof(Guid).GetConstructor(EventProviderWriter.DefaultLookup, null, aParamTypes, null );
- Contract.Assert(ByteArrayGUIDCons != null, "Unable to find the constructor for GUID that accepts a string as argument");
+ Debug.Assert(ByteArrayGUIDCons != null, "Unable to find the constructor for GUID that accepts a string as argument");
// Retrieve the IConnectionPointContainer.FindConnectionPoint() method.
MethodInfo CPCFindCPMethod = typeof(IConnectionPointContainer).GetMethod( "FindConnectionPoint" );
- Contract.Assert(CPCFindCPMethod != null, "Unable to find the method ConnectionPointContainer.FindConnectionPoint()");
+ Debug.Assert(CPCFindCPMethod != null, "Unable to find the method ConnectionPointContainer.FindConnectionPoint()");
// Define the Init method itself.
MethodBuilder Meth = OutputTypeBuilder.DefineMethod(
{
// Retrieve the constructor info for the base class's constructor.
ConstructorInfo DefaultBaseClsCons = typeof(Object).GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, Array.Empty<Type>(), null );
- Contract.Assert(DefaultBaseClsCons != null, "Unable to find the object's public default constructor");
+ Debug.Assert(DefaultBaseClsCons != null, "Unable to find the object's public default constructor");
// Define the default constructor.
MethodAttributes ctorAttributes = MethodAttributes.SpecialName | (DefaultBaseClsCons.Attributes & MethodAttributes.MemberAccessMask);
{
// Find the cookie on the event sink helper.
FieldInfo CookieField = SinkHelperClass.GetField( "m_dwCookie" );
- Contract.Assert(CookieField != null, "Unable to find the field m_dwCookie on the sink helper");
+ Debug.Assert(CookieField != null, "Unable to find the field m_dwCookie on the sink helper");
// Retrieve the ArrayList.Item property get method.
PropertyInfo ArrayListItemProperty = typeof(ArrayList).GetProperty( "Item" );
- Contract.Assert(ArrayListItemProperty != null, "Unable to find the property ArrayList.Item");
+ Debug.Assert(ArrayListItemProperty != null, "Unable to find the property ArrayList.Item");
MethodInfo ArrayListItemGetMethod = ArrayListItemProperty.GetGetMethod();
- Contract.Assert(ArrayListItemGetMethod != null, "Unable to find the get method for property ArrayList.Item");
+ Debug.Assert(ArrayListItemGetMethod != null, "Unable to find the get method for property ArrayList.Item");
// Retrieve the ArrayList.Count property get method.
PropertyInfo ArrayListSizeProperty = typeof(ArrayList).GetProperty( "Count" );
- Contract.Assert(ArrayListSizeProperty != null, "Unable to find the property ArrayList.Count");
+ Debug.Assert(ArrayListSizeProperty != null, "Unable to find the property ArrayList.Count");
MethodInfo ArrayListSizeGetMethod = ArrayListSizeProperty.GetGetMethod();
- Contract.Assert(ArrayListSizeGetMethod != null, "Unable to find the get method for property ArrayList.Count");
+ Debug.Assert(ArrayListSizeGetMethod != null, "Unable to find the get method for property ArrayList.Count");
// Retrieve the ConnectionPoint.Unadvise() method.
MethodInfo CPUnadviseMethod = typeof(IConnectionPoint).GetMethod( "Unadvise" );
- Contract.Assert(CPUnadviseMethod != null, "Unable to find the method ConnectionPoint.Unadvise()");
+ Debug.Assert(CPUnadviseMethod != null, "Unable to find the method ConnectionPoint.Unadvise()");
// Retrieve the Marshal.ReleaseComObject() method.
MethodInfo ReleaseComObjectMethod = typeof(Marshal).GetMethod( "ReleaseComObject" );
- Contract.Assert(ReleaseComObjectMethod != null, "Unable to find the method Marshal.ReleaseComObject()");
+ Debug.Assert(ReleaseComObjectMethod != null, "Unable to find the method Marshal.ReleaseComObject()");
// Retrieve the Monitor.Enter() method.
MethodInfo MonitorEnterMethod = typeof(Monitor).GetMethod("Enter", MonitorEnterParamTypes, null);
- Contract.Assert(MonitorEnterMethod != null, "Unable to find the method Monitor.Enter()");
+ Debug.Assert(MonitorEnterMethod != null, "Unable to find the method Monitor.Enter()");
// Retrieve the Monitor.Exit() method.
Type[] aParamTypes = new Type[1];
aParamTypes[0] = typeof(Object);
MethodInfo MonitorExitMethod = typeof(Monitor).GetMethod( "Exit", aParamTypes, null );
- Contract.Assert(MonitorExitMethod != null, "Unable to find the method Monitor.Exit()");
+ Debug.Assert(MonitorExitMethod != null, "Unable to find the method Monitor.Exit()");
// Define the Finalize method itself.
MethodBuilder Meth = OutputTypeBuilder.DefineMethod( "Finalize", MethodAttributes.Public | MethodAttributes.Virtual, null, null );
{
// Retrieve the method info for GC.SuppressFinalize().
MethodInfo SuppressFinalizeMethod = typeof(GC).GetMethod("SuppressFinalize");
- Contract.Assert(SuppressFinalizeMethod != null, "Unable to find the GC.SuppressFinalize");
+ Debug.Assert(SuppressFinalizeMethod != null, "Unable to find the GC.SuppressFinalize");
// Define the Finalize method itself.
MethodBuilder Meth = OutputTypeBuilder.DefineMethod( "Dispose", MethodAttributes.Public | MethodAttributes.Virtual, null, null );
using System.Reflection;
using System.Reflection.Emit;
using System.Collections;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
internal class EventSinkHelperWriter
{
// Retrieve the delegate type from the add_XXX method.
MethodInfo AddMeth = m_EventItfType.GetMethod( "add_" + aMethods[cMethods].Name );
ParameterInfo[] aParams = AddMeth.GetParameters();
- Contract.Assert(aParams.Length == 1, "All event interface methods must take a single delegate derived type and have a void return type");
+ Debug.Assert(aParams.Length == 1, "All event interface methods must take a single delegate derived type and have a void return type");
Type DelegateCls = aParams[0].ParameterType;
// Define the delegate instance field.
{
// Retrieve the method info for the invoke method on the delegate.
MethodInfo DelegateInvokeMethod = DelegateCls.GetMethod( "Invoke" );
- Contract.Assert(DelegateInvokeMethod != null, "Unable to find method Delegate.Invoke()");
+ Debug.Assert(DelegateInvokeMethod != null, "Unable to find method Delegate.Invoke()");
// Retrieve the return type.
Type ReturnType = Method.ReturnType;
if ( ReturnType == typeof(IntPtr) )
il.Emit( OpCodes.Ldc_I4_0 );
else
- Contract.Assert(false, "Unexpected type for Primitive type.");
+ Debug.Assert(false, "Unexpected type for Primitive type.");
break;
}
}
{
// Retrieve the constructor info for the base classe's constructor.
ConstructorInfo DefaultBaseClsCons = typeof(Object).GetConstructor(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public, null, Array.Empty<Type>(), null );
- Contract.Assert(DefaultBaseClsCons != null, "Unable to find the constructor for class " + m_InputType.Name);
+ Debug.Assert(DefaultBaseClsCons != null, "Unable to find the constructor for class " + m_InputType.Name);
// Define the default constructor.
MethodBuilder Cons = OutputTypeBuilder.DefineMethod( ".ctor",
using System.Security;
using System.Collections;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
{
private BindableVectorToCollectionAdapter()
{
- Contract.Assert(false, "This class is never instantiated");
+ Debug.Assert(false, "This class is never instantiated");
}
// int Count { get }
using System.Security;
using System.Collections;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
{
private BindableVectorToListAdapter()
{
- Contract.Assert(false, "This class is never instantiated");
+ Debug.Assert(false, "This class is never instantiated");
}
// object this[int index] { get }
using System;
using System.Collections;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Reflection;
using System.Security;
{
Contract.Requires(wrapper != null);
IReference<T> reference = (IReference<T>) wrapper;
- Contract.Assert(reference != null, "CLRIReferenceImpl::UnboxHelper - QI'ed for IReference<"+typeof(T)+">, but that failed.");
+ Debug.Assert(reference != null, "CLRIReferenceImpl::UnboxHelper - QI'ed for IReference<"+typeof(T)+">, but that failed.");
return reference.Value;
}
}
{
Contract.Requires(wrapper != null);
IReferenceArray<T> reference = (IReferenceArray<T>)wrapper;
- Contract.Assert(reference != null, "CLRIReferenceArrayImpl::UnboxHelper - QI'ed for IReferenceArray<" + typeof(T) + ">, but that failed.");
+ Debug.Assert(reference != null, "CLRIReferenceArrayImpl::UnboxHelper - QI'ed for IReferenceArray<" + typeof(T) + ">, but that failed.");
T[] marshaled = reference.Value;
return marshaled;
}
return Activator.CreateInstance(specificType, new Object[] { propType.Value, obj });
}
- Contract.Assert(false, "We should not see non-WinRT type here");
+ Debug.Assert(false, "We should not see non-WinRT type here");
return null;
}
Type type = obj.GetType().GetElementType();
- Contract.Assert(obj.Rank == 1 && obj.GetLowerBound(0) == 0 && !type.IsArray);
+ Debug.Assert(obj.Rank == 1 && obj.GetLowerBound(0) == 0 && !type.IsArray);
if (type == typeof(int))
return new CLRIReferenceArrayImpl<int>(PropertyType.Int32Array, (int[])obj);
using System;
using System.Security;
using System.Reflection;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
// We can safely skip access check because this is only used in full trust scenarios.
// And we have already verified that the property accessor is public.
- Contract.Assert(AppDomain.CurrentDomain.PermissionSet.IsUnrestricted());
+ Debug.Assert(AppDomain.CurrentDomain.PermissionSet.IsUnrestricted());
return rtMethod.UnsafeInvoke(target, BindingFlags.Default, null, args, null);
}
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
{
private DictionaryToMapAdapter()
{
- Contract.Assert(false, "This class is never instantiated");
+ Debug.Assert(false, "This class is never instantiated");
}
// V Lookup(K key)
internal IReadOnlyDictionary<K, V> GetView<K, V>()
{
IDictionary<K, V> _this = JitHelpers.UnsafeCast<IDictionary<K, V>>(this);
- Contract.Assert(_this != null);
+ Debug.Assert(_this != null);
// Note: This dictionary is not really read-only - you could QI for a modifiable
// dictionary. We gain some perf by doing this. We believe this is acceptable.
using System;
using System.Collections;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
{
private EnumerableToIterableAdapter()
{
- Contract.Assert(false, "This class is never instantiated");
+ Debug.Assert(false, "This class is never instantiated");
}
// This method is invoked when First is called on a managed implementation of IIterable<T>.
{
private EnumerableToBindableIterableAdapter()
{
- Contract.Assert(false, "This class is never instantiated");
+ Debug.Assert(false, "This class is never instantiated");
}
internal sealed class NonGenericToGenericEnumerator : IEnumerator<object>
using System;
using System.Security;
using System.Collections;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
{
private IDisposableToIClosableAdapter()
{
- Contract.Assert(false, "This class is never instantiated");
+ Debug.Assert(false, "This class is never instantiated");
}
public void Close()
{
private IClosableToIDisposableAdapter()
{
- Contract.Assert(false, "This class is never instantiated");
+ Debug.Assert(false, "This class is never instantiated");
}
private void Dispose()
{
private IMapViewToIReadOnlyDictionaryAdapter()
{
- Contract.Assert(false, "This class is never instantiated");
+ Debug.Assert(false, "This class is never instantiated");
}
// V this[K key] { get }
{
private IReadOnlyDictionaryToIMapViewAdapter()
{
- Contract.Assert(false, "This class is never instantiated");
+ Debug.Assert(false, "This class is never instantiated");
}
// V Lookup(K key)
{
private IReadOnlyListToIVectorViewAdapter()
{
- Contract.Assert(false, "This class is never instantiated");
+ Debug.Assert(false, "This class is never instantiated");
}
// T GetAt(uint index)
{
private IVectorViewToIReadOnlyListAdapter()
{
- Contract.Assert(false, "This class is never instantiated");
+ Debug.Assert(false, "This class is never instantiated");
}
// T this[int index] { get }
using System;
using System.Collections;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
{
private IterableToEnumerableAdapter()
{
- Contract.Assert(false, "This class is never instantiated");
+ Debug.Assert(false, "This class is never instantiated");
}
// This method is invoked when GetEnumerator is called on a WinRT-backed implementation of IEnumerable<T>.
{
private BindableIterableToEnumerableAdapter()
{
- Contract.Assert(false, "This class is never instantiated");
+ Debug.Assert(false, "This class is never instantiated");
}
private sealed class NonGenericToGenericIterator : IIterator<object>
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
{
private ListToBindableVectorAdapter()
{
- Contract.Assert(false, "This class is never instantiated");
+ Debug.Assert(false, "This class is never instantiated");
}
// object GetAt(uint index)
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
{
private ListToVectorAdapter()
{
- Contract.Assert(false, "This class is never instantiated");
+ Debug.Assert(false, "This class is never instantiated");
}
// T GetAt(uint index)
internal IReadOnlyList<T> GetView<T>()
{
IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this);
- Contract.Assert(_this != null);
+ Debug.Assert(_this != null);
// Note: This list is not really read-only - you could QI for a modifiable
// list. We gain some perf by doing this. We believe this is acceptable.
using System.Security;
using System.Collections;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
{
private MapToCollectionAdapter()
{
- Contract.Assert(false, "This class is never instantiated");
+ Debug.Assert(false, "This class is never instantiated");
}
// int Count { get }
using System.Security;
using System.Collections;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
{
private MapToDictionaryAdapter()
{
- Contract.Assert(false, "This class is never instantiated");
+ Debug.Assert(false, "This class is never instantiated");
}
// V this[K key] { get }
using System.Security;
using System.Collections;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
{
private MapViewToReadOnlyCollectionAdapter()
{
- Contract.Assert(false, "This class is never instantiated");
+ Debug.Assert(false, "This class is never instantiated");
}
// int Count { get }
using System.Security;
using System.Collections;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
{
private VectorToCollectionAdapter()
{
- Contract.Assert(false, "This class is never instantiated");
+ Debug.Assert(false, "This class is never instantiated");
}
// int Count { get }
using System.Security;
using System.Collections;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
{
private VectorToListAdapter()
{
- Contract.Assert(false, "This class is never instantiated");
+ Debug.Assert(false, "This class is never instantiated");
}
// T this[int index] { get }
using System.Security;
using System.Collections;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
{
private VectorViewToReadOnlyCollectionAdapter()
{
- Contract.Assert(false, "This class is never instantiated");
+ Debug.Assert(false, "This class is never instantiated");
}
// int Count { get }
using System;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Reflection;
using System.Runtime.CompilerServices;
private static object GetInstanceKey(Action<EventRegistrationToken> removeMethod)
{
object target = removeMethod.Target;
- Contract.Assert(target == null || Marshal.IsComObject(target), "Must be null or a RCW");
+ Debug.Assert(target == null || Marshal.IsComObject(target), "Must be null or a RCW");
if (target == null)
return removeMethod.Method.DeclaringType;
// Note that inside TryGetValueWithValueEquality we assumes that any delegate
// with the same value equality would have the same hash code
object key = registrationTokens.FindEquivalentKeyUnsafe(handler, out tokens);
- Contract.Assert((key != null && tokens != null) || (key == null && tokens == null),
+ Debug.Assert((key != null && tokens != null) || (key == null && tokens == null),
"key and tokens must be both null or non-null");
if (tokens == null)
{
internal void ReleaseReaderLock()
{
EnterMyLock();
- Contract.Assert(owners > 0, "ReleasingReaderLock: releasing lock and no read lock taken");
+ Debug.Assert(owners > 0, "ReleasingReaderLock: releasing lock and no read lock taken");
--owners;
ExitAndWakeUpAppropriateWaiters();
}
internal void ReleaseWriterLock()
{
EnterMyLock();
- Contract.Assert(owners == -1, "Calling ReleaseWriterLock when no write lock is held");
+ Debug.Assert(owners == -1, "Calling ReleaseWriterLock when no write lock is held");
owners++;
ExitAndWakeUpAppropriateWaiters();
}
/// set 'waitEvent'
/// </summary>
private void LazyCreateEvent(ref EventWaitHandle waitEvent, bool makeAutoResetEvent) {
- Contract.Assert(myLock != 0, "Lock must be held");
- Contract.Assert(waitEvent == null, "Wait event must be null");
+ Debug.Assert(myLock != 0, "Lock must be held");
+ Debug.Assert(waitEvent == null, "Wait event must be null");
ExitMyLock();
EventWaitHandle newEvent;
/// </summary>
private void WaitOnEvent(EventWaitHandle waitEvent, ref uint numWaiters, int millisecondsTimeout)
{
- Contract.Assert(myLock != 0, "Lock must be held");
+ Debug.Assert(myLock != 0, "Lock must be held");
waitEvent.Reset();
numWaiters++;
/// </summary>
private void ExitAndWakeUpAppropriateWaiters()
{
- Contract.Assert(myLock != 0, "Lock must be held");
+ Debug.Assert(myLock != 0, "Lock must be held");
if (owners == 0 && numWriteWaiters > 0)
{
}
private void ExitMyLock()
{
- Contract.Assert(myLock != 0, "Exiting spin lock that is not held");
+ Debug.Assert(myLock != 0, "Exiting spin lock that is not held");
myLock = 0;
}
};
using System.Runtime.ConstrainedExecution;
using System.Security.Permissions;
using System.Runtime.Versioning;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
/*
break;
default:
- Contract.Assert(false, "Fell through switch statement!");
+ Debug.Assert(false, "Fell through switch statement!");
break;
}
}
using System.IO;
using System.Text;
using System.Globalization;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[System.Runtime.InteropServices.ComVisible(true)]
FieldInfo [] typeFields;
RuntimeType parentType;
- Contract.Assert((object)type != null, "[GetAllSerializableMembers]type!=null");
+ Debug.Assert((object)type != null, "[GetAllSerializableMembers]type!=null");
if (type.IsInterface) {
return new MemberInfo[0];
}
if (mi.MemberType==MemberTypes.Field) {
- Contract.Assert(mi is RuntimeFieldInfo || mi is SerializationFieldInfo,
+ Debug.Assert(mi is RuntimeFieldInfo || mi is SerializationFieldInfo,
"[FormatterServices.GetObjectData]mi is RuntimeFieldInfo || mi is SerializationFieldInfo.");
RtFieldInfo rfi = mi as RtFieldInfo;
using System;
using System.Reflection;
using System.Globalization;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Threading;
public override int MetadataToken { get { return m_field.MetadataToken; } }
internal SerializationFieldInfo(RuntimeFieldInfo field, String namePrefix) {
- Contract.Assert(field!=null, "[SerializationFieldInfo.ctor]field!=null");
- Contract.Assert(namePrefix!=null, "[SerializationFieldInfo.ctor]namePrefix!=null");
+ Debug.Assert(field!=null, "[SerializationFieldInfo.ctor]field!=null");
+ Debug.Assert(namePrefix!=null, "[SerializationFieldInfo.ctor]namePrefix!=null");
m_field = field;
m_serializationName = String.Concat(namePrefix, FakeNameSeparatorString, m_field.Name);
using System.Reflection;
using System.Runtime.Remoting;
using System.Globalization;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Security;
using System.Runtime.CompilerServices;
private void ExpandArrays()
{
int newSize;
- Contract.Assert(m_members.Length == m_currMember, "[SerializationInfo.ExpandArrays]m_members.Length == m_currMember");
+ Debug.Assert(m_members.Length == m_currMember, "[SerializationInfo.ExpandArrays]m_members.Length == m_currMember");
newSize = (m_currMember * 2);
// its ObjectManager implementation, but it should not be exposed out of a contract.
public void UpdateValue(String name, Object value, Type type)
{
- Contract.Assert(null != name, "[SerializationInfo.UpdateValue]name!=null");
- Contract.Assert(null != value, "[SerializationInfo.UpdateValue]value!=null");
- Contract.Assert(null != (object)type, "[SerializationInfo.UpdateValue]type!=null");
+ Debug.Assert(null != name, "[SerializationInfo.UpdateValue]name!=null");
+ Debug.Assert(null != value, "[SerializationInfo.UpdateValue]value!=null");
+ Debug.Assert(null != (object)type, "[SerializationInfo.UpdateValue]type!=null");
int index = FindElement(name);
if (index < 0)
throw new SerializationException(Environment.GetResourceString("Serialization_NotFound", name));
}
- Contract.Assert(index < m_data.Length, "[SerializationInfo.GetElement]index<m_data.Length");
- Contract.Assert(index < m_types.Length, "[SerializationInfo.GetElement]index<m_types.Length");
+ Debug.Assert(index < m_data.Length, "[SerializationInfo.GetElement]index<m_data.Length");
+ Debug.Assert(index < m_types.Length, "[SerializationInfo.GetElement]index<m_types.Length");
foundType = m_types[index];
- Contract.Assert((object)foundType != null, "[SerializationInfo.GetElement]foundType!=null");
+ Debug.Assert((object)foundType != null, "[SerializationInfo.GetElement]foundType!=null");
return m_data[index];
}
return null;
}
- Contract.Assert(index < m_data.Length, "[SerializationInfo.GetElement]index<m_data.Length");
- Contract.Assert(index < m_types.Length, "[SerializationInfo.GetElement]index<m_types.Length");
+ Debug.Assert(index < m_data.Length, "[SerializationInfo.GetElement]index<m_data.Length");
+ Debug.Assert(index < m_types.Length, "[SerializationInfo.GetElement]index<m_types.Length");
foundType = m_types[index];
- Contract.Assert((object)foundType != null, "[SerializationInfo.GetElement]foundType!=null");
+ Debug.Assert((object)foundType != null, "[SerializationInfo.GetElement]foundType!=null");
return m_data[index];
}
return value;
}
- Contract.Assert(m_converter != null, "[SerializationInfo.GetValue]m_converter!=null");
+ Debug.Assert(m_converter != null, "[SerializationInfo.GetValue]m_converter!=null");
return m_converter.Convert(value, type);
}
Type foundType;
Object value;
- Contract.Assert((object)type != null, "[SerializationInfo.GetValue]type ==null");
- Contract.Assert(type is RuntimeType, "[SerializationInfo.GetValue]type is not a runtime type");
+ Debug.Assert((object)type != null, "[SerializationInfo.GetValue]type ==null");
+ Debug.Assert(type is RuntimeType, "[SerializationInfo.GetValue]type is not a runtime type");
value = GetElementNoThrow(name, out foundType);
if (value == null)
return value;
}
- Contract.Assert(m_converter != null, "[SerializationInfo.GetValue]m_converter!=null");
+ Debug.Assert(m_converter != null, "[SerializationInfo.GetValue]m_converter!=null");
return m_converter.Convert(value, type);
}
============================================================*/
namespace System.Runtime.Serialization {
using System;
+ using System.Diagnostics;
using System.Collections;
using System.Diagnostics.Contracts;
bool m_current;
internal SerializationInfoEnumerator(String[] members, Object[] info, Type[] types, int numItems) {
- Contract.Assert(members!=null, "[SerializationInfoEnumerator.ctor]members!=null");
- Contract.Assert(info!=null, "[SerializationInfoEnumerator.ctor]info!=null");
- Contract.Assert(types!=null, "[SerializationInfoEnumerator.ctor]types!=null");
- Contract.Assert(numItems>=0, "[SerializationInfoEnumerator.ctor]numItems>=0");
- Contract.Assert(members.Length>=numItems, "[SerializationInfoEnumerator.ctor]members.Length>=numItems");
- Contract.Assert(info.Length>=numItems, "[SerializationInfoEnumerator.ctor]info.Length>=numItems");
- Contract.Assert(types.Length>=numItems, "[SerializationInfoEnumerator.ctor]types.Length>=numItems");
+ Debug.Assert(members!=null, "[SerializationInfoEnumerator.ctor]members!=null");
+ Debug.Assert(info!=null, "[SerializationInfoEnumerator.ctor]info!=null");
+ Debug.Assert(types!=null, "[SerializationInfoEnumerator.ctor]types!=null");
+ Debug.Assert(numItems>=0, "[SerializationInfoEnumerator.ctor]numItems>=0");
+ Debug.Assert(members.Length>=numItems, "[SerializationInfoEnumerator.ctor]members.Length>=numItems");
+ Debug.Assert(info.Length>=numItems, "[SerializationInfoEnumerator.ctor]info.Length>=numItems");
+ Debug.Assert(types.Length>=numItems, "[SerializationInfoEnumerator.ctor]types.Length>=numItems");
m_members = members;
m_data = info;
//
using System;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Security.Permissions;
using Microsoft.Win32;
private static NamedPermissionSet GetOrDeserializePermissionSet(ref NamedPermissionSet permissionSet,
string permissionSetXml)
{
- Contract.Assert(!String.IsNullOrEmpty(permissionSetXml));
+ Debug.Assert(!String.IsNullOrEmpty(permissionSetXml));
return permissionSet.Copy() as NamedPermissionSet;
}
}
using System.Collections;
using System.Text;
using System;
- using System.Diagnostics;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using IUnrestrictedPermission = System.Security.Permissions.IUnrestrictedPermission;
// without having to create objects.
// The security annotation fxcop rule that flags all methods with a Demand() has logic
// which checks for methods named Demand in types that implement IPermission or IStackWalk.
- Contract.Assert(new StackFrame().GetMethod().Name.Equals("Demand"), "This method needs to be named Demand");
+ Debug.Assert(new StackFrame().GetMethod().Name.Equals("Demand"), "This method needs to be named Demand");
StackCrawlMark stackMark = StackCrawlMark.LookForMyCallersCaller;
CodeAccessSecurityEngine.SpecialDemand(permissionType, ref stackMark);
// without having to new a PermissionSet.
// The security annotation fxcop rule that flags all methods with an Assert() has logic
// which checks for methods named Assert in types that implement IPermission or IStackWalk.
- Contract.Assert(new StackFrame().GetMethod().Name.Equals("Assert"), "This method needs to be named Assert");
+ Debug.Assert(new StackFrame().GetMethod().Name.Equals("Assert"), "This method needs to be named Assert");
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
SecurityRuntime.AssertAllPossible(ref stackMark);
internal bool CheckDemand(CodeAccessPermission grant)
{
- Contract.Assert( grant == null || grant.GetType().Equals( this.GetType() ), "CheckDemand not defined for permissions of different type" );
+ Debug.Assert( grant == null || grant.GetType().Equals( this.GetType() ), "CheckDemand not defined for permissions of different type" );
return IsSubsetOf( grant );
}
internal bool CheckPermitOnly(CodeAccessPermission permitted)
{
- Contract.Assert( permitted == null || permitted.GetType().Equals( this.GetType() ), "CheckPermitOnly not defined for permissions of different type" );
+ Debug.Assert( permitted == null || permitted.GetType().Equals( this.GetType() ), "CheckPermitOnly not defined for permissions of different type" );
return IsSubsetOf( permitted );
}
internal bool CheckDeny(CodeAccessPermission denied)
{
- Contract.Assert( denied == null || denied.GetType().Equals( this.GetType() ), "CheckDeny not defined for permissions of different type" );
+ Debug.Assert( denied == null || denied.GetType().Equals( this.GetType() ), "CheckDeny not defined for permissions of different type" );
IPermission intersectPerm = Intersect(denied);
return (intersectPerm == null || intersectPerm.IsSubsetOf(null));
}
internal bool CheckAssert(CodeAccessPermission asserted)
{
- Contract.Assert( asserted == null || asserted.GetType().Equals( this.GetType() ), "CheckPermitOnly not defined for permissions of different type" );
+ Debug.Assert( asserted == null || asserted.GetType().Equals( this.GetType() ), "CheckPermitOnly not defined for permissions of different type" );
return IsSubsetOf( asserted );
}
}
using System.Globalization;
using System.Security.Policy;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
// Used in DemandInternal, to remember the result of previous demands
private static void ThrowSecurityException(Object assemblyOrString, PermissionSet granted, PermissionSet refused, RuntimeMethodHandleInternal rmh, SecurityAction action, Object demand, IPermission permThatFailed)
#pragma warning restore 618
{
- Contract.Assert((assemblyOrString == null || assemblyOrString is RuntimeAssembly || assemblyOrString is String), "Must pass in an Assembly object or String object here");
+ Debug.Assert((assemblyOrString == null || assemblyOrString is RuntimeAssembly || assemblyOrString is String), "Must pass in an Assembly object or String object here");
if (assemblyOrString == null || assemblyOrString is RuntimeAssembly)
ThrowSecurityException((RuntimeAssembly)assemblyOrString, granted, refused, rmh, action, demand, permThatFailed);
// To reduce the amount of ifdef-code-churn, a dummy arg is used for the first parameter - instead of a CompressedStack object,
// we use a System.Object that should always be null. If we tried to change the signature of the function, there will need to be
// corresponding changes in VM (metasig.h, mscorlib.h, securitystackwalk.cpp, number of elements in the arg array, etc.)
- Contract.Assert(notUsed == null, "Should not reach here with a non-null first arg which is the CompressedStack");
+ Debug.Assert(notUsed == null, "Should not reach here with a non-null first arg which is the CompressedStack");
CheckSetHelper(grants, refused, demands, rmh, (Object)asm, action, true);
}
bool throwException)
#pragma warning restore 618
{
- Contract.Assert(demands != null, "Should not reach here with a null demand set");
+ Debug.Assert(demands != null, "Should not reach here with a null demand set");
IPermission permThatFailed = null;
if (grants != null)
// To reduce the amount of ifdef-code-churn, a dummy arg is used for the first parameter - instead of a CompressedStack object,
// we use a System.Object that should always be null. If we tried to change the signature of the function, there will need to be
// corresponding changes in VM (metasig.h, mscorlib.h, securitystackwalk.cpp, number of elements in the arg array, etc.)
- Contract.Assert(notUsed == null, "Should not reach here with a non-null first arg which is the CompressedStack");
+ Debug.Assert(notUsed == null, "Should not reach here with a non-null first arg which is the CompressedStack");
CheckHelper(grantedSet, refusedSet, demand, permToken, rmh, (Object)asm, action, true);
}
#endif // FEATURE_COMPRESSEDSTACK
#pragma warning restore 618
{
// We should never get here with a null demand
- Contract.Assert(demand != null, "Should not reach here with a null demand");
+ Debug.Assert(demand != null, "Should not reach here with a null demand");
if (permToken == null)
permToken = PermissionToken.GetToken(demand);
// If we aren't unrestricted, there is a refused set, or our permission is not of the unrestricted
// variety, we need to do the proper callback.
- Contract.Assert(demand != null,"demand != null");
+ Debug.Assert(demand != null,"demand != null");
// Find the permission of matching type in the permission set.
using System.Globalization;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
#if !FEATURE_PAL
using Microsoft.Win32.SafeHandles;
PermissionSet permSet;
// If the demand is null, there is no need to continue
- Contract.Assert(demand != null && !demand.CheckDemand(null), "Empty demands should have been filtered out by this point");
+ Debug.Assert(demand != null && !demand.CheckDemand(null), "Empty demands should have been filtered out by this point");
// decode imperative
if (GetPermitOnly(fDeclarative) != null)
using System.Threading;
using System.Collections;
using System.Collections.Generic;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[Serializable]
}
internal void UpdateDomainPLS (PermissionSet grantSet, PermissionSet deniedSet) {
- Contract.Assert(m_permSetTriples == null, "m_permSetTriples != null");
+ Debug.Assert(m_permSetTriples == null, "m_permSetTriples != null");
if (m_firstPermSetTriple == null)
m_firstPermSetTriple = new PermissionSetTriple();
internal bool CheckDemandNoThrow(CodeAccessPermission demand)
{
// AppDomain permissions - no asserts. So there should only be one triple to work with
- Contract.Assert(m_permSetTriples == null && m_firstPermSetTriple != null, "More than one PermissionSetTriple encountered in AD PermissionListSet");
+ Debug.Assert(m_permSetTriples == null && m_firstPermSetTriple != null, "More than one PermissionSetTriple encountered in AD PermissionListSet");
internal bool CheckSetDemandNoThrow(PermissionSet pSet)
{
// AppDomain permissions - no asserts. So there should only be one triple to work with
- Contract.Assert(m_permSetTriples == null && m_firstPermSetTriple != null, "More than one PermissionSetTriple encountered in AD PermissionListSet");
+ Debug.Assert(m_permSetTriples == null && m_firstPermSetTriple != null, "More than one PermissionSetTriple encountered in AD PermissionListSet");
return m_firstPermSetTriple.CheckSetDemandNoThrow(pSet);
/// <param name="flags">set of flags to check (See PermissionType)</param>
private bool CheckFlags(int flags)
{
- Contract.Assert(flags != 0, "Invalid permission flag demand");
+ Debug.Assert(flags != 0, "Invalid permission flag demand");
bool check = true;
using System.Text;
using System.Globalization;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[Serializable]
[OnSerialized]
private void OnSerialized(StreamingContext context)
{
- Contract.Assert(false, "PermissionSet does not support serialization on CoreCLR");
+ Debug.Assert(false, "PermissionSet does not support serialization on CoreCLR");
}
#endif // _DEBUG
IPermission targetPerm = target.GetPermission(i);
#if _DEBUG
PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i );
- Contract.Assert(targetPerm == null || (token.m_type & PermissionTokenType.DontKnow) == 0, "Token not properly initialized");
+ Debug.Assert(targetPerm == null || (token.m_type & PermissionTokenType.DontKnow) == 0, "Token not properly initialized");
#endif
if (target.m_Unrestricted)
internal void CheckDecoded( CodeAccessPermission demandedPerm, PermissionToken tokenDemandedPerm )
{
- Contract.Assert( demandedPerm != null, "Expected non-null value" );
+ Debug.Assert( demandedPerm != null, "Expected non-null value" );
if (this.m_allPermissionsDecoded || this.m_permSet == null)
return;
if (tokenDemandedPerm == null)
tokenDemandedPerm = PermissionToken.GetToken( demandedPerm );
- Contract.Assert( tokenDemandedPerm != null, "Unable to find token for demanded permission" );
+ Debug.Assert( tokenDemandedPerm != null, "Unable to find token for demanded permission" );
CheckDecoded( tokenDemandedPerm.m_index );
}
internal void CheckDecoded(PermissionSet demandedSet)
{
- Contract.Assert(demandedSet != null, "Expected non-null value");
+ Debug.Assert(demandedSet != null, "Expected non-null value");
if (this.m_allPermissionsDecoded || this.m_permSet == null)
return;
if ((token.m_type & PermissionTokenType.IUnrestricted) != 0)
{
this.m_permSet.SetItem( i, otherPerm.Copy() );
- Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
+ Debug.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
}
}
}
if ((token.m_type & PermissionTokenType.IUnrestricted) != 0)
{
pset.m_permSet.SetItem( i, otherPerm.Copy() );
- Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
+ Debug.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
}
}
}
if ((token.m_type & PermissionTokenType.IUnrestricted) != 0)
{
pset.m_permSet.SetItem( i, thisPerm.Copy() );
- Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
+ Debug.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
}
}
}
else
intersectPerm = thisPerm.Intersect( otherPerm );
pset.m_permSet.SetItem( i, intersectPerm );
- Contract.Assert( intersectPerm == null || PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
+ Debug.Assert( intersectPerm == null || PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
}
}
if (((token.m_type & PermissionTokenType.IUnrestricted) == 0) || !pset.m_Unrestricted)
{
pset.m_permSet.SetItem( i, otherPerm.Copy() );
- Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
+ Debug.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
}
}
}
if (((token.m_type & PermissionTokenType.IUnrestricted) == 0) || !pset.m_Unrestricted)
{
pset.m_permSet.SetItem( i, thisPerm.Copy() );
- Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
+ Debug.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
}
}
}
else
unionPerm = thisPerm.Union( otherPerm );
pset.m_permSet.SetItem( i, unionPerm );
- Contract.Assert( unionPerm == null || PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
+ Debug.Assert( unionPerm == null || PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
}
}
// Internal routine used by CreateSerialized to add a permission to the set
private static void MergePermission(IPermission perm, bool separateCasFromNonCas, ref PermissionSet casPset, ref PermissionSet nonCasPset)
{
- Contract.Assert(casPset == null || !casPset.IsReadOnly);
- Contract.Assert(nonCasPset == null || !nonCasPset.IsReadOnly);
+ Debug.Assert(casPset == null || !casPset.IsReadOnly);
+ Debug.Assert(nonCasPset == null || !nonCasPset.IsReadOnly);
if (perm == null)
return;
for (int i = 0; i < attrs.Length; i++)
{
#pragma warning disable 618
- Contract.Assert(i == 0 || ((SecurityAttribute)attrs[i]).m_action == ((SecurityAttribute)attrs[i - 1]).m_action, "Mixed SecurityActions");
+ Debug.Assert(i == 0 || ((SecurityAttribute)attrs[i]).m_action == ((SecurityAttribute)attrs[i - 1]).m_action, "Mixed SecurityActions");
#pragma warning restore 618
if (attrs[i] is PermissionSetAttribute)
{
MergePermission(perm, serialize, ref casPset, ref nonCasPset);
}
}
- Contract.Assert(serialize || nonCasPset == null, "We shouldn't separate nonCAS permissions unless fSerialize is true");
+ Debug.Assert(serialize || nonCasPset == null, "We shouldn't separate nonCAS permissions unless fSerialize is true");
//
// Filter HostProtection permission. In the VM, some optimizations are done based upon these
nonCasPset = null;
}
- Contract.Assert(!serialize, "Cannot serialize permission sets on CoreCLR");
+ Debug.Assert(!serialize, "Cannot serialize permission sets on CoreCLR");
return null;
}
internal static PermissionSet RemoveRefusedPermissionSet(PermissionSet assertSet, PermissionSet refusedSet, out bool bFailedToCompress)
{
- Contract.Assert((assertSet == null || !assertSet.IsUnrestricted()), "Cannot be unrestricted here");
+ Debug.Assert((assertSet == null || !assertSet.IsUnrestricted()), "Cannot be unrestricted here");
PermissionSet retPs = null;
bFailedToCompress = false;
if (assertSet == null)
internal static void RemoveAssertedPermissionSet(PermissionSet demandSet, PermissionSet assertSet, out PermissionSet alteredDemandSet)
{
- Contract.Assert(!assertSet.IsUnrestricted(), "Cannot call this function if assertSet is unrestricted");
+ Debug.Assert(!assertSet.IsUnrestricted(), "Cannot call this function if assertSet is unrestricted");
alteredDemandSet = null;
PermissionSetEnumeratorInternal enumerator = new PermissionSetEnumeratorInternal(demandSet);
using System.Security;
using System.Security.Permissions;
using System.Runtime.InteropServices;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
PermissionSetTriple retTriple = null;
if (in_a != null)
{
- Contract.Assert((!in_a.IsUnrestricted() || RefusedSet == null), "Cannot be unrestricted or refused must be null");
+ Debug.Assert((!in_a.IsUnrestricted() || RefusedSet == null), "Cannot be unrestricted or refused must be null");
// if we're already asserting in_a, nothing to do
if (in_a.IsSubsetOf(AssertSet))
return null;
internal bool CheckDemandNoThrow(CodeAccessPermission demand, PermissionToken permToken)
{
- Contract.Assert(AssertSet == null, "AssertSet not null");
+ Debug.Assert(AssertSet == null, "AssertSet not null");
#pragma warning disable 618
return CodeAccessSecurityEngine.CheckHelper(GrantSet, RefusedSet, demand, permToken, RuntimeMethodHandleInternal.EmptyHandle, null, SecurityAction.Demand, false);
#pragma warning restore 618
}
internal bool CheckSetDemandNoThrow(PermissionSet demandSet)
{
- Contract.Assert(AssertSet == null, "AssertSet not null");
+ Debug.Assert(AssertSet == null, "AssertSet not null");
#pragma warning disable 618
return CodeAccessSecurityEngine.CheckSetHelper(GrantSet, RefusedSet, demandSet, RuntimeMethodHandleInternal.EmptyHandle, null, SecurityAction.Demand, false);
using System.Threading;
using System.Globalization;
using System.Runtime.CompilerServices;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[Flags]
static internal TokenBasedSet s_tokenSet = new TokenBasedSet();
internal static bool IsMscorlibClassName (string className) {
- Contract.Assert( c_mscorlibName == ((RuntimeAssembly)Assembly.GetExecutingAssembly()).GetSimpleName(),
+ Debug.Assert( c_mscorlibName == ((RuntimeAssembly)Assembly.GetExecutingAssembly()).GetSimpleName(),
System.CoreLib.Name+" name mismatch" );
// If the class name does not look like a fully qualified name, we cannot simply determine if it's
internal PermissionToken GetToken(Type cls, IPermission perm)
{
- Contract.Assert( cls != null, "Must pass in valid type" );
+ Debug.Assert( cls != null, "Must pass in valid type" );
IntPtr typePtr = cls.TypeHandle.Value;
object tok = m_handleTable[typePtr];
{
if (perm != null)
{
- Contract.Assert( !(perm is IBuiltInPermission), "This should not be called for built-ins" );
+ Debug.Assert( !(perm is IBuiltInPermission), "This should not be called for built-ins" );
((PermissionToken)tok).m_type = PermissionTokenType.IUnrestricted;
}
else
{
- Contract.Assert( cls.GetInterface( "System.Security.Permissions.IBuiltInPermission" ) == null, "This shoudl not be called for built-ins" );
+ Debug.Assert( cls.GetInterface( "System.Security.Permissions.IBuiltInPermission" ) == null, "This shoudl not be called for built-ins" );
if (cls.GetInterface(s_unrestrictedPermissionInferfaceName) != null)
((PermissionToken)tok).m_type = PermissionTokenType.IUnrestricted;
else
using System.Globalization;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[Serializable]
return this.IsEmpty() ? null : this.Copy();
}
- Contract.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" );
+ Debug.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" );
if (this.m_allFiles || operand.m_allFiles)
{
return null;
}
- Contract.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" );
+ Debug.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" );
if (this.m_allFiles)
{
return true;
}
- Contract.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" );
+ Debug.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" );
if (!((m_pathDiscovery && this.m_set.IsSubsetOfPathDiscovery( operand.m_set )) || this.m_set.IsSubsetOf( operand.m_set )))
{
FileIOAccess operand = obj as FileIOAccess;
if(operand == null)
return (IsEmpty() && obj == null);
- Contract.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" );
+ Debug.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" );
if(m_pathDiscovery)
{
if(this.m_allFiles && operand.m_allFiles)
#endif
using System.Security.Util;
using System.Globalization;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[Serializable]
if (current != null) {
if (String.Equals(current.Tag, "AccessEntry")) {
int iMax = current.m_lAttributes.Count;
- Contract.Assert(iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly");
+ Debug.Assert(iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly");
string keyStore = null;
string providerName = null;
int providerType = -1;
using System;
using System.Collections;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.IO;
using System.Runtime.InteropServices;
internal LegacyEvidenceWrapper(object legacyEvidence)
{
- Contract.Assert(legacyEvidence != null);
- Contract.Assert(legacyEvidence.GetType() != typeof(EvidenceBase), "Attempt to wrap an EvidenceBase in a LegacyEvidenceWrapper");
- Contract.Assert(legacyEvidence.GetType().IsSerializable, "legacyEvidence.GetType().IsSerializable");
+ Debug.Assert(legacyEvidence != null);
+ Debug.Assert(legacyEvidence.GetType() != typeof(EvidenceBase), "Attempt to wrap an EvidenceBase in a LegacyEvidenceWrapper");
+ Debug.Assert(legacyEvidence.GetType().IsSerializable, "legacyEvidence.GetType().IsSerializable");
m_legacyEvidence = legacyEvidence;
}
{
get
{
- Contract.Assert(m_legacyEvidenceList.Count > 0, "No items in LegacyEvidenceList, cannot tell what type they are");
+ Debug.Assert(m_legacyEvidenceList.Count > 0, "No items in LegacyEvidenceList, cannot tell what type they are");
ILegacyEvidenceAdapter adapter = m_legacyEvidenceList[0] as ILegacyEvidenceAdapter;
return adapter == null ? m_legacyEvidenceList[0].GetType() : adapter.EvidenceType;
public void Add(EvidenceBase evidence)
{
- Contract.Assert(evidence != null);
- Contract.Assert(m_legacyEvidenceList.Count == 0 || EvidenceType == evidence.GetType() || (evidence is LegacyEvidenceWrapper && (evidence as LegacyEvidenceWrapper).EvidenceType == EvidenceType),
+ Debug.Assert(evidence != null);
+ Debug.Assert(m_legacyEvidenceList.Count == 0 || EvidenceType == evidence.GetType() || (evidence is LegacyEvidenceWrapper && (evidence as LegacyEvidenceWrapper).EvidenceType == EvidenceType),
"LegacyEvidenceList must be homogeonous");
- Contract.Assert(evidence.GetType() != typeof(LegacyEvidenceList),
+ Debug.Assert(evidence.GetType() != typeof(LegacyEvidenceList),
"Attempt to add a legacy evidence list to another legacy evidence list");
m_legacyEvidenceList.Add(evidence);
/// </summary>
private EvidenceTypeDescriptor(EvidenceTypeDescriptor descriptor)
{
- Contract.Assert(descriptor != null);
+ Debug.Assert(descriptor != null);
m_hostCanGenerate = descriptor.m_hostCanGenerate;
set
{
- Contract.Assert(value != null);
+ Debug.Assert(value != null);
#if _DEBUG
- Contract.Assert(CheckEvidenceType(value), "Incorrect type of AssemblyEvidence set");
+ Debug.Assert(CheckEvidenceType(value), "Incorrect type of AssemblyEvidence set");
#endif
m_assemblyEvidence = value;
}
set
{
- Contract.Assert(value, "Attempt to clear the Generated flag");
+ Debug.Assert(value, "Attempt to clear the Generated flag");
m_generated = value;
}
}
set
{
- Contract.Assert(value, "Attempt to clear HostCanGenerate flag");
+ Debug.Assert(value, "Attempt to clear HostCanGenerate flag");
m_hostCanGenerate = value;
}
}
set
{
- Contract.Assert(value != null);
+ Debug.Assert(value != null);
#if _DEBUG
- Contract.Assert(CheckEvidenceType(value), "Incorrect type of HostEvidence set");
+ Debug.Assert(CheckEvidenceType(value), "Incorrect type of HostEvidence set");
#endif
m_hostEvidence = value;
}
/// </summary>
private bool CheckEvidenceType(EvidenceBase evidence)
{
- Contract.Assert(evidence != null);
+ Debug.Assert(evidence != null);
ILegacyEvidenceAdapter legacyAdapter = evidence as ILegacyEvidenceAdapter;
Type storedType = legacyAdapter == null ? evidence.GetType() : legacyAdapter.EvidenceType;
/// </summary>
internal void SetEvidenceType(Type evidenceType)
{
- Contract.Assert(evidenceType != null);
- Contract.Assert(m_evidenceType == null, "Attempt to reset evidence type");
+ Debug.Assert(evidenceType != null);
+ Debug.Assert(m_evidenceType == null, "Attempt to reset evidence type");
m_evidenceType = evidenceType;
}
//
using System;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Security.Permissions;
private Site(SiteString name)
{
- Contract.Assert(name != null);
+ Debug.Assert(name != null);
m_name = name;
}
using System.Security.Util;
using UrlIdentityPermission = System.Security.Permissions.UrlIdentityPermission;
using System.Runtime.Serialization;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[Serializable]
private Url(Url url)
{
- Contract.Assert(url != null);
+ Debug.Assert(url != null);
m_url = url.m_url;
}
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Runtime.Serialization;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[Serializable]
private Zone(Zone zone)
{
- Contract.Assert(zone != null);
+ Debug.Assert(zone != null);
m_zone = zone.m_zone;
}
#endif // FEATURE_CORRUPTING_EXCEPTIONS
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
// This enum must be kept in sync with the SecurityContextSource enum in the VM
if (currEC != null)
{
- Contract.Assert(currEC == Thread.CurrentThread.GetMutableExecutionContext(), "SecurityContextSwitcher used from another thread");
- Contract.Assert(currSC == currEC.SecurityContext, "SecurityContextSwitcher context mismatch");
+ Debug.Assert(currEC == Thread.CurrentThread.GetMutableExecutionContext(), "SecurityContextSwitcher used from another thread");
+ Debug.Assert(currSC == currEC.SecurityContext, "SecurityContextSwitcher context mismatch");
// restore the saved security context
currEC.SecurityContext = prevSC.DangerousGetRawSecurityContext();
else
{
// caller must have already restored the ExecutionContext
- Contract.Assert(Thread.CurrentThread.GetExecutionContextReader().SecurityContext.IsSame(prevSC));
+ Debug.Assert(Thread.CurrentThread.GetExecutionContextReader().SecurityContext.IsSame(prevSC));
}
currSC = null; // this will prevent the switcher object being used again
// and automatically goes away when the callback returns.
WindowsIdentity.SafeRevertToSelf(ref stackMark);
// Ensure we have reverted to the state we entered in.
- Contract.Assert(GetCurrentWI(Thread.CurrentThread.GetExecutionContextReader()) == null);
+ Debug.Assert(GetCurrentWI(Thread.CurrentThread.GetExecutionContextReader()) == null);
}
}
else
/// <internalonly/>
internal SecurityContext CreateMutableCopy()
{
- Contract.Assert(!this.isNewCapture);
+ Debug.Assert(!this.isNewCapture);
SecurityContext sc = new SecurityContext();
sc._disableFlow = this._disableFlow;
using System.Globalization;
using System.IO;
using System.Security.Permissions;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
internal enum SecurityElementType
Hashtable hashtable = new Hashtable( m_lAttributes.Count/2 );
int iMax = m_lAttributes.Count;
- Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
+ Debug.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
for (int i = 0; i < iMax; i += 2)
{
else
{
int iMax = m_lAttributes.Count;
- Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
+ Debug.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
for (int i = 0; i < iMax; i += 2)
{
else
{
int iMax = m_lAttributes.Count;
- Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
+ Debug.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
if (iMax != other.m_lAttributes.Count)
return false;
private static String GetEscapeSequence( char c )
{
int iMax = s_escapeStringPairs.Length;
- Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
+ Debug.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
for (int i = 0; i < iMax; i += 2)
{
return strEscValue;
}
- Contract.Assert( false, "Unable to find escape sequence for this character" );
+ Debug.Assert( false, "Unable to find escape sequence for this character" );
return c.ToString();
}
int maxCompareLength = str.Length - index;
int iMax = s_escapeStringPairs.Length;
- Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
+ Debug.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
for (int i = 0; i < iMax; i += 2)
{
while (true);
// C# reports a warning if I leave this in, but I still kinda want to just in case.
- // Contract.Assert( false, "If you got here, the execution engine or compiler is really confused" );
+ // Debug.Assert( false, "If you got here, the execution engine or compiler is really confused" );
// return str;
}
func( obj, " " );
int iMax = m_lAttributes.Count;
- Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
+ Debug.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
for (int i = 0; i < iMax; i += 2)
{
// the one we are asked for
int iMax = m_lAttributes.Count;
- Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
+ Debug.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
for (int i = 0; i < iMax; i += 2)
{
using System.Globalization;
using System.Runtime.Versioning;
using System.IO;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[Serializable]
public void AddExpressions( ArrayList exprArrayList, bool checkForDuplicates)
{
- Contract.Assert( m_throwOnRelative, "This should only be called when throw on relative is set" );
+ Debug.Assert( m_throwOnRelative, "This should only be called when throw on relative is set" );
m_expressionsArray = null;
m_expressions = null;
using System.Security.Permissions;
using System.Runtime.Serialization;
using System.Threading;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Diagnostics.CodeAnalysis;
}
else
{
- Contract.Assert( (thisObj == null || otherObj == null), "Permission cannot be in both TokenBasedSets" );
+ Debug.Assert( (thisObj == null || otherObj == null), "Permission cannot be in both TokenBasedSets" );
}
}
return unionSet;
using System.Threading;
using System.Globalization;
using System.Reflection;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
internal static class XMLUtil
if ( typename == null )
typename = type.FullName;
- Contract.Assert( type.FullName.Equals( typename ), "Incorrect class name passed! Was : " + typename + " Shoule be: " + type.FullName);
+ Debug.Assert( type.FullName.Equals( typename ), "Incorrect class name passed! Was : " + typename + " Shoule be: " + type.FullName);
element.AddAttribute( "class", typename + ", " + type.Module.Assembly.FullName.Replace( '\"', '\'' ) );
}
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using Microsoft.Win32.SafeHandles;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
public sealed class SecureString: IDisposable {
throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_IndexString"));
}
Contract.EndContractBlock();
- Contract.Assert(index <= Int32.MaxValue / sizeof(char));
+ Debug.Assert(index <= Int32.MaxValue / sizeof(char));
EnsureNotDisposed();
EnsureNotReadOnly();
private int BufferLength {
[System.Security.SecurityCritical] // auto-generated
get {
- Contract.Assert(m_buffer != null, "Buffer is not initialized!");
+ Debug.Assert(m_buffer != null, "Buffer is not initialized!");
return m_buffer.Length;
}
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private static uint GetAlignedSize( int size) {
- Contract.Assert(size >= 0, "size must be non-negative");
+ Debug.Assert(size >= 0, "size must be non-negative");
uint alignedSize = ((uint)size / BlockSize) * BlockSize;
if( (size % BlockSize != 0) || size == 0) { // if size is 0, set allocated size to blocksize
[System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
private void ProtectMemory() {
- Contract.Assert(!m_buffer.IsInvalid && m_buffer.Length != 0, "Invalid buffer!");
- Contract.Assert(m_buffer.Length % BlockSize == 0, "buffer length must be multiple of blocksize!");
+ Debug.Assert(!m_buffer.IsInvalid && m_buffer.Length != 0, "Invalid buffer!");
+ Debug.Assert(m_buffer.Length % BlockSize == 0, "buffer length must be multiple of blocksize!");
if( m_length == 0 || m_encrypted) {
return;
[System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private void UnProtectMemory() {
- Contract.Assert(!m_buffer.IsInvalid && m_buffer.Length != 0, "Invalid buffer!");
- Contract.Assert(m_buffer.Length % BlockSize == 0, "buffer length must be multiple of blocksize!");
+ Debug.Assert(!m_buffer.IsInvalid && m_buffer.Length != 0, "Invalid buffer!");
+ Debug.Assert(m_buffer.Length % BlockSize == 0, "buffer length must be multiple of blocksize!");
if( m_length == 0) {
return;
source.AcquirePointer(ref sourcePtr);
target.AcquirePointer(ref targetPtr);
- Contract.Assert(Win32Native.SysStringLen((IntPtr)targetPtr) >= Win32Native.SysStringLen((IntPtr)sourcePtr), "Target buffer is not large enough!");
+ Debug.Assert(Win32Native.SysStringLen((IntPtr)targetPtr) >= Win32Native.SysStringLen((IntPtr)sourcePtr), "Target buffer is not large enough!");
Buffer.Memcpy(targetPtr, sourcePtr, (int) Win32Native.SysStringLen((IntPtr)sourcePtr) * 2);
}
using System.Security.Util;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
internal sealed class SharedStatics
}
}
- Contract.Assert(_sharedStatics._Remoting_Identity_IDGuid != null,
+ Debug.Assert(_sharedStatics._Remoting_Identity_IDGuid != null,
"_sharedStatics._Remoting_Identity_IDGuid != null");
return _sharedStatics._Remoting_Identity_IDGuid;
}
internal static ulong MemoryFailPointReservedMemory {
get {
- Contract.Assert(Volatile.Read(ref _sharedStatics._memFailPointReservedMemory) >= 0, "Process-wide MemoryFailPoint reserved memory was negative!");
+ Debug.Assert(Volatile.Read(ref _sharedStatics._memFailPointReservedMemory) >= 0, "Process-wide MemoryFailPoint reserved memory was negative!");
return (ulong) Volatile.Read(ref _sharedStatics._memFailPointReservedMemory);
}
}
// See the LICENSE file in the project root for more information.
using System.Collections;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.CompilerServices;
int charA = *a;
int charB = *b;
- Contract.Assert((charA | charB) <= 0x7F, "strings have to be ASCII");
+ Debug.Assert((charA | charB) <= 0x7F, "strings have to be ASCII");
// uppercase both chars - notice that we need just one compare per char
if ((uint)(charA - 'a') <= (uint)('z' - 'a')) charA -= 0x20;
#if BIT64
// Single int read aligns pointers for the following long reads
// No length check needed as this method is called when length >= 2
- Contract.Assert(length >= 2);
+ Debug.Assert(length >= 2);
if (*(int*)a != *(int*)b) goto ReturnFalse;
length -= 2; a += 2; b += 2;
// NOTE: This may be subject to change if eliminating the check
// in the callers makes them small enough to be inlined by the JIT
- Contract.Assert(strA.m_firstChar == strB.m_firstChar,
+ Debug.Assert(strA.m_firstChar == strB.m_firstChar,
"For performance reasons, callers of this method should " +
"check/short-circuit beforehand if the first char is the same.");
if (*a != *b) return *a - *b;
DiffOffset1:
- Contract.Assert(*(a + 1) != *(b + 1), "This char must be different if we reach here!");
+ Debug.Assert(*(a + 1) != *(b + 1), "This char must be different if we reach here!");
return *(a + 1) - *(b + 1);
}
}
internal int GetLegacyNonRandomizedHashCode() {
unsafe {
fixed (char* src = &m_firstChar) {
- Contract.Assert(src[this.Length] == '\0', "src[this.Length] == '\\0'");
- Contract.Assert( ((int)src)%4 == 0, "Managed string should start at 4 bytes boundary");
+ Debug.Assert(src[this.Length] == '\0', "src[this.Length] == '\\0'");
+ Debug.Assert( ((int)src)%4 == 0, "Managed string should start at 4 bytes boundary");
#if BIT64
int hash1 = 5381;
#else // !BIT64 (32)
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.CompilerServices;
{
string s = strings[i];
- Contract.Assert(s != null);
- Contract.Assert(position <= totalLength - s.Length, "We didn't allocate enough space for the result string!");
+ Debug.Assert(s != null);
+ Debug.Assert(position <= totalLength - s.Length, "We didn't allocate enough space for the result string!");
FillStringChecked(result, position, s);
position += s.Length;
{
// If the separator is null, it is converted to an empty string before entering this function.
// Even for empty strings, fixed should never return null (it should return a pointer to a null char).
- Contract.Assert(separator != null);
- Contract.Assert(separatorLength >= 0);
+ Debug.Assert(separator != null);
+ Debug.Assert(separatorLength >= 0);
if (value == null)
{
}
// we must have at least one slot left to fill in the last string.
- Contract.Assert(arrIndex < maxItems);
+ Debug.Assert(arrIndex < maxItems);
//Handle the last string at the end of the array if there is one.
if (currIndex< Length) {
// sepList -- an array of ints for split char indicies.
//--------------------------------------------------------------------
private unsafe int MakeSeparatorList(char* separators, int separatorsLength, int[] sepList) {
- Contract.Assert(separatorsLength >= 0, "separatorsLength >= 0");
+ Debug.Assert(separatorsLength >= 0, "separatorsLength >= 0");
int foundCount=0;
if (separators == null || separatorsLength == 0) {
// sepList -- an array of ints for split string indicies.
//--------------------------------------------------------------------
private unsafe int MakeSeparatorList(string separator, int[] sepList) {
- Contract.Assert(!string.IsNullOrEmpty(separator), "!string.IsNullOrEmpty(separator)");
+ Debug.Assert(!string.IsNullOrEmpty(separator), "!string.IsNullOrEmpty(separator)");
int foundCount = 0;
int sepListCount = sepList.Length;
// lengthList -- an array of ints for split string lengths.
//--------------------------------------------------------------------
private unsafe int MakeSeparatorList(String[] separators, int[] sepList, int[] lengthList) {
- Contract.Assert(separators != null && separators.Length > 0, "separators != null && separators.Length > 0");
+ Debug.Assert(separators != null && separators.Length > 0, "separators != null && separators.Length > 0");
int foundCount = 0;
int sepListCount = sepList.Length;
}
unsafe string InternalSubString(int startIndex, int length) {
- Contract.Assert( startIndex >= 0 && startIndex <= this.Length, "StartIndex is out of range!");
- Contract.Assert( length >= 0 && startIndex <= this.Length - length, "length is out of range!");
+ Debug.Assert( startIndex >= 0 && startIndex <= this.Length, "StartIndex is out of range!");
+ Debug.Assert( length >= 0 && startIndex <= this.Length - length, "length is out of range!");
String result = FastAllocateString(length);
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using Microsoft.Win32;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Security;
for(int i = 0; i < length; i++) {
int c = inBuff[i];
- Contract.Assert(c <= 0x7F, "string has to be ASCII");
+ Debug.Assert(c <= 0x7F, "string has to be ASCII");
// uppercase - notice that we need just one compare
if ((uint)(c - 'a') <= (uint)('z' - 'a')) c -= 0x20;
outBuff[i] = (char)c;
}
- Contract.Assert(outBuff[length]=='\0', "outBuff[length]=='\0'");
+ Debug.Assert(outBuff[length]=='\0', "outBuff[length]=='\0'");
}
return strOut;
}
// Get our string length
int stringLength = encoding.GetCharCount(bytes, byteLength, null);
- Contract.Assert(stringLength >= 0, "stringLength >= 0");
+ Debug.Assert(stringLength >= 0, "stringLength >= 0");
// They gave us an empty string if they needed one
// 0 bytelength might be possible if there's something in an encoder
fixed(char* pTempChars = &s.m_firstChar)
{
int doubleCheck = encoding.GetChars(bytes, byteLength, pTempChars, stringLength, null);
- Contract.Assert(stringLength == doubleCheck,
+ Debug.Assert(stringLength == doubleCheck,
"Expected encoding.GetChars to return same length as encoding.GetCharCount");
}
unsafe internal int ConvertToAnsi(byte *pbNativeBuffer, int cbNativeBuffer, bool fBestFit, bool fThrowOnUnmappableChar)
{
- Contract.Assert(cbNativeBuffer >= (Length + 1) * Marshal.SystemMaxDBCSCharSize, "Insufficient buffer length passed to ConvertToAnsi");
+ Debug.Assert(cbNativeBuffer >= (Length + 1) * Marshal.SystemMaxDBCSCharSize, "Insufficient buffer length passed to ConvertToAnsi");
const uint CP_ACP = 0;
int nb;
end += 2;
}
- Contract.Assert(end[0] == 0 || end[1] == 0);
+ Debug.Assert(end[0] == 0 || end[1] == 0);
if (end[0] != 0) end++;
#else // !BIT64
// Based on https://graphics.stanford.edu/~seander/bithacks.html#ZeroInWord
#endif // !BIT64
FoundZero:
- Contract.Assert(*end == 0);
+ Debug.Assert(*end == 0);
int count = (int)(end - ptr);
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeStringPtrNotAtom"));
#endif // FEATURE_PAL
- Contract.Assert(this == null, "this == null"); // this is the string constructor, we allocate it
+ Debug.Assert(this == null, "this == null"); // this is the string constructor, we allocate it
try {
int count = wcslen(ptr);
throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
}
Contract.EndContractBlock();
- Contract.Assert(this == null, "this == null"); // this is the string constructor, we allocate it
+ Debug.Assert(this == null, "this == null"); // this is the string constructor, we allocate it
char *pFrom = ptr + startIndex;
if (pFrom < ptr) {
#endif // FEATURE_COMINTEROP
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
{
static internal IntPtr ConvertToNative(string strManaged)
{
- Contract.Assert(false, "NYI");
+ Debug.Assert(false, "NYI");
return IntPtr.Zero;
}
static internal unsafe string ConvertToManaged(IntPtr bstr)
{
- Contract.Assert(false, "NYI");
+ Debug.Assert(false, "NYI");
return null;
}
static internal void ClearNative(IntPtr pNative)
{
- Contract.Assert(false, "NYI");
+ Debug.Assert(false, "NYI");
}
} // class WSTRBufferMarshaler
internal static void ClearNative(IntPtr hstring)
{
- Contract.Assert(Environment.IsWinRTSupported);
+ Debug.Assert(Environment.IsWinRTSupported);
if (hstring != IntPtr.Zero)
{
internal static unsafe void ClearNativeContents_Type(IntPtr pNativeHome, int cElements)
{
- Contract.Assert(Environment.IsWinRTSupported);
+ Debug.Assert(Environment.IsWinRTSupported);
TypeNameNative *pNativeTypeArray = *(TypeNameNative **)pNativeHome;
if (pNativeTypeArray != null)
ptr, allocSize,
IsBestFit(dwFlags),
IsThrowOn(dwFlags));
- Contract.Assert(length < allocSize, "Expected a length less than the allocated size");
+ Debug.Assert(length < allocSize, "Expected a length less than the allocated size");
}
if (IsOut(dwFlags))
{
internal static unsafe void ClearNative(TypeNameNative *pNativeType)
{
- Contract.Assert(Environment.IsWinRTSupported);
+ Debug.Assert(Environment.IsWinRTSupported);
if (pNativeType->typeName != IntPtr.Zero)
{
// S_OK should be marshaled as null. WinRT API's should not return S_FALSE by convention.
// We've chosen to treat S_FALSE as success and return null.
- Contract.Assert(e != null || hr == 0 || hr == 1, "Unexpected HRESULT - it is a success HRESULT (without the high bit set) other than S_OK & S_FALSE.");
+ Debug.Assert(e != null || hr == 0 || hr == 1, "Unexpected HRESULT - it is a success HRESULT (without the high bit set) other than S_OK & S_FALSE.");
return e;
}
} // class HResultExceptionMarshaler
using System;
using System.Runtime.Serialization;
using System.Security.Permissions;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
// ASCIIEncoding
internal override unsafe int GetByteCount(char* chars, int charCount, EncoderNLS encoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
- Contract.Assert(charCount >= 0, "[ASCIIEncoding.GetByteCount]count is negative");
- Contract.Assert(chars != null, "[ASCIIEncoding.GetByteCount]chars is null");
+ Debug.Assert(charCount >= 0, "[ASCIIEncoding.GetByteCount]count is negative");
+ Debug.Assert(chars != null, "[ASCIIEncoding.GetByteCount]chars is null");
// Assert because we shouldn't be able to have a null encoder.
- Contract.Assert(encoderFallback != null, "[ASCIIEncoding.GetByteCount]Attempting to use null fallback encoder");
+ Debug.Assert(encoderFallback != null, "[ASCIIEncoding.GetByteCount]Attempting to use null fallback encoder");
char charLeftOver = (char)0;
EncoderReplacementFallback fallback = null;
if (encoder != null)
{
charLeftOver = encoder.charLeftOver;
- Contract.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
+ Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
"[ASCIIEncoding.GetByteCount]leftover character should be high surrogate");
fallback = encoder.Fallback as EncoderReplacementFallback;
}
// Verify that we have no fallbackbuffer, for ASCII its always empty, so just assert
- Contract.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
+ Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
encoder.FallbackBuffer.Remaining == 0,
"[ASCIICodePageEncoding.GetByteCount]Expected empty fallback buffer");
// if (encoder.InternalHasFallbackBuffer && encoder.FallbackBuffer.Remaining > 0)
// We may have a left over character from last time, try and process it.
if (charLeftOver > 0)
{
- Contract.Assert(Char.IsHighSurrogate(charLeftOver), "[ASCIIEncoding.GetByteCount]leftover character should be high surrogate");
- Contract.Assert(encoder != null, "[ASCIIEncoding.GetByteCount]Expected encoder");
+ Debug.Assert(Char.IsHighSurrogate(charLeftOver), "[ASCIIEncoding.GetByteCount]leftover character should be high surrogate");
+ Debug.Assert(encoder != null, "[ASCIIEncoding.GetByteCount]Expected encoder");
// Since left over char was a surrogate, it'll have to be fallen back.
// Get Fallback
byteCount++;
}
- Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
+ Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
"[ASCIIEncoding.GetByteCount]Expected Empty fallback buffer");
return byteCount;
byte* bytes, int byteCount, EncoderNLS encoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
- Contract.Assert(bytes != null, "[ASCIIEncoding.GetBytes]bytes is null");
- Contract.Assert(byteCount >= 0, "[ASCIIEncoding.GetBytes]byteCount is negative");
- Contract.Assert(chars != null, "[ASCIIEncoding.GetBytes]chars is null");
- Contract.Assert(charCount >= 0, "[ASCIIEncoding.GetBytes]charCount is negative");
+ Debug.Assert(bytes != null, "[ASCIIEncoding.GetBytes]bytes is null");
+ Debug.Assert(byteCount >= 0, "[ASCIIEncoding.GetBytes]byteCount is negative");
+ Debug.Assert(chars != null, "[ASCIIEncoding.GetBytes]chars is null");
+ Debug.Assert(charCount >= 0, "[ASCIIEncoding.GetBytes]charCount is negative");
// Assert because we shouldn't be able to have a null encoder.
- Contract.Assert(encoderFallback != null, "[ASCIIEncoding.GetBytes]Attempting to use null encoder fallback");
+ Debug.Assert(encoderFallback != null, "[ASCIIEncoding.GetBytes]Attempting to use null encoder fallback");
// Get any left over characters
char charLeftOver = (char)0;
fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, true);
}
- Contract.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
+ Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
"[ASCIIEncoding.GetBytes]leftover character should be high surrogate");
// Verify that we have no fallbackbuffer, for ASCII its always empty, so just assert
- Contract.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
+ Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
encoder.FallbackBuffer.Remaining == 0,
"[ASCIICodePageEncoding.GetBytes]Expected empty fallback buffer");
// if (encoder.m_throwOnOverflow && encoder.InternalHasFallbackBuffer &&
if (charLeftOver > 0)
{
// Initialize the buffer
- Contract.Assert(encoder != null,
+ Debug.Assert(encoder != null,
"[ASCIIEncoding.GetBytes]Expected non null encoder if we have surrogate left over");
fallbackBuffer = encoder.FallbackBuffer;
fallbackBuffer.InternalInitialize(chars, charEnd, encoder, true);
// didn't use this char, we'll throw or use buffer
if (fallbackBuffer == null || fallbackBuffer.bFallingBack == false)
{
- Contract.Assert(chars > charStart || bytes == byteStart,
+ Debug.Assert(chars > charStart || bytes == byteStart,
"[ASCIIEncoding.GetBytes]Expected chars to have advanced already.");
chars--; // don't use last char
}
encoder.m_charsUsed = (int)(chars - charStart);
}
- Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0 ||
+ Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0 ||
(encoder != null && !encoder.m_throwOnOverflow ),
"[ASCIIEncoding.GetBytes]Expected Empty fallback buffer at end");
internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS decoder)
{
// Just assert, we're called internally so these should be safe, checked already
- Contract.Assert(bytes != null, "[ASCIIEncoding.GetCharCount]bytes is null");
- Contract.Assert(count >= 0, "[ASCIIEncoding.GetCharCount]byteCount is negative");
+ Debug.Assert(bytes != null, "[ASCIIEncoding.GetCharCount]bytes is null");
+ Debug.Assert(count >= 0, "[ASCIIEncoding.GetCharCount]byteCount is negative");
// ASCII doesn't do best fit, so don't have to check for it, find out which decoder fallback we're using
DecoderReplacementFallback fallback = null;
else
{
fallback = decoder.Fallback as DecoderReplacementFallback;
- Contract.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer ||
+ Debug.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer ||
decoder.FallbackBuffer.Remaining == 0,
"[ASCIICodePageEncoding.GetCharCount]Expected empty fallback buffer");
}
}
// Fallback buffer must be empty
- Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
+ Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
"[ASCIIEncoding.GetCharCount]Expected Empty fallback buffer");
// Converted sequence is same length as input
char* chars, int charCount, DecoderNLS decoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
- Contract.Assert(bytes != null, "[ASCIIEncoding.GetChars]bytes is null");
- Contract.Assert(byteCount >= 0, "[ASCIIEncoding.GetChars]byteCount is negative");
- Contract.Assert(chars != null, "[ASCIIEncoding.GetChars]chars is null");
- Contract.Assert(charCount >= 0, "[ASCIIEncoding.GetChars]charCount is negative");
+ Debug.Assert(bytes != null, "[ASCIIEncoding.GetChars]bytes is null");
+ Debug.Assert(byteCount >= 0, "[ASCIIEncoding.GetChars]byteCount is negative");
+ Debug.Assert(chars != null, "[ASCIIEncoding.GetChars]chars is null");
+ Debug.Assert(charCount >= 0, "[ASCIIEncoding.GetChars]charCount is negative");
// Do it fast way if using ? replacement fallback
byte* byteEnd = bytes + byteCount;
else
{
fallback = decoder.Fallback as DecoderReplacementFallback;
- Contract.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer ||
+ Debug.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer ||
decoder.FallbackBuffer.Remaining == 0,
"[ASCIICodePageEncoding.GetChars]Expected empty fallback buffer");
}
if (!fallbackBuffer.InternalFallback(byteBuffer, bytes, ref chars))
{
// May or may not throw, but we didn't get this byte
- Contract.Assert(bytes > byteStart || chars == charStart,
+ Debug.Assert(bytes > byteStart || chars == charStart,
"[ASCIIEncoding.GetChars]Expected bytes to have advanced already (fallback case)");
bytes--; // unused byte
fallbackBuffer.InternalReset(); // Didn't fall this back
// Make sure we have buffer space
if (chars >= charEnd)
{
- Contract.Assert(bytes > byteStart || chars == charStart,
+ Debug.Assert(bytes > byteStart || chars == charStart,
"[ASCIIEncoding.GetChars]Expected bytes to have advanced already (normal case)");
bytes--; // unused byte
ThrowCharsOverflow(decoder, chars == charStart); // throw?
decoder.m_bytesUsed = (int)(bytes - byteStart);
// Expect Empty fallback buffer for GetChars
- Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
+ Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
"[ASCIIEncoding.GetChars]Expected Empty fallback buffer");
return (int)(chars - charStart);
namespace System.Text
{
using System;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.InteropServices;
{
// Make sure to get the base stuff too This throws if info is null
SerializeEncoding(info, context);
- Contract.Assert(info!=null, "[BaseCodePageEncoding.GetObjectData] Expected null info to throw");
+ Debug.Assert(info!=null, "[BaseCodePageEncoding.GetObjectData] Expected null info to throw");
// Just need Everett maxCharSize (BaseCodePageEncoding) or m_maxByteSize (MLangBaseCodePageEncoding)
info.AddValue(m_bUseMlangTypeForSerialization ? "m_maxByteSize" : "maxCharSize",
if (pCodePage == null)
return 0;
- Contract.Assert(pCodePage->ByteCount == 1 || pCodePage->ByteCount == 2,
+ Debug.Assert(pCodePage->ByteCount == 1 || pCodePage->ByteCount == 2,
"[BaseCodePageEncoding] Code page (" + codePage + ") has invalid byte size (" + pCodePage->ByteCount + ") in table");
// Return what it says for byte count
return pCodePage->ByteCount;
// This gets shared memory for our map. If its can't, it gives us clean memory.
Byte *pMemorySection = EncodingTable.nativeCreateOpenFileMapping(strName, iSize, out mappedFileHandle);
- Contract.Assert(pMemorySection != null,
+ Debug.Assert(pMemorySection != null,
"[BaseCodePageEncoding.GetSharedMemory] Expected non-null memory section to be opened");
// If that failed, we have to die.
// Read in our best fit table if necessary
if (arrayUnicodeBestFit == null) ReadBestFitTable();
- Contract.Assert(arrayUnicodeBestFit != null,
+ Debug.Assert(arrayUnicodeBestFit != null,
"[BaseCodePageEncoding.GetBestFitUnicodeToBytesData]Expected non-null arrayUnicodeBestFit");
// Normally we don't have any best fit data.
// Read in our best fit table if necessary
if (arrayBytesBestFit == null) ReadBestFitTable();
- Contract.Assert(arrayBytesBestFit != null,
+ Debug.Assert(arrayBytesBestFit != null,
"[BaseCodePageEncoding.GetBestFitBytesToUnicodeData]Expected non-null arrayBytesBestFit");
// Normally we don't have any best fit data.
using System;
using System.Runtime.Serialization;
using System.Security.Permissions;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
/*=================================CodePageEncoding==================================
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
// We cannot ever call this.
- Contract.Assert(false, "Didn't expect to make it to CodePageEncoding ISerializable.GetObjectData");
+ Debug.Assert(false, "Didn't expect to make it to CodePageEncoding ISerializable.GetObjectData");
throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException"));
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
// We cannot ever call this.
- Contract.Assert(false, "Didn't expect to make it to CodePageEncoding.Decoder.GetObjectData");
+ Debug.Assert(false, "Didn't expect to make it to CodePageEncoding.Decoder.GetObjectData");
throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException"));
}
}
namespace System.Text
{
using System;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Text;
using System.Threading;
internal DBCSCodePageEncoding(SerializationInfo info, StreamingContext context) : base(0)
{
// Actually this can't ever get called, CodePageEncoding is our proxy
- Contract.Assert(false, "Didn't expect to make it to DBCSCodePageEncoding serialization constructor");
+ Debug.Assert(false, "Didn't expect to make it to DBCSCodePageEncoding serialization constructor");
throw new ArgumentNullException("this");
}
protected override unsafe void LoadManagedCodePage()
{
// Should be loading OUR code page
- Contract.Assert(pCodePage->CodePage == this.dataTableCodePage,
+ Debug.Assert(pCodePage->CodePage == this.dataTableCodePage,
"[DBCSCodePageEncoding.LoadManagedCodePage]Expected to load data table code page");
// Make sure we're really a 1 byte code page
byteCountUnknown++;
// We use fallback encoder, which uses ?, which so far all of our tables do as well
- Contract.Assert(bytesUnknown == 0x3f,
+ Debug.Assert(bytesUnknown == 0x3f,
"[DBCSCodePageEncoding.LoadManagedCodePage]Expected 0x3f (?) as unknown byte character");
// Get our mapped section (bytes to allocate = 2 bytes per 65536 Unicode chars + 2 bytes per 65536 DBCS chars)
// If its cached (& filled in) we don't have to do anything else
if (*mapCodePageCached != 0)
{
- Contract.Assert(((*mapCodePageCached == this.dataTableCodePage && this.bFlagDataTable) ||
+ Debug.Assert(((*mapCodePageCached == this.dataTableCodePage && this.bFlagDataTable) ||
(*mapCodePageCached == this.CodePage && !this.bFlagDataTable)),
"[DBCSCodePageEncoding.LoadManagedCodePage]Expected mapped section cached page flag to be set to data table or regular code page.");
else if (input == LEAD_BYTE_CHAR) // 0xfffe
{
// Lead byte mark
- Contract.Assert(bytePosition < 0x100, "[DBCSCodePageEncoding.LoadManagedCodePage]expected lead byte to be < 0x100");
+ Debug.Assert(bytePosition < 0x100, "[DBCSCodePageEncoding.LoadManagedCodePage]expected lead byte to be < 0x100");
useBytes = bytePosition;
// input stays 0xFFFE
}
// If they're out of order we need to sort them.
if (bOutOfOrder)
{
- Contract.Assert((arrayTemp.Length / 2) < 20,
+ Debug.Assert((arrayTemp.Length / 2) < 20,
"[DBCSCodePageEncoding.ReadBestFitTable]Expected small best fit table < 20 for code page " + CodePage + ", not " + arrayTemp.Length / 2);
for (int i = 0; i < arrayTemp.Length - 2; i+=2)
// We can't do this assert for CP 51932 & 50220 because they aren't
// calling CleanUpBytes() for best fit. All the string stuff here
// also makes this assert slow.
- // Contract.Assert(arrayTemp[iBestFitCount-1] != (char)0xFFFD, String.Format(
+ // Debug.Assert(arrayTemp[iBestFitCount-1] != (char)0xFFFD, String.Format(
// "[DBCSCodePageEncoding.ReadBestFitTable] No valid Unicode value {0:X4} for round trip bytes {1:X4}, encoding {2}",
// (int)mapBytesToUnicode[input], (int)input, CodePage));
}
internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS encoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
- Contract.Assert(count >= 0, "[DBCSCodePageEncoding.GetByteCount]count is negative");
- Contract.Assert(chars != null, "[DBCSCodePageEncoding.GetByteCount]chars is null");
+ Debug.Assert(count >= 0, "[DBCSCodePageEncoding.GetByteCount]count is negative");
+ Debug.Assert(chars != null, "[DBCSCodePageEncoding.GetByteCount]chars is null");
// Assert because we shouldn't be able to have a null encoder.
- Contract.Assert(encoderFallback != null, "[DBCSCodePageEncoding.GetByteCount]Attempting to use null fallback");
+ Debug.Assert(encoderFallback != null, "[DBCSCodePageEncoding.GetByteCount]Attempting to use null fallback");
CheckMemorySection();
// We may have a left over character from last time, try and process it.
if (charLeftOver > 0)
{
- Contract.Assert(Char.IsHighSurrogate(charLeftOver), "[DBCSCodePageEncoding.GetByteCount]leftover character should be high surrogate");
- Contract.Assert(encoder != null,
+ Debug.Assert(Char.IsHighSurrogate(charLeftOver), "[DBCSCodePageEncoding.GetByteCount]leftover character should be high surrogate");
+ Debug.Assert(encoder != null,
"[DBCSCodePageEncoding.GetByteCount]Expect to have encoder if we have a charLeftOver");
// Since left over char was a surrogate, it'll have to be fallen back.
byte* bytes, int byteCount, EncoderNLS encoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
- Contract.Assert(bytes != null, "[DBCSCodePageEncoding.GetBytes]bytes is null");
- Contract.Assert(byteCount >= 0, "[DBCSCodePageEncoding.GetBytes]byteCount is negative");
- Contract.Assert(chars != null, "[DBCSCodePageEncoding.GetBytes]chars is null");
- Contract.Assert(charCount >= 0, "[DBCSCodePageEncoding.GetBytes]charCount is negative");
+ Debug.Assert(bytes != null, "[DBCSCodePageEncoding.GetBytes]bytes is null");
+ Debug.Assert(byteCount >= 0, "[DBCSCodePageEncoding.GetBytes]byteCount is negative");
+ Debug.Assert(chars != null, "[DBCSCodePageEncoding.GetBytes]chars is null");
+ Debug.Assert(charCount >= 0, "[DBCSCodePageEncoding.GetBytes]charCount is negative");
// Assert because we shouldn't be able to have a null encoder.
- Contract.Assert(encoderFallback != null, "[DBCSCodePageEncoding.GetBytes]Attempting to use null encoder fallback");
+ Debug.Assert(encoderFallback != null, "[DBCSCodePageEncoding.GetBytes]Attempting to use null encoder fallback");
CheckMemorySection();
if (encoder != null)
{
charLeftOver = encoder.charLeftOver;
- Contract.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
+ Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
"[DBCSCodePageEncoding.GetBytes]leftover character should be high surrogate");
// Go ahead and get the fallback buffer (need leftover fallback if converting)
// We may have a left over character from last time, try and process it.
if (charLeftOver > 0)
{
- Contract.Assert(encoder != null,
+ Debug.Assert(encoder != null,
"[DBCSCodePageEncoding.GetBytes]Expect to have encoder if we have a charLeftOver");
// Since left over char was a surrogate, it'll have to be fallen back.
if (fallbackBuffer == null)
{
// Initialize the buffer
- Contract.Assert(encoder == null,
+ Debug.Assert(encoder == null,
"[DBCSCodePageEncoding.GetBytes]Expected delayed create fallback only if no encoder.");
fallbackBuffer = this.encoderFallback.CreateFallbackBuffer();
fallbackBuffer.InternalInitialize(charEnd - charCount, charEnd, encoder, true);
// didn't use this char, we'll throw or use buffer
if (fallbackBuffer == null || fallbackBuffer.bFallingBack == false)
{
- Contract.Assert(chars > charStart,
+ Debug.Assert(chars > charStart,
"[DBCSCodePageEncoding.GetBytes]Expected chars to have advanced (double byte case)");
chars--; // don't use last char
}
// didn't use this char, we'll throw or use buffer
if (fallbackBuffer == null || fallbackBuffer.bFallingBack == false)
{
- Contract.Assert(chars > charStart,
+ Debug.Assert(chars > charStart,
"[DBCSCodePageEncoding.GetBytes]Expected chars to have advanced (single byte case)");
chars--; // don't use last char
}
// If we're not converting we must not have a fallback buffer
// (We don't really have a way to clear none-encoder using fallbacks however)
-// Contract.Assert((encoder == null || encoder.m_throwOnOverflow) &&
+// Debug.Assert((encoder == null || encoder.m_throwOnOverflow) &&
// (fallbackBuffer == null || fallbackBuffer.Remaining == 0),
// "[DBCSEncoding.GetBytes]Expected empty fallback buffer at end if not converting");
internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder)
{
// Just assert, we're called internally so these should be safe, checked already
- Contract.Assert(bytes != null, "[DBCSCodePageEncoding.GetCharCount]bytes is null");
- Contract.Assert(count >= 0, "[DBCSCodePageEncoding.GetCharCount]byteCount is negative");
+ Debug.Assert(bytes != null, "[DBCSCodePageEncoding.GetCharCount]bytes is null");
+ Debug.Assert(count >= 0, "[DBCSCodePageEncoding.GetCharCount]byteCount is negative");
CheckMemorySection();
// Shouldn't have anything in fallback buffer for GetCharCount
// (don't have to check m_throwOnOverflow for count)
- Contract.Assert(decoder == null ||
+ Debug.Assert(decoder == null ||
!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
"[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer at start");
}
- Contract.Assert(fallbackBuffer == null,
+ Debug.Assert(fallbackBuffer == null,
"[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer");
fallbackBuffer = decoder.FallbackBuffer;
fallbackBuffer.InternalInitialize(bytes, null);
charCount--;
// We'll need a fallback
- Contract.Assert(fallbackBuffer == null,
+ Debug.Assert(fallbackBuffer == null,
"[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer for unknown pair");
fallbackBuffer = decoder.FallbackBuffer;
fallbackBuffer.InternalInitialize(byteEnd - count, null);
}
// Shouldn't have anything in fallback buffer for GetChars
- Contract.Assert(decoder == null || !decoder.m_throwOnOverflow ||
+ Debug.Assert(decoder == null || !decoder.m_throwOnOverflow ||
!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
"[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer at end");
char* chars, int charCount, DecoderNLS baseDecoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
- Contract.Assert(bytes != null, "[DBCSCodePageEncoding.GetChars]bytes is null");
- Contract.Assert(byteCount >= 0, "[DBCSCodePageEncoding.GetChars]byteCount is negative");
- Contract.Assert(chars != null, "[DBCSCodePageEncoding.GetChars]chars is null");
- Contract.Assert(charCount >= 0, "[DBCSCodePageEncoding.GetChars]charCount is negative");
+ Debug.Assert(bytes != null, "[DBCSCodePageEncoding.GetChars]bytes is null");
+ Debug.Assert(byteCount >= 0, "[DBCSCodePageEncoding.GetChars]byteCount is negative");
+ Debug.Assert(chars != null, "[DBCSCodePageEncoding.GetChars]chars is null");
+ Debug.Assert(charCount >= 0, "[DBCSCodePageEncoding.GetChars]charCount is negative");
CheckMemorySection();
DecoderFallbackBuffer fallbackBuffer = null;
// Shouldn't have anything in fallback buffer for GetChars
- Contract.Assert(decoder == null || !decoder.m_throwOnOverflow ||
+ Debug.Assert(decoder == null || !decoder.m_throwOnOverflow ||
!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
"[DBCSCodePageEncoding.GetChars]Expected empty fallback buffer at start");
// Well, we're flushing, so use '?' or fallback
// fallback leftover byte
- Contract.Assert(fallbackBuffer == null,
+ Debug.Assert(fallbackBuffer == null,
"[DBCSCodePageEncoding.GetChars]Expected empty fallback");
fallbackBuffer = decoder.FallbackBuffer;
fallbackBuffer.InternalInitialize(bytes, charEnd);
char cDecoder = mapBytesToUnicode[iBytes];
if (cDecoder == UNKNOWN_CHAR_FLAG && iBytes != 0)
{
- Contract.Assert(fallbackBuffer == null,
+ Debug.Assert(fallbackBuffer == null,
"[DBCSCodePageEncoding.GetChars]Expected empty fallback for two bytes");
fallbackBuffer = decoder.FallbackBuffer;
fallbackBuffer.InternalInitialize(byteEnd - byteCount, charEnd);
if (!fallbackBuffer.InternalFallback(byteBuffer, bytes, ref chars))
{
// May or may not throw, but we didn't get these byte(s)
- Contract.Assert(bytes >= byteStart + byteBuffer.Length,
+ Debug.Assert(bytes >= byteStart + byteBuffer.Length,
"[DBCSCodePageEncoding.GetChars]Expected bytes to have advanced for fallback");
bytes-=byteBuffer.Length; // didn't use these byte(s)
fallbackBuffer.InternalReset(); // Didn't fall this back
if (chars >= charEnd)
{
// May or may not throw, but we didn't get these byte(s)
- Contract.Assert(bytes > byteStart,
+ Debug.Assert(bytes > byteStart,
"[DBCSCodePageEncoding.GetChars]Expected bytes to have advanced for lead byte");
bytes--; // unused byte
if (iBytes >= 0x100)
{
- Contract.Assert(bytes > byteStart,
+ Debug.Assert(bytes > byteStart,
"[DBCSCodePageEncoding.GetChars]Expected bytes to have advanced for trail byte");
bytes--; // 2nd unused byte
}
}
// Shouldn't have anything in fallback buffer for GetChars
- Contract.Assert(decoder == null || !decoder.m_throwOnOverflow ||
+ Debug.Assert(decoder == null || !decoder.m_throwOnOverflow ||
!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
"[DBCSCodePageEncoding.GetChars]Expected empty fallback buffer at end");
using System.Runtime.Serialization;
using System.Text;
using System;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
// A Decoder is used to decode a sequence of blocks of bytes into a
// sequence of blocks of characters. Following instantiation of a decoder,
// Do the work
int result = GetChars(arrByte, 0, byteCount, arrChar, 0, flush);
- Contract.Assert(result <= charCount, "Returned more chars than we have space for");
+ Debug.Assert(result <= charCount, "Returned more chars than we have space for");
// Copy the char array
// WARNING: We MUST make sure that we don't copy too many chars. We can't
using System;
using System.Text;
using System.Threading;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[Serializable]
public override bool Fallback(byte[] bytesUnknown, int index)
{
// We expect no previous fallback in our buffer
- Contract.Assert(iCount < 1, "[DecoderReplacementFallbackBuffer.Fallback] Calling fallback without a previously empty buffer");
+ Debug.Assert(iCount < 1, "[DecoderReplacementFallbackBuffer.Fallback] Calling fallback without a previously empty buffer");
cBestFit = TryBestFit(bytesUnknown);
if (cBestFit == '\0')
if (cTest == cCheck)
{
// We found it
- Contract.Assert(index + 1 < oFallback.arrayBestFit.Length,
+ Debug.Assert(index + 1 < oFallback.arrayBestFit.Length,
"[InternalDecoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array");
return oFallback.arrayBestFit[index + 1];
}
if (oFallback.arrayBestFit[index] == cCheck)
{
// We found it
- Contract.Assert(index + 1 < oFallback.arrayBestFit.Length,
+ Debug.Assert(index + 1 < oFallback.arrayBestFit.Length,
"[InternalDecoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array");
return oFallback.arrayBestFit[index + 1];
}
using System.Security;
using System.Threading;
using System.Globalization;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Text
// for (int i = 0; i < count; i++)
// bytesUnknown[i] = *(bytes++);
- Contract.Assert(byteStart != null, "[DecoderFallback.InternalFallback]Used InternalFallback without calling InternalInitialize");
+ Debug.Assert(byteStart != null, "[DecoderFallback.InternalFallback]Used InternalFallback without calling InternalInitialize");
// See if there's a fallback character and we have an output buffer then copy our string.
if (this.Fallback(bytes, (int)(pBytes - byteStart - bytes.Length)))
// for (int i = 0; i < count; i++)
// bytesUnknown[i] = *(bytes++);
- Contract.Assert(byteStart != null, "[DecoderFallback.InternalFallback]Used InternalFallback without calling InternalInitialize");
+ Debug.Assert(byteStart != null, "[DecoderFallback.InternalFallback]Used InternalFallback without calling InternalInitialize");
// See if there's a fallback character and we have an output buffer then copy our string.
if (this.Fallback(bytes, (int)(pBytes - byteStart - bytes.Length)))
namespace System.Text
{
using System;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[Serializable]
}
// Now make sure its in the expected range
- Contract.Assert(fallbackIndex < strDefault.Length && fallbackIndex >= 0,
+ Debug.Assert(fallbackIndex < strDefault.Length && fallbackIndex >= 0,
"Index exceeds buffer range");
return strDefault[fallbackIndex];
using System.Runtime.Serialization;
using System.Text;
using System;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
// An Encoder is used to encode a sequence of blocks of characters into
// a sequence of blocks of bytes. Following instantiation of an encoder,
// Do the work
int result = GetBytes(arrChar, 0, charCount, arrByte, 0, flush);
- Contract.Assert(result <= byteCount, "Returned more bytes than we have space for");
+ Debug.Assert(result <= byteCount, "Returned more bytes than we have space for");
// Copy the byte array
// WARNING: We MUST make sure that we don't copy too many bytes. We can't
using System.Globalization;
using System.Text;
using System.Threading;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[Serializable]
// If we had a buffer already we're being recursive, throw, it's probably at the suspect
// character in our array.
// Shouldn't be able to get here for all of our code pages, table would have to be messed up.
- Contract.Assert(iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(non surrogate)] Fallback char " + ((int)cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback");
+ Debug.Assert(iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(non surrogate)] Fallback char " + ((int)cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback");
iCount = iSize = 1;
cBestFit = TryBestFit(charUnknown);
// If we had a buffer already we're being recursive, throw, it's probably at the suspect
// character in our array. 0 is processing last character, < 0 is not falling back
// Shouldn't be able to get here, table would have to be messed up.
- Contract.Assert(iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(surrogate)] Fallback char " + ((int)cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback");
+ Debug.Assert(iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(surrogate)] Fallback char " + ((int)cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback");
// Go ahead and get our fallback, surrogates don't have best fit
cBestFit = '?';
if (cTest == cUnknown)
{
// We found it
- Contract.Assert(index + 1 < oFallback.arrayBestFit.Length,
+ Debug.Assert(index + 1 < oFallback.arrayBestFit.Length,
"[InternalEncoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array");
return oFallback.arrayBestFit[index + 1];
}
if (oFallback.arrayBestFit[index] == cUnknown)
{
// We found it
- Contract.Assert(index + 1 < oFallback.arrayBestFit.Length,
+ Debug.Assert(index + 1 < oFallback.arrayBestFit.Length,
"[InternalEncoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array");
return oFallback.arrayBestFit[index + 1];
}
using System;
using System.Security;
using System.Threading;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Text
internal unsafe virtual bool InternalFallback(char ch, ref char* chars)
{
// Shouldn't have null charStart
- Contract.Assert(charStart != null,
+ Debug.Assert(charStart != null,
"[EncoderFallback.InternalFallbackBuffer]Fallback buffer is not initialized");
// Get our index, remember chars was preincremented to point at next char, so have to -1
{
using System;
using System.Runtime;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[Serializable]
}
// Now make sure its in the expected range
- Contract.Assert(fallbackIndex < strDefault.Length && fallbackIndex >= 0,
+ Debug.Assert(fallbackIndex < strDefault.Length && fallbackIndex >= 0,
"Index exceeds buffer range");
return strDefault[fallbackIndex];
using System.Security.Permissions;
using System.Threading;
using System.Text;
+ using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using Win32Native = Microsoft.Win32.Win32Native;
result = GetEncodingCodePage(codepage) ?? GetEncodingRare(codepage);
}
- Contract.Assert(result != null, "result != null");
+ Debug.Assert(result != null, "result != null");
encodings.Add(key, result);
}
#if FEATURE_CODEPAGES_FILE
private static Encoding GetEncodingRare(int codepage)
{
- Contract.Assert(codepage != 0 && codepage != 1200 && codepage != 1201 && codepage != 65001,
+ Debug.Assert(codepage != 0 && codepage != 1200 && codepage != 1201 && codepage != 65001,
"[Encoding.GetEncodingRare]This code page (" + codepage + ") isn't supported by GetEncodingRare!");
Encoding result;
switch (codepage)
int byteCount = GetByteCount(s);
byte[] bytes = new byte[byteCount];
int bytesReceived = GetBytes(s, 0, s.Length, bytes, 0);
- Contract.Assert(byteCount == bytesReceived);
+ Debug.Assert(byteCount == bytesReceived);
return bytes;
}
// Do the work
int result = GetBytes(arrChar, 0, charCount, arrByte, 0);
- Contract.Assert(result <= byteCount, "[Encoding.GetBytes]Returned more bytes than we have space for");
+ Debug.Assert(result <= byteCount, "[Encoding.GetBytes]Returned more bytes than we have space for");
// Copy the byte array
// WARNING: We MUST make sure that we don't copy too many bytes. We can't
// Do the work
int result = GetChars(arrByte, 0, byteCount, arrChar, 0);
- Contract.Assert(result <= charCount, "[Encoding.GetChars]Returned more chars than we have space for");
+ Debug.Assert(result <= charCount, "[Encoding.GetChars]Returned more chars than we have space for");
// Copy the char array
// WARNING: We MUST make sure that we don't copy too many chars. We can't
// If we're getting chars or getting char count we don't expect to have
// to remember fallbacks between calls (so it should be empty)
- Contract.Assert(fallbackBuffer.Remaining == 0,
+ Debug.Assert(fallbackBuffer.Remaining == 0,
"[Encoding.EncodingCharBuffer.EncodingCharBuffer]Expected empty fallback buffer for getchars/charcount");
fallbackBuffer.InternalInitialize(bytes, charEnd);
}
// but we'll double check just to make sure.
internal unsafe byte GetNextByte()
{
- Contract.Assert(bytes < byteEnd, "[EncodingCharBuffer.GetNextByte]Expected more date");
+ Debug.Assert(bytes < byteEnd, "[EncodingCharBuffer.GetNextByte]Expected more date");
if (bytes >= byteEnd)
return 0;
return *(bytes++);
internal unsafe bool AddByte(byte b, int moreBytesExpected)
{
- Contract.Assert(moreBytesExpected >= 0, "[EncodingByteBuffer.AddByte]expected non-negative moreBytesExpected");
+ Debug.Assert(moreBytesExpected >= 0, "[EncodingByteBuffer.AddByte]expected non-negative moreBytesExpected");
if (bytes != null)
{
if (bytes >= byteEnd - moreBytesExpected)
fallbackBuffer.MovePrevious(); // don't use last fallback
else
{
- Contract.Assert(chars > charStart ||
+ Debug.Assert(chars > charStart ||
((bThrow == true) && (bytes == byteStart)),
"[EncodingByteBuffer.MovePrevious]expected previous data or throw");
if (chars > charStart)
// 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.Diagnostics.Contracts;
using System.Security;
{
// Validate parameters
- Contract.Assert(encoding != null); // this parameter should only be affected internally, so just do a debug check here
+ Debug.Assert(encoding != null); // this parameter should only be affected internally, so just do a debug check here
if (chars == null)
{
throw new ArgumentNullException(nameof(chars), Environment.GetResourceString("ArgumentNull_Array"));
public unsafe static int GetByteCount(Encoding encoding, string s)
{
- Contract.Assert(encoding != null);
+ Debug.Assert(encoding != null);
if (s == null)
{
string paramName = encoding is ASCIIEncoding ? "chars" : nameof(s); // ASCIIEncoding calls the string chars
public unsafe static int GetByteCount(Encoding encoding, char* chars, int count)
{
- Contract.Assert(encoding != null);
+ Debug.Assert(encoding != null);
if (chars == null)
{
throw new ArgumentNullException(nameof(chars), Environment.GetResourceString("ArgumentNull_Array"));
public unsafe static int GetBytes(Encoding encoding, string s, int charIndex, int charCount, byte[] bytes, int byteIndex)
{
- Contract.Assert(encoding != null);
+ Debug.Assert(encoding != null);
if (s == null || bytes == null)
{
string stringName = encoding is ASCIIEncoding ? "chars" : nameof(s); // ASCIIEncoding calls the first parameter chars
public unsafe static int GetBytes(Encoding encoding, char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
{
- Contract.Assert(encoding != null);
+ Debug.Assert(encoding != null);
if (chars == null || bytes == null)
{
throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), Environment.GetResourceString("ArgumentNull_Array"));
public unsafe static int GetBytes(Encoding encoding, char* chars, int charCount, byte* bytes, int byteCount)
{
- Contract.Assert(encoding != null);
+ Debug.Assert(encoding != null);
if (bytes == null || chars == null)
{
throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), Environment.GetResourceString("ArgumentNull_Array"));
public unsafe static int GetCharCount(Encoding encoding, byte[] bytes, int index, int count)
{
- Contract.Assert(encoding != null);
+ Debug.Assert(encoding != null);
if (bytes == null)
{
throw new ArgumentNullException(nameof(bytes), Environment.GetResourceString("ArgumentNull_Array"));
public unsafe static int GetCharCount(Encoding encoding, byte* bytes, int count)
{
- Contract.Assert(encoding != null);
+ Debug.Assert(encoding != null);
if (bytes == null)
{
throw new ArgumentNullException(nameof(bytes), Environment.GetResourceString("ArgumentNull_Array"));
public unsafe static int GetChars(Encoding encoding, byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
{
- Contract.Assert(encoding != null);
+ Debug.Assert(encoding != null);
if (bytes == null || chars == null)
{
throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), Environment.GetResourceString("ArgumentNull_Array"));
public unsafe static int GetChars(Encoding encoding, byte* bytes, int byteCount, char* chars, int charCount)
{
- Contract.Assert(encoding != null);
+ Debug.Assert(encoding != null);
if (bytes == null || chars == null)
{
throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), Environment.GetResourceString("ArgumentNull_Array"));
public unsafe static string GetString(Encoding encoding, byte[] bytes, int index, int count)
{
- Contract.Assert(encoding != null);
+ Debug.Assert(encoding != null);
if (bytes == null)
{
throw new ArgumentNullException(nameof(bytes), Environment.GetResourceString("ArgumentNull_Array"));
namespace System.Text
{
using System;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Text;
using System.Runtime.InteropServices;
{
// Set up our base, also throws if info was empty
DeserializeEncoding(info, context);
- Contract.Assert(info!=null, "[GB18030Encoding(Serialization...)] Expected null info to throw");
+ Debug.Assert(info!=null, "[GB18030Encoding(Serialization...)] Expected null info to throw");
// Already build our code page, fallbacks & read only, so we're good to go!
}
{
// Make sure to get the base stuff too This throws if info is null
SerializeEncoding(info, context);
- Contract.Assert(info!=null, "[GB18030.GetObjectData] Expected null info to throw");
+ Debug.Assert(info!=null, "[GB18030.GetObjectData] Expected null info to throw");
// Everett doesn't need more than the basics
}
// It was GB 18030 4 byte data, next <data> characters are 4 byte sequences.
while (data > 0)
{
- Contract.Assert(count4Byte <= GBLast4ByteCode,
+ Debug.Assert(count4Byte <= GBLast4ByteCode,
"[GB18030Encoding.LoadManagedCodePage] Found too many 4 byte codes in data table.");
// Set the 4 byte -> Unicode value
}
// unicodeCount should've wrapped back to 0
- Contract.Assert(unicodeCount == 0,
+ Debug.Assert(unicodeCount == 0,
"[GB18030Encoding.LoadManagedCodePage] Expected unicodeCount to wrap around to 0 as all chars were processed");
// We should've read in GBLast4ByteCode 4 byte sequences
- Contract.Assert(count4Byte == GBLast4ByteCode + 1,
+ Debug.Assert(count4Byte == GBLast4ByteCode + 1,
"[GB18030Encoding.LoadManagedCodePage] Expected 0x99FB to be last 4 byte offset, found 0x" + count4Byte.ToString("X4", CultureInfo.InvariantCulture));
// Need to flag ourselves saying we've built this CP.
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
// We'll allow null bytes as a count
-// Contract.Assert(bytes != null, "[GB18030Encoding.GetBytes]bytes is null");
- Contract.Assert(byteCount >= 0, "[GB18030Encoding.GetBytes]byteCount is negative");
- Contract.Assert(chars != null, "[GB18030Encoding.GetBytes]chars is null");
- Contract.Assert(charCount >= 0, "[GB18030Encoding.GetBytes]charCount is negative");
+// Debug.Assert(bytes != null, "[GB18030Encoding.GetBytes]bytes is null");
+ Debug.Assert(byteCount >= 0, "[GB18030Encoding.GetBytes]byteCount is negative");
+ Debug.Assert(chars != null, "[GB18030Encoding.GetBytes]chars is null");
+ Debug.Assert(charCount >= 0, "[GB18030Encoding.GetBytes]charCount is negative");
// Assert because we shouldn't be able to have a null encoder.
- Contract.Assert(encoderFallback != null, "[GB18030Encoding.GetBytes]Attempting to use null encoder fallback");
+ Debug.Assert(encoderFallback != null, "[GB18030Encoding.GetBytes]Attempting to use null encoder fallback");
// Get any left over characters
char charLeftOver = (char)0;
// Have to check for charLeftOver
if (charLeftOver != 0)
{
- Contract.Assert(Char.IsHighSurrogate(charLeftOver),
+ Debug.Assert(Char.IsHighSurrogate(charLeftOver),
"[GB18030Encoding.GetBytes] leftover character should be high surrogate, not 0x" + ((int)charLeftOver).ToString("X4", CultureInfo.InvariantCulture));
// If our next char isn't a low surrogate, then we need to do fallback.
offset /= 0x7e;
byte byte2 = (byte)((offset % 0x0a) + 0x30);
offset /= 0x0a;
- Contract.Assert(offset < 0x6f,
+ Debug.Assert(offset < 0x6f,
"[GB18030Encoding.GetBytes](1) Expected offset < 0x6f, not 0x" + offset.ToString("X2", CultureInfo.InvariantCulture));
charLeftOver = (char)0;
iBytes /= 0x7e;
byte byte2 = (byte)((iBytes % 0x0a) + 0x30);
iBytes /= 0x0a;
- Contract.Assert(iBytes < 0x7e,
+ Debug.Assert(iBytes < 0x7e,
"[GB18030Encoding.GetBytes]Expected iBytes < 0x7e, not 0x" + iBytes.ToString("X2", CultureInfo.InvariantCulture));
if (!buffer.AddByte((byte)(iBytes + 0x81), byte2, byte3, byte4))
break;
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
// We'll allow null chars as a count
- Contract.Assert(bytes != null, "[GB18030Encoding.GetChars]bytes is null");
- Contract.Assert(byteCount >= 0, "[GB18030Encoding.GetChars]byteCount is negative");
-// Contract.Assert(chars != null, "[GB18030Encoding.GetChars]chars is null");
- Contract.Assert(charCount >= 0, "[GB18030Encoding.GetChars]charCount is negative");
+ Debug.Assert(bytes != null, "[GB18030Encoding.GetChars]bytes is null");
+ Debug.Assert(byteCount >= 0, "[GB18030Encoding.GetChars]byteCount is negative");
+// Debug.Assert(chars != null, "[GB18030Encoding.GetChars]chars is null");
+ Debug.Assert(charCount >= 0, "[GB18030Encoding.GetChars]charCount is negative");
// Fix our decoder
GB18030Decoder decoder = (GB18030Decoder)baseDecoder;
namespace System.Text
{
using System;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.Serialization;
defaultCodePage = codePage - 57000;
// Legal windows code pages are between Devanagari and Punjabi
- Contract.Assert(defaultCodePage >= CodeDevanagari && defaultCodePage <= CodePunjabi,
+ Debug.Assert(defaultCodePage >= CodeDevanagari && defaultCodePage <= CodePunjabi,
"[ISCIIEncoding] Code page (" + codePage + " isn't supported by ISCIIEncoding!");
// This shouldn't really be possible
{
// Actually this can't ever get called, MLangCodePageEncoding is our proxy
// (In Everett this was done by MLang)
- Contract.Assert(false, "Didn't expect to make it to ISCIIEncoding serialization constructor");
+ Debug.Assert(false, "Didn't expect to make it to ISCIIEncoding serialization constructor");
throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException"));
}
{
// Make sure to get the base stuff too This throws if info is null
SerializeEncoding(info, context);
- Contract.Assert(info!=null, "[ISCIIEncoding.GetObjectData] Expected null info to throw");
+ Debug.Assert(info!=null, "[ISCIIEncoding.GetObjectData] Expected null info to throw");
// Just need Everett MLangCodePageEncoding maxCharSize
info.AddValue("m_maxByteSize", 2);
byte* bytes, int byteCount, EncoderNLS baseEncoder)
{
// Allow null bytes for counting
- Contract.Assert(chars != null, "[ISCIIEncoding.GetBytes]chars!=null");
-// Contract.Assert(bytes != null, "[ISCIIEncoding.GetBytes]bytes!=null");
- Contract.Assert(charCount >=0, "[ISCIIEncoding.GetBytes]charCount >=0");
- Contract.Assert(byteCount >=0, "[ISCIIEncoding.GetBytes]byteCount >=0");
+ Debug.Assert(chars != null, "[ISCIIEncoding.GetBytes]chars!=null");
+// Debug.Assert(bytes != null, "[ISCIIEncoding.GetBytes]bytes!=null");
+ Debug.Assert(charCount >=0, "[ISCIIEncoding.GetBytes]charCount >=0");
+ Debug.Assert(byteCount >=0, "[ISCIIEncoding.GetBytes]byteCount >=0");
// Need the ISCII Encoder
ISCIIEncoder encoder = (ISCIIEncoder) baseEncoder;
// See if our code page ("font" in ISCII spec) has to change
// (This if doesn't add character, just changes character set)
- Contract.Assert(indicScript!=0, "[ISCIIEncoding.GetBytes]expected an indic script value");
+ Debug.Assert(indicScript!=0, "[ISCIIEncoding.GetBytes]expected an indic script value");
if (indicScript != currentCodePage)
{
// It changed, spit out the ATR
currentCodePage = indicScript;
// We only know how to map from Unicode to pages from Devanagari to Punjabi (2 to 11)
- Contract.Assert(currentCodePage >= CodeDevanagari && currentCodePage <= CodePunjabi,
+ Debug.Assert(currentCodePage >= CodeDevanagari && currentCodePage <= CodePunjabi,
"[ISCIIEncoding.GetBytes]Code page (" + currentCodePage + " shouldn't appear in ISCII from Unicode table!");
}
if (indicTwoBytes != 0)
{
// This one needs another byte
- Contract.Assert((indicTwoBytes >> 12) > 0 && (indicTwoBytes >> 12) <= 3,
+ Debug.Assert((indicTwoBytes >> 12) > 0 && (indicTwoBytes >> 12) <= 3,
"[ISCIIEncoding.GetBytes]Expected indicTwoBytes from 1-3, not " + (indicTwoBytes >> 12));
// Already did buffer checking, but...
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
// Allow null chars for counting
- Contract.Assert(bytes != null, "[ISCIIEncoding.GetChars]bytes is null");
- Contract.Assert(byteCount >= 0, "[ISCIIEncoding.GetChars]byteCount is negative");
-// Contract.Assert(chars != null, "[ISCIIEncoding.GetChars]chars is null");
- Contract.Assert(charCount >= 0, "[ISCIIEncoding.GetChars]charCount is negative");
+ Debug.Assert(bytes != null, "[ISCIIEncoding.GetChars]bytes is null");
+ Debug.Assert(byteCount >= 0, "[ISCIIEncoding.GetChars]byteCount is negative");
+// Debug.Assert(chars != null, "[ISCIIEncoding.GetChars]chars is null");
+ Debug.Assert(charCount >= 0, "[ISCIIEncoding.GetChars]charCount is negative");
// Need the ISCII Decoder
ISCIIDecoder decoder = (ISCIIDecoder) baseDecoder;
// Get our current code page index (some code pages are dups)
int currentCodePageIndex = -1;
- Contract.Assert(currentCodePage >= CodeDevanagari && currentCodePage <= CodePunjabi,
+ Debug.Assert(currentCodePage >= CodeDevanagari && currentCodePage <= CodePunjabi,
"[ISCIIEncoding.GetChars]Decoder code page must be >= Devanagari and <= Punjabi, not " + currentCodePage);
if (currentCodePage >= CodeDevanagari && currentCodePage <= CodePunjabi)
bLastSpecial = false;
// One and only one of our flags should be set
- Contract.Assert(((bLastVirama ? 1 : 0) + (bLastATR ? 1 : 0) +
+ Debug.Assert(((bLastVirama ? 1 : 0) + (bLastATR ? 1 : 0) +
(bLastDevenagariStressAbbr ? 1 : 0) +
((cLastCharForNextNukta > 0) ? 1 : 0)) == 1,
String.Format(CultureInfo.InvariantCulture,
bLastATR = false;
// we know we can't have any of these other modes
- Contract.Assert(bLastVirama == false, "[ISCIIEncoding.GetChars] Expected no bLastVirama in bLastATR mode");
- Contract.Assert(bLastDevenagariStressAbbr == false, "[ISCIIEncoding.GetChars] Expected no bLastDevenagariStressAbbr in bLastATR mode");
- Contract.Assert(cLastCharForNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNextNukta in bLastATR mode");
- Contract.Assert(cLastCharForNoNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNoNextNukta in bLastATR mode");
+ Debug.Assert(bLastVirama == false, "[ISCIIEncoding.GetChars] Expected no bLastVirama in bLastATR mode");
+ Debug.Assert(bLastDevenagariStressAbbr == false, "[ISCIIEncoding.GetChars] Expected no bLastDevenagariStressAbbr in bLastATR mode");
+ Debug.Assert(cLastCharForNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNextNukta in bLastATR mode");
+ Debug.Assert(cLastCharForNoNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNoNextNukta in bLastATR mode");
// Keep processing this byte
}
bLastVirama = false;
// We know we can't have any of these other modes
- Contract.Assert(bLastATR == false, "[ISCIIEncoding.GetChars] Expected no bLastATR in bLastVirama mode");
- Contract.Assert(bLastDevenagariStressAbbr == false, "[ISCIIEncoding.GetChars] Expected no bLastDevenagariStressAbbr in bLastVirama mode");
- Contract.Assert(cLastCharForNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNextNukta in bLastVirama mode");
- Contract.Assert(cLastCharForNoNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNoNextNukta in bLastVirama mode");
+ Debug.Assert(bLastATR == false, "[ISCIIEncoding.GetChars] Expected no bLastATR in bLastVirama mode");
+ Debug.Assert(bLastDevenagariStressAbbr == false, "[ISCIIEncoding.GetChars] Expected no bLastDevenagariStressAbbr in bLastVirama mode");
+ Debug.Assert(cLastCharForNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNextNukta in bLastVirama mode");
+ Debug.Assert(cLastCharForNoNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNoNextNukta in bLastVirama mode");
}
else if (bLastDevenagariStressAbbr)
{
// (last character was added when mode was set)
bLastDevenagariStressAbbr = false;
- Contract.Assert(bLastATR == false, "[ISCIIEncoding.GetChars] Expected no bLastATR in bLastDevenagariStressAbbr mode");
- Contract.Assert(bLastVirama == false, "[ISCIIEncoding.GetChars] Expected no bLastVirama in bLastDevenagariStressAbbr mode");
- Contract.Assert(cLastCharForNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNextNukta in bLastDevenagariStressAbbr mode");
- Contract.Assert(cLastCharForNoNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNoNextNukta in bLastDevenagariStressAbbr mode");
+ Debug.Assert(bLastATR == false, "[ISCIIEncoding.GetChars] Expected no bLastATR in bLastDevenagariStressAbbr mode");
+ Debug.Assert(bLastVirama == false, "[ISCIIEncoding.GetChars] Expected no bLastVirama in bLastDevenagariStressAbbr mode");
+ Debug.Assert(cLastCharForNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNextNukta in bLastDevenagariStressAbbr mode");
+ Debug.Assert(cLastCharForNoNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNoNextNukta in bLastDevenagariStressAbbr mode");
}
else
{
// We were checking for next char being a nukta
- Contract.Assert(cLastCharForNextNukta > 0 && cLastCharForNoNextNukta > 0,
+ Debug.Assert(cLastCharForNextNukta > 0 && cLastCharForNoNextNukta > 0,
"[ISCIIEncoding.GetChars]No other special case found, but cLastCharFor(No)NextNukta variable(s) aren't set.");
// We'll either add combined char or last char
// Keep processing this byte, turn off mode.
cLastCharForNextNukta = cLastCharForNoNextNukta = '\0';
- Contract.Assert(bLastATR == false, "[ISCIIEncoding.GetChars] Expected no bLastATR in cLastCharForNextNukta mode");
- Contract.Assert(bLastVirama == false, "[ISCIIEncoding.GetChars] Expected no bLastVirama in cLastCharForNextNukta mode");
- Contract.Assert(bLastDevenagariStressAbbr == false, "[ISCIIEncoding.GetChars] Expected no bLastDevenagariStressAbbr in cLastCharForNextNukta mode");
+ Debug.Assert(bLastATR == false, "[ISCIIEncoding.GetChars] Expected no bLastATR in cLastCharForNextNukta mode");
+ Debug.Assert(bLastVirama == false, "[ISCIIEncoding.GetChars] Expected no bLastVirama in cLastCharForNextNukta mode");
+ Debug.Assert(bLastDevenagariStressAbbr == false, "[ISCIIEncoding.GetChars] Expected no bLastDevenagariStressAbbr in cLastCharForNextNukta mode");
}
}
// Now bLastSpecial should be false and all flags false.
- Contract.Assert (!bLastSpecial && !bLastDevenagariStressAbbr && !bLastVirama && !bLastATR &&
+ Debug.Assert (!bLastSpecial && !bLastDevenagariStressAbbr && !bLastVirama && !bLastATR &&
cLastCharForNextNukta == '\0',
"[ISCIIEncoding.GetChars]No special state for last code point should exist at this point.");
continue;
}
- Contract.Assert (currentCodePageIndex != -1, "[ISCIIEncoding.GetChars]Expected valid currentCodePageIndex != -1");
+ Debug.Assert (currentCodePageIndex != -1, "[ISCIIEncoding.GetChars]Expected valid currentCodePageIndex != -1");
char ch = IndicMapping[currentCodePageIndex, 0, b - MultiByteBegin];
char cAlt = IndicMapping[currentCodePageIndex, 1, b - MultiByteBegin];
}
// We must be the Devenagari special case for F0, B8 & F0, BF
- Contract.Assert(currentCodePage == CodeDevanagari && b == DevenagariExt,
+ Debug.Assert(currentCodePage == CodeDevanagari && b == DevenagariExt,
String.Format(CultureInfo.InvariantCulture,
"[ISCIIEncoding.GetChars] Devenagari special case must {0} not {1} or in Devanagari code page {2} not {3}.",
DevenagariExt, b, CodeDevanagari, currentCodePage));
cLastCharForNoNextNukta != '\0' || bLastATR || bLastDevenagariStressAbbr)
{
// Either not flushing or had state (from convert)
- Contract.Assert(!decoder.MustFlush || !decoder.m_throwOnOverflow,
+ Debug.Assert(!decoder.MustFlush || !decoder.m_throwOnOverflow,
"[ISCIIEncoding.GetChars]Expected no state or not converting or not flushing");
decoder.currentCodePage = currentCodePage;
decoder.bLastVirama = bLastVirama;
namespace System.Text
{
using System.Globalization;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Text;
using System.Runtime.InteropServices;
internal ISO2022Encoding(SerializationInfo info, StreamingContext context) : base(info, context)
{
// Actually this can't ever get called, CodePageEncoding is our proxy
- Contract.Assert(false, "Didn't expect to make it to DBCSCodePageEncoding serialization constructor");
+ Debug.Assert(false, "Didn't expect to make it to DBCSCodePageEncoding serialization constructor");
throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException"));
}
strFormat = "CodePage_{0}_{1}_{2}_{3}_{4}_HZ";
break;
default:
- Contract.Assert(false, "[ISO2022Encoding.GetMemorySectionName] Don't expect to get here for code page " + this.CodePage);
+ Debug.Assert(false, "[ISO2022Encoding.GetMemorySectionName] Don't expect to get here for code page " + this.CodePage);
strFormat = "CodePage_{0}_{1}_{2}_{3}_{4}";
break;
}
internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS baseEncoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
- Contract.Assert(count >= 0, "[ISO2022Encoding.GetByteCount]count is negative");
- Contract.Assert(chars != null, "[ISO2022Encoding.GetByteCount]chars is null");
+ Debug.Assert(count >= 0, "[ISO2022Encoding.GetByteCount]count is negative");
+ Debug.Assert(chars != null, "[ISO2022Encoding.GetByteCount]chars is null");
// Just call GetBytes with null byte* to get count
return GetBytes(chars, count, null, 0, baseEncoder);
byte* bytes, int byteCount, EncoderNLS baseEncoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
- Contract.Assert(chars != null, "[ISO2022Encoding.GetBytes]chars is null");
- Contract.Assert(byteCount >= 0, "[ISO2022Encoding.GetBytes]byteCount is negative");
- Contract.Assert(charCount >= 0, "[ISO2022Encoding.GetBytes]charCount is negative");
+ Debug.Assert(chars != null, "[ISO2022Encoding.GetBytes]chars is null");
+ Debug.Assert(byteCount >= 0, "[ISO2022Encoding.GetBytes]byteCount is negative");
+ Debug.Assert(charCount >= 0, "[ISO2022Encoding.GetBytes]charCount is negative");
// Assert because we shouldn't be able to have a null encoder.
- Contract.Assert(encoderFallback != null, "[ISO2022Encoding.GetBytes]Attempting to use null encoder fallback");
+ Debug.Assert(encoderFallback != null, "[ISO2022Encoding.GetBytes]Attempting to use null encoder fallback");
// Fix our encoder
ISO2022Encoder encoder = (ISO2022Encoder)baseEncoder;
internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder)
{
// Just assert, we're called internally so these should be safe, checked already
- Contract.Assert(bytes != null, "[ISO2022Encoding.GetCharCount]bytes is null");
- Contract.Assert(count >= 0, "[ISO2022Encoding.GetCharCount]byteCount is negative");
+ Debug.Assert(bytes != null, "[ISO2022Encoding.GetCharCount]bytes is null");
+ Debug.Assert(count >= 0, "[ISO2022Encoding.GetCharCount]byteCount is negative");
// Just call getChars with null char* to get count
return GetChars(bytes, count, null, 0, baseDecoder);
char* chars, int charCount, DecoderNLS baseDecoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
- Contract.Assert(bytes != null, "[ISO2022Encoding.GetChars]bytes is null");
- Contract.Assert(byteCount >= 0, "[ISO2022Encoding.GetChars]byteCount is negative");
- Contract.Assert(charCount >= 0, "[ISO2022Encoding.GetChars]charCount is negative");
+ Debug.Assert(bytes != null, "[ISO2022Encoding.GetChars]bytes is null");
+ Debug.Assert(byteCount >= 0, "[ISO2022Encoding.GetChars]byteCount is negative");
+ Debug.Assert(charCount >= 0, "[ISO2022Encoding.GetChars]charCount is negative");
// Fix our decoder
ISO2022Decoder decoder = (ISO2022Decoder)baseDecoder;
iCount = GetCharsCP52936( bytes, byteCount, chars, charCount, decoder);
break;
default:
- Contract.Assert(false, "[ISO2022Encoding.GetChars] had unexpected code page");
+ Debug.Assert(false, "[ISO2022Encoding.GetChars] had unexpected code page");
break;
}
// We may have a left over character from last time, try and process it.
if (charLeftOver > 0)
{
- Contract.Assert(Char.IsHighSurrogate(charLeftOver), "[ISO2022Encoding.GetBytesCP5022xJP]leftover character should be high surrogate");
+ Debug.Assert(Char.IsHighSurrogate(charLeftOver), "[ISO2022Encoding.GetBytesCP5022xJP]leftover character should be high surrogate");
// It has to be a high surrogate, which we don't support, so it has to be a fallback
buffer.Fallback(charLeftOver);
else
{
// 50221 does halfwidth katakana by escape sequence
- Contract.Assert(CodePage == 50221, "[ISO2022Encoding.GetBytesCP5022xJP]Expected Code Page 50221");
+ Debug.Assert(CodePage == 50221, "[ISO2022Encoding.GetBytesCP5022xJP]Expected Code Page 50221");
// Add our escape sequence
if (!buffer.AddByte(ESCAPE, unchecked((byte)'('), unchecked((byte)'I')))
// We may have a l left over character from last time, try and process it.
if (charLeftOver > 0)
{
- Contract.Assert(Char.IsHighSurrogate(charLeftOver), "[ISO2022Encoding.GetBytesCP50225KR]leftover character should be high surrogate");
+ Debug.Assert(Char.IsHighSurrogate(charLeftOver), "[ISO2022Encoding.GetBytesCP50225KR]leftover character should be high surrogate");
// It has to be a high surrogate, which we don't support, so it has to be a fallback
buffer.Fallback(charLeftOver);
if (!encoder.MustFlush || encoder.charLeftOver != (char)0)
{
// We should be not flushing or converting
- Contract.Assert(!encoder.MustFlush || !encoder.m_throwOnOverflow,
+ Debug.Assert(!encoder.MustFlush || !encoder.m_throwOnOverflow,
"[ISO2022Encoding.GetBytesCP50225KR]Expected no left over data or not flushing or not converting");
encoder.shiftInOutMode = shiftOutMode;
}
// We may have a left over character from last time, try and process it.
if (charLeftOver > 0)
{
- Contract.Assert(Char.IsHighSurrogate(charLeftOver), "[ISO2022Encoding.GetBytesCP52936]leftover character should be high surrogate");
+ Debug.Assert(Char.IsHighSurrogate(charLeftOver), "[ISO2022Encoding.GetBytesCP52936]leftover character should be high surrogate");
// It has to be a high surrogate, which we don't support, so it has to be a fallback
buffer.Fallback(charLeftOver);
if (!decoder.MustFlush || escapeCount != 0)
{
// Either not flushing or had state (from convert)
- Contract.Assert(!decoder.MustFlush || !decoder.m_throwOnOverflow,
+ Debug.Assert(!decoder.MustFlush || !decoder.m_throwOnOverflow,
"[ISO2022Encoding.GetCharsCP5022xJP]Expected no state or not converting or not flushing");
decoder.currentMode = currentMode;
private byte DecrementEscapeBytes(ref byte[] bytes, ref int count)
{
- Contract.Assert(count > 0, "[ISO2022Encoding.DecrementEscapeBytes]count > 0");
+ Debug.Assert(count > 0, "[ISO2022Encoding.DecrementEscapeBytes]count > 0");
// Decrement our count
count--;
if (!decoder.MustFlush || escapeCount != 0)
{
// Either not flushing or had state (from convert)
- Contract.Assert(!decoder.MustFlush || !decoder.m_throwOnOverflow,
+ Debug.Assert(!decoder.MustFlush || !decoder.m_throwOnOverflow,
"[ISO2022Encoding.GetCharsCP50225KR]Expected no state or not converting or not flushing");
decoder.currentMode = currentMode;
private unsafe int GetCharsCP52936(byte* bytes, int byteCount,
char* chars, int charCount, ISO2022Decoder decoder)
{
- Contract.Assert(byteCount >=0, "[ISO2022Encoding.GetCharsCP52936]count >=0");
- Contract.Assert(bytes!=null, "[ISO2022Encoding.GetCharsCP52936]bytes!=null");
+ Debug.Assert(byteCount >=0, "[ISO2022Encoding.GetCharsCP52936]count >=0");
+ Debug.Assert(bytes!=null, "[ISO2022Encoding.GetCharsCP52936]bytes!=null");
// Get our info.
Encoding.EncodingCharBuffer buffer = new Encoding.EncodingCharBuffer(
if (currentMode != ISO2022Modes.ModeASCII)
{
// Should be ModeHZ
- Contract.Assert(currentMode == ISO2022Modes.ModeHZ, "[ISO2022Encoding.GetCharsCP52936]Expected ModeHZ");
+ Debug.Assert(currentMode == ISO2022Modes.ModeHZ, "[ISO2022Encoding.GetCharsCP52936]Expected ModeHZ");
char cm;
// Everett allowed characters < 0x20 to be passed as if they were ASCII
else
{
// Either not flushing or had state (from convert)
- Contract.Assert(!decoder.MustFlush || !decoder.m_throwOnOverflow,
+ Debug.Assert(!decoder.MustFlush || !decoder.m_throwOnOverflow,
"[ISO2022Encoding.GetCharsCP52936]Expected no state or not converting or not flushing");
decoder.currentMode = currentMode;
namespace System.Text
{
using System;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.InteropServices;
{
// Make sure to get the base stuff too This throws if info is null
SerializeEncoding(info, context);
- Contract.Assert(info!=null, "[Latin1Encoding.GetObjectData] Expected null info to throw");
+ Debug.Assert(info!=null, "[Latin1Encoding.GetObjectData] Expected null info to throw");
// In Everett this is a CodePageEncoding, so it needs maxCharSize
info.AddValue("CodePageEncoding+maxCharSize", 1);
internal override unsafe int GetByteCount(char* chars, int charCount, EncoderNLS encoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
- Contract.Assert(charCount >= 0, "[Latin1Encoding.GetByteCount]count is negative");
- Contract.Assert(chars != null, "[Latin1Encoding.GetByteCount]chars is null");
+ Debug.Assert(charCount >= 0, "[Latin1Encoding.GetByteCount]count is negative");
+ Debug.Assert(chars != null, "[Latin1Encoding.GetByteCount]chars is null");
// Assert because we shouldn't be able to have a null encoder.
- Contract.Assert(encoderFallback != null, "[Latin1Encoding.GetByteCount]Attempting to use null fallback encoder");
+ Debug.Assert(encoderFallback != null, "[Latin1Encoding.GetByteCount]Attempting to use null fallback encoder");
char charLeftOver = (char)0;
if (encoder != null)
{
charLeftOver = encoder.charLeftOver;
- Contract.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
+ Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
"[Latin1Encoding.GetByteCount]leftover character should be high surrogate");
fallback = encoder.Fallback as EncoderReplacementFallback;
// Verify that we have no fallbackbuffer, for Latin1 its always empty, so just assert
- Contract.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
+ Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
encoder.FallbackBuffer.Remaining == 0,
"[Latin1CodePageEncoding.GetByteCount]Expected empty fallback buffer");
}
if (charLeftOver > 0)
{
// Initialize the buffer
- Contract.Assert(encoder != null,
+ Debug.Assert(encoder != null,
"[Latin1Encoding.GetByteCount]Expected encoder if we have charLeftOver");
fallbackBuffer = encoder.FallbackBuffer;
fallbackBuffer.InternalInitialize(chars, charEnd, encoder, false);
byteCount++;
}
- Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
+ Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
"[Latin1Encoding.GetByteCount]Expected Empty fallback buffer");
return byteCount;
byte* bytes, int byteCount, EncoderNLS encoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
- Contract.Assert(bytes != null, "[Latin1Encoding.GetBytes]bytes is null");
- Contract.Assert(byteCount >= 0, "[Latin1Encoding.GetBytes]byteCount is negative");
- Contract.Assert(chars != null, "[Latin1Encoding.GetBytes]chars is null");
- Contract.Assert(charCount >= 0, "[Latin1Encoding.GetBytes]charCount is negative");
+ Debug.Assert(bytes != null, "[Latin1Encoding.GetBytes]bytes is null");
+ Debug.Assert(byteCount >= 0, "[Latin1Encoding.GetBytes]byteCount is negative");
+ Debug.Assert(chars != null, "[Latin1Encoding.GetBytes]chars is null");
+ Debug.Assert(charCount >= 0, "[Latin1Encoding.GetBytes]charCount is negative");
// Assert because we shouldn't be able to have a null encoder.
- Contract.Assert(encoderFallback != null, "[Latin1Encoding.GetBytes]Attempting to use null encoder fallback");
+ Debug.Assert(encoderFallback != null, "[Latin1Encoding.GetBytes]Attempting to use null encoder fallback");
// Get any left over characters & check fast or slower fallback type
char charLeftOver = (char)0;
{
charLeftOver = encoder.charLeftOver;
fallback = encoder.Fallback as EncoderReplacementFallback;
- Contract.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
+ Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
"[Latin1Encoding.GetBytes]leftover character should be high surrogate");
// Verify that we have no fallbackbuffer, for ASCII its always empty, so just assert
- Contract.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
+ Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
encoder.FallbackBuffer.Remaining == 0,
"[Latin1CodePageEncoding.GetBytes]Expected empty fallback buffer");
}
{
// Since left over char was a surrogate, it'll have to be fallen back.
// Get Fallback
- Contract.Assert(encoder != null,
+ Debug.Assert(encoder != null,
"[Latin1Encoding.GetBytes]Expected encoder if we have charLeftOver");
fallbackBuffer = encoder.FallbackBuffer;
fallbackBuffer.InternalInitialize(chars, charEnd, encoder, true);
{
// Didn't use this char, throw it. Chars should've advanced by now
// If we had encoder fallback data it would've thrown before the loop
- Contract.Assert(chars > charStart,
+ Debug.Assert(chars > charStart,
"[Latin1Encoding.GetBytes]Expected chars to have advanced (fallback case)");
chars--;
fallbackBuffer.InternalReset();
if (bytes >= byteEnd)
{
// didn't use this char, we'll throw or use buffer
- Contract.Assert(fallbackBuffer == null || fallbackBuffer.bFallingBack == false,
+ Debug.Assert(fallbackBuffer == null || fallbackBuffer.bFallingBack == false,
"[Latin1Encoding.GetBytes]Expected fallback to have throw initially if insufficient space");
if (fallbackBuffer == null || fallbackBuffer.bFallingBack == false)
{
- Contract.Assert(chars > charStart,
+ Debug.Assert(chars > charStart,
"[Latin1Encoding.GetBytes]Expected chars to have advanced (fallback case)");
chars--; // don't use last char
}
encoder.m_charsUsed = (int)(chars - charStart);
}
- Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
+ Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
"[Latin1Encoding.GetBytes]Expected Empty fallback buffer");
return (int)(bytes - byteStart);
internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS decoder)
{
// Just assert, we're called internally so these should be safe, checked already
- Contract.Assert(bytes != null, "[Latin1Encoding.GetCharCount]bytes is null");
- Contract.Assert(count >= 0, "[Latin1Encoding.GetCharCount]byteCount is negative");
+ Debug.Assert(bytes != null, "[Latin1Encoding.GetCharCount]bytes is null");
+ Debug.Assert(count >= 0, "[Latin1Encoding.GetCharCount]byteCount is negative");
// Just return length, SBCS stay the same length because they don't map to surrogate
// pairs and we don't have to fallback because all latin1Encoding code points are unicode
char* chars, int charCount, DecoderNLS decoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
- Contract.Assert(bytes != null, "[Latin1Encoding.GetChars]bytes is null");
- Contract.Assert(byteCount >= 0, "[Latin1Encoding.GetChars]byteCount is negative");
- Contract.Assert(chars != null, "[Latin1Encoding.GetChars]chars is null");
- Contract.Assert(charCount >= 0, "[Latin1Encoding.GetChars]charCount is negative");
+ Debug.Assert(bytes != null, "[Latin1Encoding.GetChars]bytes is null");
+ Debug.Assert(byteCount >= 0, "[Latin1Encoding.GetChars]byteCount is negative");
+ Debug.Assert(chars != null, "[Latin1Encoding.GetChars]chars is null");
+ Debug.Assert(charCount >= 0, "[Latin1Encoding.GetChars]charCount is negative");
// Need byteCount chars, otherwise too small buffer
if (charCount < byteCount)
using System;
using System.Runtime.Serialization;
using System.Security.Permissions;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
/*=================================MLangCodePageEncoding==================================
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
// We cannot ever call this.
- Contract.Assert(false, "Didn't expect to make it to MLangCodePageEncoding ISerializable.GetObjectData");
+ Debug.Assert(false, "Didn't expect to make it to MLangCodePageEncoding ISerializable.GetObjectData");
throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException"));
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
// We cannot ever call this.
- Contract.Assert(false, "Didn't expect to make it to MLangCodePageEncoding.MLangEncoder.GetObjectData");
+ Debug.Assert(false, "Didn't expect to make it to MLangCodePageEncoding.MLangEncoder.GetObjectData");
throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException"));
}
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
// We cannot ever call this.
- Contract.Assert(false, "Didn't expect to make it to MLangCodePageEncoding.MLangDecoder.GetObjectData");
+ Debug.Assert(false, "Didn't expect to make it to MLangCodePageEncoding.MLangDecoder.GetObjectData");
throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException"));
}
}
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
// This internal class wraps up our normalization behavior
{
// Do appropriate stuff for the individual errors:
case ERROR_INSUFFICIENT_BUFFER:
- Contract.Assert(iLength > cBuffer.Length, "Buffer overflow should have iLength > cBuffer.Length");
+ Debug.Assert(iLength > cBuffer.Length, "Buffer overflow should have iLength > cBuffer.Length");
continue;
case ERROR_INVALID_PARAMETER:
namespace System.Text
{
using System;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Text;
using System.Threading;
internal SBCSCodePageEncoding(SerializationInfo info, StreamingContext context) : base(0)
{
// Actually this can't ever get called, CodePageEncoding is our proxy
- Contract.Assert(false, "Didn't expect to make it to SBCSCodePageEncoding serialization constructor");
+ Debug.Assert(false, "Didn't expect to make it to SBCSCodePageEncoding serialization constructor");
throw new ArgumentNullException("this");
}
protected override unsafe void LoadManagedCodePage()
{
// Should be loading OUR code page
- Contract.Assert(pCodePage->CodePage == this.dataTableCodePage,
+ Debug.Assert(pCodePage->CodePage == this.dataTableCodePage,
"[SBCSCodePageEncoding.LoadManagedCodePage]Expected to load data table code page");
// Make sure we're really a 1 byte code page
// If its cached (& filled in) we don't have to do anything else
if (*mapCodePageCached != 0)
{
- Contract.Assert(*mapCodePageCached == this.dataTableCodePage,
+ Debug.Assert(*mapCodePageCached == this.dataTableCodePage,
"[DBCSCodePageEncoding.LoadManagedCodePage]Expected mapped section cached page to be same as data table code page. Cached : " +
*mapCodePageCached + " Expected:" + this.dataTableCodePage);
while ((byteTemp = *((ushort*)pData)) != 0)
{
- Contract.Assert(arrayTemp[byteTemp] == UNKNOWN_CHAR, String.Format(CultureInfo.InvariantCulture,
+ Debug.Assert(arrayTemp[byteTemp] == UNKNOWN_CHAR, String.Format(CultureInfo.InvariantCulture,
"[SBCSCodePageEncoding::ReadBestFitTable] Expected unallocated byte (not 0x{2:X2}) for best fit byte at 0x{0:X2} for code page {1}",
byteTemp, CodePage, (int)arrayTemp[byteTemp]));
pData += 2;
arrayTemp[iBestFitCount++] = mapBytesToUnicode[input];
// This won't work if it won't round trip.
- Contract.Assert(arrayTemp[iBestFitCount-1] != (char)0,
+ Debug.Assert(arrayTemp[iBestFitCount-1] != (char)0,
String.Format(CultureInfo.InvariantCulture,
"[SBCSCodePageEncoding.ReadBestFitTable] No valid Unicode value {0:X4} for round trip bytes {1:X4}, encoding {2}",
(int)mapBytesToUnicode[input], (int)input, CodePage));
internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS encoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
- Contract.Assert(count >= 0, "[SBCSCodePageEncoding.GetByteCount]count is negative");
- Contract.Assert(chars != null, "[SBCSCodePageEncoding.GetByteCount]chars is null");
+ Debug.Assert(count >= 0, "[SBCSCodePageEncoding.GetByteCount]count is negative");
+ Debug.Assert(chars != null, "[SBCSCodePageEncoding.GetByteCount]chars is null");
// Assert because we shouldn't be able to have a null encoder.
- Contract.Assert(encoderFallback != null, "[SBCSCodePageEncoding.GetByteCount]Attempting to use null fallback");
+ Debug.Assert(encoderFallback != null, "[SBCSCodePageEncoding.GetByteCount]Attempting to use null fallback");
CheckMemorySection();
if (encoder != null)
{
charLeftOver = encoder.charLeftOver;
- Contract.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
+ Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
"[SBCSCodePageEncoding.GetByteCount]leftover character should be high surrogate");
fallback = encoder.Fallback as EncoderReplacementFallback;
// Verify that we have no fallbackbuffer, actually for SBCS this is always empty, so just assert
- Contract.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
+ Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
encoder.FallbackBuffer.Remaining == 0,
"[SBCSCodePageEncoding.GetByteCount]Expected empty fallback buffer at start");
}
{
// Since left over char was a surrogate, it'll have to be fallen back.
// Get Fallback
- Contract.Assert(encoder != null, "[SBCSCodePageEncoding.GetByteCount]Expect to have encoder if we have a charLeftOver");
+ Debug.Assert(encoder != null, "[SBCSCodePageEncoding.GetByteCount]Expect to have encoder if we have a charLeftOver");
fallbackBuffer = encoder.FallbackBuffer;
fallbackBuffer.InternalInitialize(chars, charEnd, encoder, false);
byteCount++;
}
- Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
+ Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
"[SBCSEncoding.GetByteCount]Expected Empty fallback buffer at end");
return (int)byteCount;
byte* bytes, int byteCount, EncoderNLS encoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
- Contract.Assert(bytes != null, "[SBCSCodePageEncoding.GetBytes]bytes is null");
- Contract.Assert(byteCount >= 0, "[SBCSCodePageEncoding.GetBytes]byteCount is negative");
- Contract.Assert(chars != null, "[SBCSCodePageEncoding.GetBytes]chars is null");
- Contract.Assert(charCount >= 0, "[SBCSCodePageEncoding.GetBytes]charCount is negative");
+ Debug.Assert(bytes != null, "[SBCSCodePageEncoding.GetBytes]bytes is null");
+ Debug.Assert(byteCount >= 0, "[SBCSCodePageEncoding.GetBytes]byteCount is negative");
+ Debug.Assert(chars != null, "[SBCSCodePageEncoding.GetBytes]chars is null");
+ Debug.Assert(charCount >= 0, "[SBCSCodePageEncoding.GetBytes]charCount is negative");
// Assert because we shouldn't be able to have a null encoder.
- Contract.Assert(encoderFallback != null, "[SBCSCodePageEncoding.GetBytes]Attempting to use null encoder fallback");
+ Debug.Assert(encoderFallback != null, "[SBCSCodePageEncoding.GetBytes]Attempting to use null encoder fallback");
CheckMemorySection();
if (encoder != null)
{
charLeftOver = encoder.charLeftOver;
- Contract.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
+ Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
"[SBCSCodePageEncoding.GetBytes]leftover character should be high surrogate");
fallback = encoder.Fallback as EncoderReplacementFallback;
// Verify that we have no fallbackbuffer, for SBCS its always empty, so just assert
- Contract.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
+ Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
encoder.FallbackBuffer.Remaining == 0,
"[SBCSCodePageEncoding.GetBytes]Expected empty fallback buffer at start");
// if (encoder.m_throwOnOverflow && encoder.InternalHasFallbackBuffer &&
{
// Since left over char was a surrogate, it'll have to be fallen back.
// Get Fallback
- Contract.Assert(encoder != null, "[SBCSCodePageEncoding.GetBytes]Expect to have encoder if we have a charLeftOver");
+ Debug.Assert(encoder != null, "[SBCSCodePageEncoding.GetBytes]Expect to have encoder if we have a charLeftOver");
fallbackBuffer = encoder.FallbackBuffer;
fallbackBuffer.InternalInitialize(chars, charEnd, encoder, true);
if (fallbackBuffer.Remaining > byteEnd - bytes)
{
// Didn't use this char, reset it
- Contract.Assert(chars > charStart,
+ Debug.Assert(chars > charStart,
"[SBCSCodePageEncoding.GetBytes]Expected chars to have advanced (fallback)");
chars--;
fallbackBuffer.InternalReset();
if (bytes >= byteEnd)
{
// didn't use this char, we'll throw or use buffer
- Contract.Assert(fallbackBuffer == null || fallbackBuffer.bFallingBack == false,
+ Debug.Assert(fallbackBuffer == null || fallbackBuffer.bFallingBack == false,
"[SBCSCodePageEncoding.GetBytes]Expected to NOT be falling back");
if (fallbackBuffer == null || fallbackBuffer.bFallingBack == false)
{
- Contract.Assert(chars > charStart,
+ Debug.Assert(chars > charStart,
"[SBCSCodePageEncoding.GetBytes]Expected chars to have advanced (normal)");
chars--; // don't use last char
}
}
// Expect Empty fallback buffer for SBCS
- Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
+ Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
"[SBCSEncoding.GetBytes]Expected Empty fallback buffer at end");
return (int)(bytes - byteStart);
internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS decoder)
{
// Just assert, we're called internally so these should be safe, checked already
- Contract.Assert(bytes != null, "[SBCSCodePageEncoding.GetCharCount]bytes is null");
- Contract.Assert(count >= 0, "[SBCSCodePageEncoding.GetCharCount]byteCount is negative");
+ Debug.Assert(bytes != null, "[SBCSCodePageEncoding.GetCharCount]bytes is null");
+ Debug.Assert(count >= 0, "[SBCSCodePageEncoding.GetCharCount]byteCount is negative");
CheckMemorySection();
{
fallback = decoder.Fallback as DecoderReplacementFallback;
bUseBestFit = decoder.Fallback.IsMicrosoftBestFitFallback;
- Contract.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer ||
+ Debug.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer ||
decoder.FallbackBuffer.Remaining == 0,
"[SBCSCodePageEncoding.GetChars]Expected empty fallback buffer at start");
}
}
// Fallback buffer must be empty
- Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
+ Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
"[SBCSEncoding.GetCharCount]Expected Empty fallback buffer at end");
// Converted sequence is same length as input
char* chars, int charCount, DecoderNLS decoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
- Contract.Assert(bytes != null, "[SBCSCodePageEncoding.GetChars]bytes is null");
- Contract.Assert(byteCount >= 0, "[SBCSCodePageEncoding.GetChars]byteCount is negative");
- Contract.Assert(chars != null, "[SBCSCodePageEncoding.GetChars]chars is null");
- Contract.Assert(charCount >= 0, "[SBCSCodePageEncoding.GetChars]charCount is negative");
+ Debug.Assert(bytes != null, "[SBCSCodePageEncoding.GetChars]bytes is null");
+ Debug.Assert(byteCount >= 0, "[SBCSCodePageEncoding.GetChars]byteCount is negative");
+ Debug.Assert(chars != null, "[SBCSCodePageEncoding.GetChars]chars is null");
+ Debug.Assert(charCount >= 0, "[SBCSCodePageEncoding.GetChars]charCount is negative");
CheckMemorySection();
{
fallback = decoder.Fallback as DecoderReplacementFallback;
bUseBestFit = decoder.Fallback.IsMicrosoftBestFitFallback;
- Contract.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer ||
+ Debug.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer ||
decoder.FallbackBuffer.Remaining == 0,
"[SBCSCodePageEncoding.GetChars]Expected empty fallback buffer at start");
}
}
// Use fallback buffer
- Contract.Assert(bytes > byteStart,
+ Debug.Assert(bytes > byteStart,
"[SBCSCodePageEncoding.GetChars]Expected bytes to have advanced already (unknown byte)");
byteBuffer[0] = *(bytes - 1);
// Fallback adds fallback to chars, but doesn't increment chars unless the whole thing fits.
// Make sure we have buffer space
if (chars >= charEnd)
{
- Contract.Assert(bytes > byteStart,
+ Debug.Assert(bytes > byteStart,
"[SBCSCodePageEncoding.GetChars]Expected bytes to have advanced already (known byte)");
bytes--; // unused byte
ThrowCharsOverflow(decoder, bytes == byteStart); // throw?
decoder.m_bytesUsed = (int)(bytes - byteStart);
// Expect Empty fallback buffer for GetChars
- Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
+ Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
"[SBCSEncoding.GetChars]Expected Empty fallback buffer at end");
return (int)(chars - charStart);
using System.Security;
using System.Threading;
using System.Globalization;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Collections.Generic;
for (; ; )
{
// All blocks have copy of the maxCapacity.
- Contract.Assert(currentBlock.m_MaxCapacity == maxCapacity, "Bad maxCapacity");
- Contract.Assert(currentBlock.m_ChunkChars != null, "Empty Buffer");
+ Debug.Assert(currentBlock.m_MaxCapacity == maxCapacity, "Bad maxCapacity");
+ Debug.Assert(currentBlock.m_ChunkChars != null, "Empty Buffer");
- Contract.Assert(currentBlock.m_ChunkLength <= currentBlock.m_ChunkChars.Length, "Out of range length");
- Contract.Assert(currentBlock.m_ChunkLength >= 0, "Negative length");
- Contract.Assert(currentBlock.m_ChunkOffset >= 0, "Negative offset");
+ Debug.Assert(currentBlock.m_ChunkLength <= currentBlock.m_ChunkChars.Length, "Out of range length");
+ Debug.Assert(currentBlock.m_ChunkLength >= 0, "Negative length");
+ Debug.Assert(currentBlock.m_ChunkOffset >= 0, "Negative offset");
StringBuilder prevBlock = currentBlock.m_ChunkPrevious;
if (prevBlock == null)
{
- Contract.Assert(currentBlock.m_ChunkOffset == 0, "First chunk's offset is not 0");
+ Debug.Assert(currentBlock.m_ChunkOffset == 0, "First chunk's offset is not 0");
break;
}
// There are no gaps in the blocks.
- Contract.Assert(currentBlock.m_ChunkOffset == prevBlock.m_ChunkOffset + prevBlock.m_ChunkLength, "There is a gap between chunks!");
+ Debug.Assert(currentBlock.m_ChunkOffset == prevBlock.m_ChunkOffset + prevBlock.m_ChunkLength, "There is a gap between chunks!");
currentBlock = prevBlock;
}
}
{
m_ChunkLength = 0;
m_ChunkOffset = 0;
- Contract.Assert(Capacity >= originalCapacity, "setting the Length should never decrease the Capacity");
+ Debug.Assert(Capacity >= originalCapacity, "setting the Length should never decrease the Capacity");
return;
}
int newLen = originalCapacity - chunk.m_ChunkOffset;
char[] newArray = new char[newLen];
- Contract.Assert(newLen > chunk.m_ChunkChars.Length, "the new chunk should be larger than the one it is replacing");
+ Debug.Assert(newLen > chunk.m_ChunkChars.Length, "the new chunk should be larger than the one it is replacing");
Array.Copy(chunk.m_ChunkChars, newArray, chunk.m_ChunkLength);
m_ChunkChars = newArray;
m_ChunkLength = value - chunk.m_ChunkOffset;
VerifyClassInvariant();
}
- Contract.Assert(Capacity >= originalCapacity, "setting the Length should never decrease the Capacity");
+ Debug.Assert(Capacity >= originalCapacity, "setting the Length should never decrease the Capacity");
}
}
{
m_ChunkLength = idx;
ExpandByABlock(repeatCount);
- Contract.Assert(m_ChunkLength == 0, "Expand should create a new block");
+ Debug.Assert(m_ChunkLength == 0, "Expand should create a new block");
idx = 0;
}
}
if (insertingChars > MaxCapacity - this.Length) {
throw new OutOfMemoryException();
}
- Contract.Assert(insertingChars + this.Length < Int32.MaxValue);
+ Debug.Assert(insertingChars + this.Length < Int32.MaxValue);
StringBuilder chunk;
int indexInChunk;
chunk = FindChunkForIndex(index);
indexInChunk = index - chunk.m_ChunkOffset;
- Contract.Assert(chunk != null || count == 0, "Chunks ended prematurely");
+ Debug.Assert(chunk != null || count == 0, "Chunks ended prematurely");
}
}
VerifyClassInvariant();
// Expand the builder to add another chunk.
int restLength = valueCount - firstLength;
ExpandByABlock(restLength);
- Contract.Assert(m_ChunkLength == 0, "Expand did not make a new block");
+ Debug.Assert(m_ChunkLength == 0, "Expand did not make a new block");
// Copy the second chunk
ThreadSafeCopy(value + firstLength, m_ChunkChars, 0, restLength);
break;
int gapEnd = replacements[i];
- Contract.Assert(gapStart < sourceChunk.m_ChunkChars.Length, "gap starts at end of buffer. Should not happen");
- Contract.Assert(gapStart <= gapEnd, "negative gap size");
- Contract.Assert(gapEnd <= sourceChunk.m_ChunkLength, "gap too big");
+ Debug.Assert(gapStart < sourceChunk.m_ChunkChars.Length, "gap starts at end of buffer. Should not happen");
+ Debug.Assert(gapStart <= gapEnd, "negative gap size");
+ Debug.Assert(gapEnd <= sourceChunk.m_ChunkLength, "gap too big");
if (delta != 0) // can skip the sliding of gaps if source an target string are the same size.
{
// Copy the gap data between the current replacement and the the next replacement
else
{
targetIndexInChunk += gapEnd - gapStart;
- Contract.Assert(targetIndexInChunk <= targetChunk.m_ChunkLength, "gap not in chunk");
+ Debug.Assert(targetIndexInChunk <= targetChunk.m_ChunkLength, "gap not in chunk");
}
}
for (; ; )
{
int lengthInChunk = chunk.m_ChunkLength - indexInChunk;
- Contract.Assert(lengthInChunk >= 0, "index not in chunk");
+ Debug.Assert(lengthInChunk >= 0, "index not in chunk");
int lengthToCopy = Math.Min(lengthInChunk, count);
ThreadSafeCopy(value, chunk.m_ChunkChars, indexInChunk, lengthToCopy);
/// <returns></returns>
private StringBuilder FindChunkForIndex(int index)
{
- Contract.Assert(0 <= index && index <= Length, "index not in string");
+ Debug.Assert(0 <= index && index <= Length, "index not in string");
StringBuilder ret = this;
while (ret.m_ChunkOffset > index)
ret = ret.m_ChunkPrevious;
- Contract.Assert(ret != null, "index not in string");
+ Debug.Assert(ret != null, "index not in string");
return ret;
}
/// <returns></returns>
private StringBuilder FindChunkForByte(int byteIndex)
{
- Contract.Assert(0 <= byteIndex && byteIndex <= Length*sizeof(char), "Byte Index not in string");
+ Debug.Assert(0 <= byteIndex && byteIndex <= Length*sizeof(char), "Byte Index not in string");
StringBuilder ret = this;
while (ret.m_ChunkOffset*sizeof(char) > byteIndex)
ret = ret.m_ChunkPrevious;
- Contract.Assert(ret != null, "Byte Index not in string");
+ Debug.Assert(ret != null, "Byte Index not in string");
return ret;
}
private void MakeRoom(int index, int count, out StringBuilder chunk, out int indexInChunk, bool doneMoveFollowingChars)
{
VerifyClassInvariant();
- Contract.Assert(count > 0, "Count must be strictly positive");
- Contract.Assert(index >= 0, "Index can't be negative");
+ Debug.Assert(count > 0, "Count must be strictly positive");
+ Debug.Assert(index >= 0, "Index can't be negative");
if (count + Length > m_MaxCapacity || count + Length < count)
throw new ArgumentOutOfRangeException("requiredLength", Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity"));
/// </summary>
private StringBuilder(int size, int maxCapacity, StringBuilder previousBlock)
{
- Contract.Assert(size > 0, "size not positive");
- Contract.Assert(maxCapacity > 0, "maxCapacity not positive");
+ Debug.Assert(size > 0, "size not positive");
+ Debug.Assert(maxCapacity > 0, "maxCapacity not positive");
m_ChunkChars = new char[size];
m_MaxCapacity = maxCapacity;
m_ChunkPrevious = previousBlock;
private void Remove(int startIndex, int count, out StringBuilder chunk, out int indexInChunk)
{
VerifyClassInvariant();
- Contract.Assert(startIndex >= 0 && startIndex < Length, "startIndex not in string");
+ Debug.Assert(startIndex >= 0 && startIndex < Length, "startIndex not in string");
int endIndex = startIndex + count;
}
chunk = chunk.m_ChunkPrevious;
}
- Contract.Assert(chunk != null, "fell off beginning of string!");
+ Debug.Assert(chunk != null, "fell off beginning of string!");
int copyTargetIndexInChunk = indexInChunk;
int copyCount = endChunk.m_ChunkLength - endIndexInChunk;
if (copyTargetIndexInChunk != endIndexInChunk) // Sometimes no move is necessary
ThreadSafeCopy(endChunk.m_ChunkChars, endIndexInChunk, endChunk.m_ChunkChars, copyTargetIndexInChunk, copyCount);
- Contract.Assert(chunk != null, "fell off beginning of string!");
+ Debug.Assert(chunk != null, "fell off beginning of string!");
VerifyClassInvariant();
}
}
using System;
using System.Runtime.Serialization;
using System.Security.Permissions;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
/*=================================SurrogateEncoder==================================
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
// We cannot ever call this.
- Contract.Assert(false, "Didn't expect to make it to SurrogateEncoder.GetObjectData");
+ Debug.Assert(false, "Didn't expect to make it to SurrogateEncoder.GetObjectData");
throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException"));
}
}
{
using System;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
// Encodes text into and out of UTF-32. UTF-32 is a way of writing
internal override unsafe int GetByteCount(char *chars, int count, EncoderNLS encoder)
{
- Contract.Assert(chars!=null, "[UTF32Encoding.GetByteCount]chars!=null");
- Contract.Assert(count >=0, "[UTF32Encoding.GetByteCount]count >=0");
+ Debug.Assert(chars!=null, "[UTF32Encoding.GetByteCount]chars!=null");
+ Debug.Assert(count >=0, "[UTF32Encoding.GetByteCount]count >=0");
char* end = chars + count;
char* charStart = chars;
// We are missing our low surrogate, decrement chars and fallback the high surrogate
// The high surrogate may have come from the encoder, but nothing else did.
- Contract.Assert(chars > charStart,
+ Debug.Assert(chars > charStart,
"[UTF32Encoding.GetByteCount]Expected chars to have advanced if no low surrogate");
chars--;
// Shouldn't have anything in fallback buffer for GetByteCount
// (don't have to check m_throwOnOverflow for count)
- Contract.Assert(fallbackBuffer.Remaining == 0,
+ Debug.Assert(fallbackBuffer.Remaining == 0,
"[UTF32Encoding.GetByteCount]Expected empty fallback buffer at end");
// Return our count
internal override unsafe int GetBytes(char *chars, int charCount,
byte* bytes, int byteCount, EncoderNLS encoder)
{
- Contract.Assert(chars!=null, "[UTF32Encoding.GetBytes]chars!=null");
- Contract.Assert(bytes!=null, "[UTF32Encoding.GetBytes]bytes!=null");
- Contract.Assert(byteCount >=0, "[UTF32Encoding.GetBytes]byteCount >=0");
- Contract.Assert(charCount >=0, "[UTF32Encoding.GetBytes]charCount >=0");
+ Debug.Assert(chars!=null, "[UTF32Encoding.GetBytes]chars!=null");
+ Debug.Assert(bytes!=null, "[UTF32Encoding.GetBytes]bytes!=null");
+ Debug.Assert(byteCount >=0, "[UTF32Encoding.GetBytes]byteCount >=0");
+ Debug.Assert(charCount >=0, "[UTF32Encoding.GetBytes]charCount >=0");
char* charStart = chars;
char* charEnd = chars + charCount;
{
// If we don't have enough room, then either we should've advanced a while
// or we should have bytes==byteStart and throw below
- Contract.Assert(chars > charStart + 1 || bytes == byteStart,
+ Debug.Assert(chars > charStart + 1 || bytes == byteStart,
"[UnicodeEncoding.GetBytes]Expected chars to have when no room to add surrogate pair");
chars-=2; // Aren't using those 2 chars
}
// We are missing our low surrogate, decrement chars and fallback the high surrogate
// The high surrogate may have come from the encoder, but nothing else did.
- Contract.Assert(chars > charStart,
+ Debug.Assert(chars > charStart,
"[UTF32Encoding.GetBytes]Expected chars to have advanced if no low surrogate");
chars--;
else
{
// Must've advanced already
- Contract.Assert(chars > charStart,
+ Debug.Assert(chars > charStart,
"[UTF32Encoding.GetBytes]Expected chars to have advanced if normal character");
chars--; // Aren't using this char
}
}
// Fix our encoder if we have one
- Contract.Assert(highSurrogate == 0 || (encoder != null && !encoder.MustFlush),
+ Debug.Assert(highSurrogate == 0 || (encoder != null && !encoder.MustFlush),
"[UTF32Encoding.GetBytes]Expected encoder to be flushed.");
if (encoder != null)
internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder)
{
- Contract.Assert(bytes!=null, "[UTF32Encoding.GetCharCount]bytes!=null");
- Contract.Assert(count >=0, "[UTF32Encoding.GetCharCount]count >=0");
+ Debug.Assert(bytes!=null, "[UTF32Encoding.GetCharCount]bytes!=null");
+ Debug.Assert(count >=0, "[UTF32Encoding.GetCharCount]count >=0");
UTF32Decoder decoder = (UTF32Decoder)baseDecoder;
// Shouldn't have anything in fallback buffer for GetCharCount
// (don't have to check m_throwOnOverflow for chars or count)
- Contract.Assert(fallbackBuffer.Remaining == 0,
+ Debug.Assert(fallbackBuffer.Remaining == 0,
"[UTF32Encoding.GetCharCount]Expected empty fallback buffer at start");
}
else
// Shouldn't have anything in fallback buffer for GetCharCount
// (don't have to check m_throwOnOverflow for chars or count)
- Contract.Assert(fallbackBuffer.Remaining == 0,
+ Debug.Assert(fallbackBuffer.Remaining == 0,
"[UTF32Encoding.GetCharCount]Expected empty fallback buffer at end");
// Return our count
internal override unsafe int GetChars(byte* bytes, int byteCount,
char* chars, int charCount, DecoderNLS baseDecoder)
{
- Contract.Assert(chars!=null, "[UTF32Encoding.GetChars]chars!=null");
- Contract.Assert(bytes!=null, "[UTF32Encoding.GetChars]bytes!=null");
- Contract.Assert(byteCount >=0, "[UTF32Encoding.GetChars]byteCount >=0");
- Contract.Assert(charCount >=0, "[UTF32Encoding.GetChars]charCount >=0");
+ Debug.Assert(chars!=null, "[UTF32Encoding.GetChars]chars!=null");
+ Debug.Assert(bytes!=null, "[UTF32Encoding.GetChars]bytes!=null");
+ Debug.Assert(byteCount >=0, "[UTF32Encoding.GetChars]byteCount >=0");
+ Debug.Assert(charCount >=0, "[UTF32Encoding.GetChars]charCount >=0");
UTF32Decoder decoder = (UTF32Decoder)baseDecoder;
// Shouldn't have anything in fallback buffer for GetChars
// (don't have to check m_throwOnOverflow for chars)
- Contract.Assert(fallbackBuffer.Remaining == 0,
+ Debug.Assert(fallbackBuffer.Remaining == 0,
"[UTF32Encoding.GetChars]Expected empty fallback buffer at start");
}
else
// Couldn't fallback, throw or wait til next time
// We either read enough bytes for bytes-=4 to work, or we're
// going to throw in ThrowCharsOverflow because chars == charStart
- Contract.Assert(bytes >= byteStart + 4 || chars == charStart,
+ Debug.Assert(bytes >= byteStart + 4 || chars == charStart,
"[UTF32Encoding.GetChars]Expected to have consumed bytes or throw (bad surrogate)");
bytes-=4; // get back to where we were
iChar=0; // Remembering nothing
// Throwing or stopping
// We either read enough bytes for bytes-=4 to work, or we're
// going to throw in ThrowCharsOverflow because chars == charStart
- Contract.Assert(bytes >= byteStart + 4 || chars == charStart,
+ Debug.Assert(bytes >= byteStart + 4 || chars == charStart,
"[UTF32Encoding.GetChars]Expected to have consumed bytes or throw (surrogate)");
bytes-=4; // get back to where we were
iChar=0; // Remembering nothing
// Throwing or stopping
// We either read enough bytes for bytes-=4 to work, or we're
// going to throw in ThrowCharsOverflow because chars == charStart
- Contract.Assert(bytes >= byteStart + 4 || chars == charStart,
+ Debug.Assert(bytes >= byteStart + 4 || chars == charStart,
"[UTF32Encoding.GetChars]Expected to have consumed bytes or throw (normal char)");
bytes-=4; // get back to where we were
iChar=0; // Remembering nothing
// Shouldn't have anything in fallback buffer for GetChars
// (don't have to check m_throwOnOverflow for chars)
- Contract.Assert(fallbackBuffer.Remaining == 0,
+ Debug.Assert(fallbackBuffer.Remaining == 0,
"[UTF32Encoding.GetChars]Expected empty fallback buffer at end");
// Return our count
using System;
using System.Runtime.Serialization;
using System.Security.Permissions;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS baseEncoder)
{
- Contract.Assert(chars!=null, "[UTF7Encoding.GetByteCount]chars!=null");
- Contract.Assert(count >=0, "[UTF7Encoding.GetByteCount]count >=0");
+ Debug.Assert(chars!=null, "[UTF7Encoding.GetByteCount]chars!=null");
+ Debug.Assert(count >=0, "[UTF7Encoding.GetByteCount]count >=0");
// Just call GetBytes with bytes == null
return GetBytes(chars, count, null, 0, baseEncoder);
internal override unsafe int GetBytes(char* chars, int charCount,
byte* bytes, int byteCount, EncoderNLS baseEncoder)
{
- Contract.Assert(byteCount >=0, "[UTF7Encoding.GetBytes]byteCount >=0");
- Contract.Assert(chars!=null, "[UTF7Encoding.GetBytes]chars!=null");
- Contract.Assert(charCount >=0, "[UTF7Encoding.GetBytes]charCount >=0");
+ Debug.Assert(byteCount >=0, "[UTF7Encoding.GetBytes]byteCount >=0");
+ Debug.Assert(chars!=null, "[UTF7Encoding.GetBytes]chars!=null");
+ Debug.Assert(charCount >=0, "[UTF7Encoding.GetBytes]charCount >=0");
// Get encoder info
UTF7Encoding.Encoder encoder = (UTF7Encoding.Encoder)baseEncoder;
internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder)
{
- Contract.Assert(count >=0, "[UTF7Encoding.GetCharCount]count >=0");
- Contract.Assert(bytes!=null, "[UTF7Encoding.GetCharCount]bytes!=null");
+ Debug.Assert(count >=0, "[UTF7Encoding.GetCharCount]count >=0");
+ Debug.Assert(bytes!=null, "[UTF7Encoding.GetCharCount]bytes!=null");
// Just call GetChars with null char* to do counting
return GetChars(bytes, count, null, 0, baseDecoder);
internal override unsafe int GetChars(byte* bytes, int byteCount,
char* chars, int charCount, DecoderNLS baseDecoder)
{
- Contract.Assert(byteCount >=0, "[UTF7Encoding.GetChars]byteCount >=0");
- Contract.Assert(bytes!=null, "[UTF7Encoding.GetChars]bytes!=null");
- Contract.Assert(charCount >=0, "[UTF7Encoding.GetChars]charCount >=0");
+ Debug.Assert(byteCount >=0, "[UTF7Encoding.GetChars]byteCount >=0");
+ Debug.Assert(bytes!=null, "[UTF7Encoding.GetChars]bytes!=null");
+ Debug.Assert(charCount >=0, "[UTF7Encoding.GetChars]charCount >=0");
// Might use a decoder
UTF7Encoding.Decoder decoder = (UTF7Encoding.Decoder) baseDecoder;
bitCount = decoder.bitCount;
firstByte = decoder.firstByte;
- Contract.Assert(firstByte == false || decoder.bitCount <= 0,
+ Debug.Assert(firstByte == false || decoder.bitCount <= 0,
"[UTF7Encoding.GetChars]If remembered bits, then first byte flag shouldn't be set");
}
public override bool Fallback(byte[] bytesUnknown, int index)
{
// We expect no previous fallback in our buffer
- Contract.Assert(iCount < 0, "[DecoderUTF7FallbackBuffer.Fallback] Can't have recursive fallbacks");
- Contract.Assert(bytesUnknown.Length == 1, "[DecoderUTF7FallbackBuffer.Fallback] Only possible fallback case should be 1 unknown byte");
+ Debug.Assert(iCount < 0, "[DecoderUTF7FallbackBuffer.Fallback] Can't have recursive fallbacks");
+ Debug.Assert(bytesUnknown.Length == 1, "[DecoderUTF7FallbackBuffer.Fallback] Only possible fallback case should be 1 unknown byte");
// Go ahead and get our fallback
cFallback = (char)bytesUnknown[0];
// array, and we might need the index, hence the byte*
{
// We expect no previous fallback in our buffer
- Contract.Assert(iCount < 0, "[DecoderUTF7FallbackBuffer.InternalFallback] Can't have recursive fallbacks");
+ Debug.Assert(iCount < 0, "[DecoderUTF7FallbackBuffer.InternalFallback] Can't have recursive fallbacks");
if (bytes.Length != 1)
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex"));
using System.Globalization;
using System.Runtime.Serialization;
using System.Security.Permissions;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
// Encodes text into and out of UTF-8. UTF-8 is a way of writing
} else {
// Case of surrogates in the fallback.
if (fallbackBuffer != null && fallbackBuffer.bFallingBack) {
- Contract.Assert(ch >= 0xD800 && ch <= 0xDBFF,
+ Debug.Assert(ch >= 0xD800 && ch <= 0xDBFF,
"[UTF8Encoding.GetBytes]expected high surrogate, not 0x" + ((int)ch).ToString("X4", CultureInfo.InvariantCulture));
ch = fallbackBuffer.InternalGetNextChar();
}
if (ch > 0) {
- Contract.Assert(ch >= 0xD800 && ch <= 0xDBFF,
+ Debug.Assert(ch >= 0xD800 && ch <= 0xDBFF,
"[UTF8Encoding.GetBytes]expected high surrogate, not 0x" + ((int)ch).ToString("X4", CultureInfo.InvariantCulture));
// use separate helper variables for local contexts so that the jit optimizations
}
#endif
- Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
+ Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
"[UTF8Encoding.GetByteCount]Expected Empty fallback buffer");
return byteCount;
internal override unsafe int GetBytes(char* chars, int charCount,
byte* bytes, int byteCount, EncoderNLS baseEncoder)
{
- Contract.Assert(chars!=null, "[UTF8Encoding.GetBytes]chars!=null");
- Contract.Assert(byteCount >=0, "[UTF8Encoding.GetBytes]byteCount >=0");
- Contract.Assert(charCount >=0, "[UTF8Encoding.GetBytes]charCount >=0");
- Contract.Assert(bytes!=null, "[UTF8Encoding.GetBytes]bytes!=null");
+ Debug.Assert(chars!=null, "[UTF8Encoding.GetBytes]chars!=null");
+ Debug.Assert(byteCount >=0, "[UTF8Encoding.GetBytes]byteCount >=0");
+ Debug.Assert(charCount >=0, "[UTF8Encoding.GetBytes]charCount >=0");
+ Debug.Assert(bytes!=null, "[UTF8Encoding.GetBytes]bytes!=null");
UTF8Encoder encoder = null;
} else {
// Case of leftover surrogates in the fallback buffer
if (fallbackBuffer != null && fallbackBuffer.bFallingBack) {
- Contract.Assert(ch >= 0xD800 && ch <= 0xDBFF,
+ Debug.Assert(ch >= 0xD800 && ch <= 0xDBFF,
"[UTF8Encoding.GetBytes]expected high surrogate, not 0x" + ((int)ch).ToString("X4", CultureInfo.InvariantCulture));
int cha = ch;
if (ch > 0) {
// We have a high surrogate left over from a previous loop.
- Contract.Assert(ch >= 0xD800 && ch <= 0xDBFF,
+ Debug.Assert(ch >= 0xD800 && ch <= 0xDBFF,
"[UTF8Encoding.GetBytes]expected high surrogate, not 0x" + ((int)ch).ToString("X4", CultureInfo.InvariantCulture));
// use separate helper variables for local contexts so that the jit optimizations
if (ch > 0xFFFF)
pSrc--; // Was surrogate, didn't use 2nd part either
}
- Contract.Assert(pSrc >= chars || pTarget == bytes,
+ Debug.Assert(pSrc >= chars || pTarget == bytes,
"[UTF8Encoding.GetBytes]Expected pSrc to be within buffer or to throw with insufficient room.");
ThrowBytesOverflow(encoder, pTarget == bytes); // Throw if we must
ch = 0; // Nothing left over (we backed up to start of pair if supplimentary)
pTarget++;
}
- Contract.Assert(pTarget <= pAllocatedBufferEnd, "[UTF8Encoding.GetBytes]pTarget <= pAllocatedBufferEnd");
+ Debug.Assert(pTarget <= pAllocatedBufferEnd, "[UTF8Encoding.GetBytes]pTarget <= pAllocatedBufferEnd");
#endif // FASTLOOP
// Do we have to set the encoder bytes?
if (encoder != null)
{
- Contract.Assert(!encoder.MustFlush || ch == 0,
+ Debug.Assert(!encoder.MustFlush || ch == 0,
"[UTF8Encoding.GetBytes] Expected no mustflush or 0 leftover ch " + ch.ToString("X2", CultureInfo.InvariantCulture));
encoder.surrogateChar = ch;
encoder.m_charsUsed = (int)(pSrc - chars);
}
- Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0 ||
+ Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0 ||
baseEncoder == null || !baseEncoder.m_throwOnOverflow,
"[UTF8Encoding.GetBytes]Expected empty fallback buffer if not converting");
// kept the same as much as possible
internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder)
{
- Contract.Assert(count >=0, "[UTF8Encoding.GetCharCount]count >=0");
- Contract.Assert(bytes!=null, "[UTF8Encoding.GetCharCount]bytes!=null");
+ Debug.Assert(count >=0, "[UTF8Encoding.GetCharCount]count >=0");
+ Debug.Assert(bytes!=null, "[UTF8Encoding.GetCharCount]bytes!=null");
// Initialize stuff
byte *pSrc = bytes;
// Shouldn't have anything in fallback buffer for GetCharCount
// (don't have to check m_throwOnOverflow for count)
- Contract.Assert(!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
+ Debug.Assert(!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
"[UTF8Encoding.GetCharCount]Expected empty fallback buffer at start");
}
ch = (ch << 6) | (cha & 0x3F);
if ((ch & FinalByte) == 0) {
- Contract.Assert( (ch & (SupplimentarySeq | ThreeByteSeq)) != 0,
+ Debug.Assert( (ch & (SupplimentarySeq | ThreeByteSeq)) != 0,
"[UTF8Encoding.GetChars]Invariant volation");
if ((ch & SupplimentarySeq) != 0) {
// Shouldn't have anything in fallback buffer for GetCharCount
// (don't have to check m_throwOnOverflow for count)
- Contract.Assert(fallback == null || fallback.Remaining == 0,
+ Debug.Assert(fallback == null || fallback.Remaining == 0,
"[UTF8Encoding.GetCharCount]Expected empty fallback buffer at end");
return charCount;
internal override unsafe int GetChars(byte* bytes, int byteCount,
char* chars, int charCount, DecoderNLS baseDecoder)
{
- Contract.Assert(chars!=null, "[UTF8Encoding.GetChars]chars!=null");
- Contract.Assert(byteCount >=0, "[UTF8Encoding.GetChars]count >=0");
- Contract.Assert(charCount >=0, "[UTF8Encoding.GetChars]charCount >=0");
- Contract.Assert(bytes!=null, "[UTF8Encoding.GetChars]bytes!=null");
+ Debug.Assert(chars!=null, "[UTF8Encoding.GetChars]chars!=null");
+ Debug.Assert(byteCount >=0, "[UTF8Encoding.GetChars]count >=0");
+ Debug.Assert(charCount >=0, "[UTF8Encoding.GetChars]charCount >=0");
+ Debug.Assert(bytes!=null, "[UTF8Encoding.GetChars]bytes!=null");
byte *pSrc = bytes;
char *pTarget = chars;
// Shouldn't have anything in fallback buffer for GetChars
// (don't have to check m_throwOnOverflow for chars, we always use all or none so always should be empty)
- Contract.Assert(!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
+ Debug.Assert(!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
"[UTF8Encoding.GetChars]Expected empty fallback buffer at start");
}
if ((ch & FinalByte) == 0) {
// Not at last byte yet
- Contract.Assert( (ch & (SupplimentarySeq | ThreeByteSeq)) != 0,
+ Debug.Assert( (ch & (SupplimentarySeq | ThreeByteSeq)) != 0,
"[UTF8Encoding.GetChars]Invariant volation");
if ((ch & SupplimentarySeq) != 0) {
{
// Ran out of buffer space
// Need to throw an exception?
- Contract.Assert(pSrc >= bytes || pTarget == chars,
+ Debug.Assert(pSrc >= bytes || pTarget == chars,
"[UTF8Encoding.GetChars]Expected to throw or remain in byte buffer after fallback");
fallback.InternalReset();
ThrowCharsOverflow(baseDecoder, pTarget == chars);
ch = 0;
break;
}
- Contract.Assert(pSrc >= bytes,
+ Debug.Assert(pSrc >= bytes,
"[UTF8Encoding.GetChars]Expected invalid byte sequence to have remained within the byte array");
ch = 0;
continue;
// Throw that we don't have enough room (pSrc could be < chars if we had started to process
// a 4 byte sequence alredy)
- Contract.Assert(pSrc >= bytes || pTarget == chars,
+ Debug.Assert(pSrc >= bytes || pTarget == chars,
"[UTF8Encoding.GetChars]Expected pSrc to be within input buffer or throw due to no output]");
ThrowCharsOverflow(baseDecoder, pTarget == chars);
}
#endif // FASTLOOP
- Contract.Assert(pTarget <= pAllocatedBufferEnd, "[UTF8Encoding.GetChars]pTarget <= pAllocatedBufferEnd");
+ Debug.Assert(pTarget <= pAllocatedBufferEnd, "[UTF8Encoding.GetChars]pTarget <= pAllocatedBufferEnd");
// no pending bits at this point
ch = 0;
// This'll back us up the appropriate # of bytes if we didn't get anywhere
if (!FallbackInvalidByteSequence(ref pSrc, ch, fallback, ref pTarget))
{
- Contract.Assert(pSrc >= bytes || pTarget == chars,
+ Debug.Assert(pSrc >= bytes || pTarget == chars,
"[UTF8Encoding.GetChars]Expected to throw or remain in byte buffer while flushing");
// Ran out of buffer space
fallback.InternalReset();
ThrowCharsOverflow(baseDecoder, pTarget == chars);
}
- Contract.Assert(pSrc >= bytes,
+ Debug.Assert(pSrc >= bytes,
"[UTF8Encoding.GetChars]Expected flushing invalid byte sequence to have remained within the byte array");
ch = 0;
}
// If we're storing flush data we expect all bits to be used or else
// we're stuck in the middle of a conversion
- Contract.Assert(!baseDecoder.MustFlush || ch == 0 || !baseDecoder.m_throwOnOverflow,
+ Debug.Assert(!baseDecoder.MustFlush || ch == 0 || !baseDecoder.m_throwOnOverflow,
"[UTF8Encoding.GetChars]Expected no must flush or no left over bits or no throw on overflow.");
// Remember our leftover bits.
// Shouldn't have anything in fallback buffer for GetChars
// (don't have to check m_throwOnOverflow for chars)
- Contract.Assert(fallback == null || fallback.Remaining == 0,
+ Debug.Assert(fallback == null || fallback.Remaining == 0,
"[UTF8Encoding.GetChars]Expected empty fallback buffer at end");
return PtrDiff(pTarget, chars);
using System.Globalization;
using System.Runtime.Serialization;
using System.Security.Permissions;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS encoder)
{
- Contract.Assert(chars!=null, "[UnicodeEncoding.GetByteCount]chars!=null");
- Contract.Assert(count >= 0, "[UnicodeEncoding.GetByteCount]count >=0");
+ Debug.Assert(chars!=null, "[UnicodeEncoding.GetByteCount]chars!=null");
+ Debug.Assert(count >= 0, "[UnicodeEncoding.GetByteCount]count >=0");
// Start by assuming each char gets 2 bytes
int byteCount = count << 1;
// Unwind the current character, this should be safe because we
// don't have leftover data in the fallback, so chars must have
// advanced already.
- Contract.Assert(chars > charStart,
+ Debug.Assert(chars > charStart,
"[UnicodeEncoding.GetByteCount]Expected chars to have advanced in unexpected high surrogate");
chars--;
// Rewind the current character, fallback previous character.
// this should be safe because we don't have leftover data in the
// fallback, so chars must have advanced already.
- Contract.Assert(chars > charStart,
+ Debug.Assert(chars > charStart,
"[UnicodeEncoding.GetByteCount]Expected chars to have advanced when expected low surrogate");
chars--;
// Shouldn't have anything in fallback buffer for GetByteCount
// (don't have to check m_throwOnOverflow for count)
- Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
+ Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
"[UnicodeEncoding.GetByteCount]Expected empty fallback buffer at end");
// Don't remember fallbackBuffer.encoder for counting
internal override unsafe int GetBytes(char* chars, int charCount,
byte* bytes, int byteCount, EncoderNLS encoder)
{
- Contract.Assert(chars!=null, "[UnicodeEncoding.GetBytes]chars!=null");
- Contract.Assert(byteCount >=0, "[UnicodeEncoding.GetBytes]byteCount >=0");
- Contract.Assert(charCount >=0, "[UnicodeEncoding.GetBytes]charCount >=0");
- Contract.Assert(bytes!=null, "[UnicodeEncoding.GetBytes]bytes!=null");
+ Debug.Assert(chars!=null, "[UnicodeEncoding.GetBytes]chars!=null");
+ Debug.Assert(byteCount >=0, "[UnicodeEncoding.GetBytes]byteCount >=0");
+ Debug.Assert(charCount >=0, "[UnicodeEncoding.GetBytes]charCount >=0");
+ Debug.Assert(bytes!=null, "[UnicodeEncoding.GetBytes]bytes!=null");
char charLeftOver = (char)0;
char ch;
// Unwind the current character, this should be safe because we
// don't have leftover data in the fallback, so chars must have
// advanced already.
- Contract.Assert(chars > charStart,
+ Debug.Assert(chars > charStart,
"[UnicodeEncoding.GetBytes]Expected chars to have advanced in unexpected high surrogate");
chars--;
{
// If we don't have enough room, then either we should've advanced a while
// or we should have bytes==byteStart and throw below
- Contract.Assert(chars > charStart + 1 || bytes == byteStart,
+ Debug.Assert(chars > charStart + 1 || bytes == byteStart,
"[UnicodeEncoding.GetBytes]Expected chars to have when no room to add surrogate pair");
chars-=2; // Didn't use either surrogate
}
// Rewind the current character, fallback previous character.
// this should be safe because we don't have leftover data in the
// fallback, so chars must have advanced already.
- Contract.Assert(chars > charStart,
+ Debug.Assert(chars > charStart,
"[UnicodeEncoding.GetBytes]Expected chars to have advanced after expecting low surrogate");
chars--;
{
// Lonely charLeftOver (from previous call) would've been caught up above,
// so this must be a case where we've already read an input char.
- Contract.Assert(chars > charStart,
+ Debug.Assert(chars > charStart,
"[UnicodeEncoding.GetBytes]Expected chars to have advanced for failed fallback");
chars--; // Not using this char
}
// Remember charLeftOver if we must, or clear it if we're flushing
// (charLeftOver should be 0 if we're flushing)
- Contract.Assert((encoder != null && !encoder.MustFlush) || charLeftOver == (char)0,
+ Debug.Assert((encoder != null && !encoder.MustFlush) || charLeftOver == (char)0,
"[UnicodeEncoding.GetBytes] Expected no left over characters if flushing");
- Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0 ||
+ Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0 ||
encoder == null || !encoder.m_throwOnOverflow,
"[UnicodeEncoding.GetBytes]Expected empty fallback buffer if not converting");
internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder)
{
- Contract.Assert(bytes!=null, "[UnicodeEncoding.GetCharCount]bytes!=null");
- Contract.Assert(count >= 0, "[UnicodeEncoding.GetCharCount]count >=0");
+ Debug.Assert(bytes!=null, "[UnicodeEncoding.GetCharCount]bytes!=null");
+ Debug.Assert(count >= 0, "[UnicodeEncoding.GetCharCount]count >=0");
UnicodeEncoding.Decoder decoder = (UnicodeEncoding.Decoder)baseDecoder;
// Shouldn't have anything in fallback buffer for GetCharCount
// (don't have to check m_throwOnOverflow for count)
- Contract.Assert(!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
+ Debug.Assert(!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
"[UnicodeEncoding.GetCharCount]Expected empty fallback buffer at start");
}
// Shouldn't have anything in fallback buffer for GetCharCount
// (don't have to check m_throwOnOverflow for count)
- Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
+ Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
"[UnicodeEncoding.GetCharCount]Expected empty fallback buffer at end");
return charCount;
internal override unsafe int GetChars(byte* bytes, int byteCount,
char* chars, int charCount, DecoderNLS baseDecoder )
{
- Contract.Assert(chars!=null, "[UnicodeEncoding.GetChars]chars!=null");
- Contract.Assert(byteCount >=0, "[UnicodeEncoding.GetChars]byteCount >=0");
- Contract.Assert(charCount >=0, "[UnicodeEncoding.GetChars]charCount >=0");
- Contract.Assert(bytes!=null, "[UnicodeEncoding.GetChars]bytes!=null");
+ Debug.Assert(chars!=null, "[UnicodeEncoding.GetChars]chars!=null");
+ Debug.Assert(byteCount >=0, "[UnicodeEncoding.GetChars]byteCount >=0");
+ Debug.Assert(charCount >=0, "[UnicodeEncoding.GetChars]charCount >=0");
+ Debug.Assert(bytes!=null, "[UnicodeEncoding.GetChars]bytes!=null");
UnicodeEncoding.Decoder decoder = (UnicodeEncoding.Decoder)baseDecoder;
// Shouldn't have anything in fallback buffer for GetChars
// (don't have to check m_throwOnOverflow for chars)
- Contract.Assert(!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
+ Debug.Assert(!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
"[UnicodeEncoding.GetChars]Expected empty fallback buffer at start");
}
{
// couldn't fall back lonely surrogate
// We either advanced bytes or chars should == charStart and throw below
- Contract.Assert(bytes >= byteStart + 2 || chars == charStart,
+ Debug.Assert(bytes >= byteStart + 2 || chars == charStart,
"[UnicodeEncoding.GetChars]Expected bytes to have advanced or no output (bad surrogate)");
bytes-=2; // didn't use these 2 bytes
fallbackBuffer.InternalReset();
{
// couldn't fall back lonely surrogate
// We either advanced bytes or chars should == charStart and throw below
- Contract.Assert(bytes >= byteStart + 2 || chars == charStart,
+ Debug.Assert(bytes >= byteStart + 2 || chars == charStart,
"[UnicodeEncoding.GetChars]Expected bytes to have advanced or no output (lonely surrogate)");
bytes-=2; // didn't use these 2 bytes
fallbackBuffer.InternalReset();
{
// couldn't find room for this surrogate pair
// We either advanced bytes or chars should == charStart and throw below
- Contract.Assert(bytes >= byteStart + 2 || chars == charStart,
+ Debug.Assert(bytes >= byteStart + 2 || chars == charStart,
"[UnicodeEncoding.GetChars]Expected bytes to have advanced or no output (surrogate pair)");
bytes-=2; // didn't use these 2 bytes
ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output
{
// couldn't fall back high surrogate, or char that would be next
// We either advanced bytes or chars should == charStart and throw below
- Contract.Assert(bytes >= byteStart + 2 || chars == charStart,
+ Debug.Assert(bytes >= byteStart + 2 || chars == charStart,
"[UnicodeEncoding.GetChars]Expected bytes to have advanced or no output (no low surrogate)");
bytes-=2; // didn't use these 2 bytes
fallbackBuffer.InternalReset();
{
// 2 bytes couldn't fall back
// We either advanced bytes or chars should == charStart and throw below
- Contract.Assert(bytes >= byteStart + 2 || chars == charStart,
+ Debug.Assert(bytes >= byteStart + 2 || chars == charStart,
"[UnicodeEncoding.GetChars]Expected bytes to have advanced or no output (normal)");
bytes-=2; // didn't use these bytes
ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output
{
// 2 bytes couldn't fall back
// We either advanced bytes or chars should == charStart and throw below
- Contract.Assert(bytes >= byteStart + 2 || chars == charStart,
+ Debug.Assert(bytes >= byteStart + 2 || chars == charStart,
"[UnicodeEncoding.GetChars]Expected bytes to have advanced or no output (decoder)");
bytes-=2; // didn't use these bytes
if (lastByte >= 0)
// Remember our decoder if we must
if (decoder != null)
{
- Contract.Assert((decoder.MustFlush == false) || ((lastChar == (char)0) && (lastByte == -1)),
+ Debug.Assert((decoder.MustFlush == false) || ((lastChar == (char)0) && (lastByte == -1)),
"[UnicodeEncoding.GetChars] Expected no left over chars or bytes if flushing"
// + " " + ((int)lastChar).ToString("X4") + " " + lastByte.ToString("X2")
);
// Shouldn't have anything in fallback buffer for GetChars
// (don't have to check m_throwOnOverflow for count or chars)
- Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
+ Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
"[UnicodeEncoding.GetChars]Expected empty fallback buffer at end");
return (int)(chars - charStart);
using System;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Security;
void IAsyncLocal.OnValueChanged(object previousValueObj, object currentValueObj, bool contextChanged)
{
- Contract.Assert(m_valueChangedHandler != null);
+ Debug.Assert(m_valueChangedHandler != null);
T previousValue = previousValueObj == null ? default(T) : (T)previousValueObj;
T currentValue = currentValueObj == null ? default(T) : (T)currentValueObj;
m_valueChangedHandler(new AsyncLocalValueChangedArgs<T>(previousValue, currentValue, contextChanged));
multi.UnsafeStore(index++, pair.Key, pair.Value);
}
}
- Contract.Assert(index == MultiElementAsyncLocalValueMap.MaxMultiElements);
+ Debug.Assert(index == MultiElementAsyncLocalValueMap.MaxMultiElements);
return multi;
}
else
map[pair.Key] = pair.Value;
}
}
- Contract.Assert(map.Count == count - 1);
+ Debug.Assert(map.Count == count - 1);
return map;
}
}
#pragma warning disable 0420 // turn off 'a reference to a volatile field will not be treated as volatile' during CAS.
using System;
-using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Permissions;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime;
using System.Runtime.CompilerServices;
private static void ActionToActionObjShunt(object obj)
{
Action action = obj as Action;
- Contract.Assert(action != null, "Expected an Action here");
+ Debug.Assert(action != null, "Expected an Action here");
action();
}
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Security.Permissions;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime;
}
// the CancellationToken has already checked that the token is cancelable before calling this method.
- Contract.Assert(CanBeCanceled, "Cannot register for uncancelable token src");
+ Debug.Assert(CanBeCanceled, "Cannot register for uncancelable token src");
// if not canceled, register the event handlers
// if canceled already, run the callback synchronously
// - After transition, no more delegates will be added to the
// - list of handlers, and hence it can be consumed and cleared at leisure by ExecuteCallbackHandlers.
ExecuteCallbackHandlers(throwOnFirstException);
- Contract.Assert(IsCancellationCompleted, "Expected cancellation to have finished");
+ Debug.Assert(IsCancellationCompleted, "Expected cancellation to have finished");
}
}
/// </remarks>
private void ExecuteCallbackHandlers(bool throwOnFirstException)
{
- Contract.Assert(IsCancellationRequested, "ExecuteCallbackHandlers should only be called after setting IsCancellationRequested->true");
- Contract.Assert(ThreadIDExecutingCallbacks != -1, "ThreadIDExecutingCallbacks should have been set.");
+ Debug.Assert(IsCancellationRequested, "ExecuteCallbackHandlers should only be called after setting IsCancellationRequested->true");
+ Debug.Assert(ThreadIDExecutingCallbacks != -1, "ThreadIDExecutingCallbacks should have been set.");
// Design decision: call the delegates in LIFO order so that callbacks fire 'deepest first'.
// This is intended to help with nesting scenarios so that child enlisters cancel before their parents.
var wsc = m_executingCallback as CancellationCallbackInfo.WithSyncContext;
if (wsc != null)
{
- Contract.Assert(wsc.TargetSyncContext != null, "Should only have derived CCI if non-null SyncCtx");
+ Debug.Assert(wsc.TargetSyncContext != null, "Should only have derived CCI if non-null SyncCtx");
wsc.TargetSyncContext.Send(CancellationCallbackCoreWork_OnSyncContext, args);
// CancellationCallbackCoreWork_OnSyncContext may have altered ThreadIDExecutingCallbacks, so reset it.
ThreadIDExecutingCallbacks = Thread.CurrentThread.ManagedThreadId;
if (exceptionList != null)
{
- Contract.Assert(exceptionList.Count > 0, "Expected exception count > 0");
+ Debug.Assert(exceptionList.Count > 0, "Expected exception count > 0");
throw new AggregateException(exceptionList);
}
}
private static void ExecutionContextCallback(object obj)
{
CancellationCallbackInfo callbackInfo = obj as CancellationCallbackInfo;
- Contract.Assert(callbackInfo != null);
+ Debug.Assert(callbackInfo != null);
callbackInfo.Callback(callbackInfo.StateForCallback);
}
}
start = 0;
curr.m_freeCount--; // Too many free elements; fix up.
}
- Contract.Assert(start >= 0 && start < c, "start is outside of bounds");
+ Debug.Assert(start >= 0 && start < c, "start is outside of bounds");
// Now walk the array until we find a free slot (or reach the end).
for (int i = 0; i < c; i++)
{
// If the slot is null, try to CAS our element into it.
int tryIndex = (start + i) % c;
- Contract.Assert(tryIndex >= 0 && tryIndex < curr.m_elements.Length, "tryIndex is outside of bounds");
+ Debug.Assert(tryIndex >= 0 && tryIndex < curr.m_elements.Length, "tryIndex is outside of bounds");
if (curr.m_elements[tryIndex] == null && Interlocked.CompareExchange(ref curr.m_elements[tryIndex], element, null) == null)
{
internal SparselyPopulatedArrayAddInfo(SparselyPopulatedArrayFragment<T> source, int index)
{
- Contract.Assert(source != null);
- Contract.Assert(index >= 0 && index < source.Length);
+ Debug.Assert(source != null);
+ Debug.Assert(index >= 0 && index < source.Length);
m_source = source;
m_index = index;
}
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System;
-using System.Diagnostics;
using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Threading;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Threading
public bool Signal()
{
ThrowIfDisposed();
- Contract.Assert(m_event != null);
+ Debug.Assert(m_event != null);
if (m_currentCount <= 0)
{
}
ThrowIfDisposed();
- Contract.Assert(m_event != null);
+ Debug.Assert(m_event != null);
int observedCount;
SpinWait spin = new SpinWait();
return true;
}
- Contract.Assert(m_currentCount >= 0, "latch was decremented below zero");
+ Debug.Assert(m_currentCount >= 0, "latch was decremented below zero");
return false;
}
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Diagnostics.CodeAnalysis;
internal void Undo(Thread currentThread)
{
- Contract.Assert(currentThread == Thread.CurrentThread);
+ Debug.Assert(currentThread == Thread.CurrentThread);
// The common case is that these have not changed, so avoid the cost of a write if not needed.
if (currentThread.SynchronizationContext != m_sc)
private ExecutionContext ShallowClone(bool isFlowSuppressed)
{
- Contract.Assert(isFlowSuppressed != m_isFlowSuppressed);
+ Debug.Assert(isFlowSuppressed != m_isFlowSuppressed);
if (!isFlowSuppressed &&
m_localValues == Default.m_localValues &&
internal static void Restore(Thread currentThread, ExecutionContext executionContext)
{
- Contract.Assert(currentThread == Thread.CurrentThread);
+ Debug.Assert(currentThread == Thread.CurrentThread);
ExecutionContext previous = currentThread.ExecutionContext ?? Default;
currentThread.ExecutionContext = executionContext;
static internal void EstablishCopyOnWriteScope(Thread currentThread, ref ExecutionContextSwitcher ecsw)
{
- Contract.Assert(currentThread == Thread.CurrentThread);
+ Debug.Assert(currentThread == Thread.CurrentThread);
ecsw.m_ec = currentThread.ExecutionContext;
ecsw.m_sc = currentThread.SynchronizationContext;
[HandleProcessCorruptedStateExceptions]
private static void OnContextChanged(ExecutionContext previous, ExecutionContext current)
{
- Contract.Assert(previous != null);
- Contract.Assert(current != null);
- Contract.Assert(previous != current);
+ Debug.Assert(previous != null);
+ Debug.Assert(current != null);
+ Debug.Assert(previous != current);
foreach (IAsyncLocal local in previous.m_localChangeNotifications)
{
{
if (hadPreviousValue)
{
- Contract.Assert(Array.IndexOf(newChangeNotifications, local) >= 0);
+ Debug.Assert(Array.IndexOf(newChangeNotifications, local) >= 0);
}
else
{
internal void Initialize(Thread currentThread)
{
- Contract.Assert(currentThread == Thread.CurrentThread);
+ Debug.Assert(currentThread == Thread.CurrentThread);
_thread = currentThread;
}
using System.Security.Permissions;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Threading
{
}
Interlocked.CompareExchange(ref target, value, null);
- Contract.Assert(target != null);
+ Debug.Assert(target != null);
return target;
}
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System;
-using System.Diagnostics;
using System.Security.Permissions;
using System.Threading;
using System.Runtime.InteropServices;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Threading
private set
{
- Contract.Assert(value >= 0, "SpinCount is a restricted-width integer. The value supplied is outside the legal range.");
- Contract.Assert(value <= SpinCountState_MaxValue, "SpinCount is a restricted-width integer. The value supplied is outside the legal range.");
+ Debug.Assert(value >= 0, "SpinCount is a restricted-width integer. The value supplied is outside the legal range.");
+ Debug.Assert(value <= SpinCountState_MaxValue, "SpinCount is a restricted-width integer. The value supplied is outside the legal range.");
// Don't worry about thread safety because it's set one time from the constructor
m_combinedState = (m_combinedState & ~SpinCountState_BitMask) | (value << SpinCountState_ShiftCount);
}
set
{
//setting to <0 would indicate an internal flaw, hence Assert is appropriate.
- Contract.Assert(value >= 0, "NumWaiters should never be less than zero. This indicates an internal error.");
+ Debug.Assert(value >= 0, "NumWaiters should never be less than zero. This indicates an internal error.");
// it is possible for the max number of waiters to be exceeded via user-code, hence we use a real exception here.
if (value >= NumWaitersState_MaxValue)
this.m_combinedState = initialState ? (1 << SignalledState_ShiftCount) : 0;
//the spinCount argument has been validated by the ctors.
//but we now sanity check our predefined constants.
- Contract.Assert(DEFAULT_SPIN_SP >= 0, "Internal error - DEFAULT_SPIN_SP is outside the legal range.");
- Contract.Assert(DEFAULT_SPIN_SP <= SpinCountState_MaxValue, "Internal error - DEFAULT_SPIN_SP is outside the legal range.");
+ Debug.Assert(DEFAULT_SPIN_SP >= 0, "Internal error - DEFAULT_SPIN_SP is outside the legal range.");
+ Debug.Assert(DEFAULT_SPIN_SP <= SpinCountState_MaxValue, "Internal error - DEFAULT_SPIN_SP is outside the legal range.");
SpinCount = PlatformHelper.IsSingleProcessor ? DEFAULT_SPIN_SP : spinCount;
bool currentIsSet = IsSet;
if (currentIsSet != preInitializeIsSet)
{
- Contract.Assert(currentIsSet,
+ Debug.Assert(currentIsSet,
"The only safe concurrent transition is from unset->set: detected set->unset.");
// We saw it as unsignaled, but it has since become set.
// If there are waiting threads, we need to pulse them.
if (Waiters > 0)
{
- Contract.Assert(m_lock != null); //if waiters>0, then m_lock has already been created.
+ Debug.Assert(m_lock != null); //if waiters>0, then m_lock has already been created.
lock (m_lock)
{
private static void CancellationTokenCallback(object obj)
{
ManualResetEventSlim mre = obj as ManualResetEventSlim;
- Contract.Assert(mre != null, "Expected a ManualResetEventSlim");
- Contract.Assert(mre.m_lock != null); //the lock should have been created before this callback is registered for use.
+ Debug.Assert(mre != null, "Expected a ManualResetEventSlim");
+ Debug.Assert(mre.m_lock != null); //the lock should have been created before this callback is registered for use.
lock (mre.m_lock)
{
Monitor.PulseAll(mre.m_lock); // awaken all waiters
{
SpinWait sw = new SpinWait();
- Contract.Assert((newBits | updateBitsMask) == updateBitsMask, "newBits do not fall within the updateBitsMask.");
+ Debug.Assert((newBits | updateBitsMask) == updateBitsMask, "newBits do not fall within the updateBitsMask.");
do
{
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[HostProtection(Synchronization=true, ExternalThreading=true)]
ThrowLockTakenException();
ReliableEnter(obj, ref lockTaken);
- Contract.Assert(lockTaken);
+ Debug.Assert(lockTaken);
}
private static void ThrowLockTakenException()
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using System.Security;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[HostProtection(Synchronization=true, ExternalThreading=true)]
[PrePrepareMethod]
internal MutexTryCodeHelper(bool initiallyOwned,MutexCleanupInfo cleanupInfo, String name, Win32Native.SECURITY_ATTRIBUTES secAttrs, Mutex mutex)
{
- Contract.Assert(name == null || name.Length != 0);
+ Debug.Assert(name == null || name.Length != 0);
m_initiallyOwned = initiallyOwned;
m_cleanupInfo = cleanupInfo;
using System.Security;
using System.Security.Permissions;
using System.Runtime.ConstrainedExecution;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Collections.Concurrent;
static internal void IOCompletionCallback_Context(Object state)
{
_IOCompletionCallback helper = (_IOCompletionCallback)state;
- Contract.Assert(helper != null,"_IOCompletionCallback cannot be null");
+ Debug.Assert(helper != null,"_IOCompletionCallback cannot be null");
helper._ioCompletionCallback(helper._errorCode, helper._numBytes, helper._pOVERLAP);
}
m_iocbHelper = null;
m_overlapped = null;
m_userObject = null;
- Contract.Assert(m_pinSelf.IsNull(), "OverlappedData has not been freed: m_pinSelf");
+ Debug.Assert(m_pinSelf.IsNull(), "OverlappedData has not been freed: m_pinSelf");
m_pinSelf = (IntPtr)0;
m_userObjectInternal = (IntPtr)0;
- Contract.Assert(m_AppDomainId == 0 || m_AppDomainId == AppDomain.CurrentDomain.Id, "OverlappedData is not in the current domain");
+ Debug.Assert(m_AppDomainId == 0 || m_AppDomainId == AppDomain.CurrentDomain.Id, "OverlappedData is not in the current domain");
m_AppDomainId = 0;
m_nativeOverlapped.EventHandle = (IntPtr)0;
m_isArray = 0;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.IO;
using System.Runtime.InteropServices;
#endif
}
- Contract.Assert(initialCount >= 0);
- Contract.Assert(maximumCount >= 1);
- Contract.Assert(initialCount <= maximumCount);
+ Debug.Assert(initialCount >= 0);
+ Debug.Assert(maximumCount >= 1);
+ Debug.Assert(initialCount <= maximumCount);
return Win32Native.CreateSemaphore(null, initialCount, maximumCount, name);
}
void IThreadPoolWorkItem.ExecuteWorkItem()
{
bool setSuccessfully = TrySetResult(true);
- Contract.Assert(setSuccessfully, "Should have been able to complete task");
+ Debug.Assert(setSuccessfully, "Should have been able to complete task");
}
void IThreadPoolWorkItem.MarkAborted(ThreadAbortException tae) { /* nop */ }
// then block on (once we've released the lock).
if (m_asyncHead != null)
{
- Contract.Assert(m_asyncTail != null, "tail should not be null if head isn't");
+ Debug.Assert(m_asyncTail != null, "tail should not be null if head isn't");
asyncWaitTask = WaitAsync(millisecondsTimeout, cancellationToken);
}
// There are no async waiters, so we can proceed with normal synchronous waiting.
// defer to synchronous waiters in priority, which means that if it's possible an asynchronous
// waiter didn't get released because a synchronous waiter was present, we need to ensure
// that synchronous waiter succeeds so that they have a chance to release.
- Contract.Assert(!waitSuccessful || m_currentCount > 0,
+ Debug.Assert(!waitSuccessful || m_currentCount > 0,
"If the wait was successful, there should be count available.");
if (m_currentCount > 0)
{
// the semaphore or when the timeout expired or cancellation was requested.
else
{
- Contract.Assert(m_currentCount == 0, "m_currentCount should never be negative");
+ Debug.Assert(m_currentCount == 0, "m_currentCount should never be negative");
var asyncWaiter = CreateAndAddAsyncWaiter();
return (millisecondsTimeout == Timeout.Infinite && !cancellationToken.CanBeCanceled) ?
asyncWaiter :
/// <returns>The created task.</returns>
private TaskNode CreateAndAddAsyncWaiter()
{
- Contract.Assert(Monitor.IsEntered(m_lockObj), "Requires the lock be held");
+ Debug.Assert(Monitor.IsEntered(m_lockObj), "Requires the lock be held");
// Create the task
var task = new TaskNode();
// Add it to the linked list
if (m_asyncHead == null)
{
- Contract.Assert(m_asyncTail == null, "If head is null, so too should be tail");
+ Debug.Assert(m_asyncTail == null, "If head is null, so too should be tail");
m_asyncHead = task;
m_asyncTail = task;
}
else
{
- Contract.Assert(m_asyncTail != null, "If head is not null, neither should be tail");
+ Debug.Assert(m_asyncTail != null, "If head is not null, neither should be tail");
m_asyncTail.Next = task;
task.Prev = m_asyncTail;
m_asyncTail = task;
private bool RemoveAsyncWaiter(TaskNode task)
{
Contract.Requires(task != null, "Expected non-null task");
- Contract.Assert(Monitor.IsEntered(m_lockObj), "Requires the lock be held");
+ Debug.Assert(Monitor.IsEntered(m_lockObj), "Requires the lock be held");
// Is the task in the list? To be in the list, either it's the head or it has a predecessor that's in the list.
bool wasInList = m_asyncHead == task || task.Prev != null;
if (task.Prev != null) task.Prev.Next = task.Next;
if (m_asyncHead == task) m_asyncHead = task.Next;
if (m_asyncTail == task) m_asyncTail = task.Prev;
- Contract.Assert((m_asyncHead == null) == (m_asyncTail == null), "Head is null iff tail is null");
+ Debug.Assert((m_asyncHead == null) == (m_asyncTail == null), "Head is null iff tail is null");
// Make sure not to leak
task.Next = task.Prev = null;
/// <returns>The task to return to the caller.</returns>
private async Task<bool> WaitUntilCountOrTimeoutAsync(TaskNode asyncWaiter, int millisecondsTimeout, CancellationToken cancellationToken)
{
- Contract.Assert(asyncWaiter != null, "Waiter should have been constructed");
- Contract.Assert(Monitor.IsEntered(m_lockObj), "Requires the lock be held");
+ Debug.Assert(asyncWaiter != null, "Waiter should have been constructed");
+ Debug.Assert(Monitor.IsEntered(m_lockObj), "Requires the lock be held");
// Wait until either the task is completed, timeout occurs, or cancellation is requested.
// We need to ensure that the Task.Delay task is appropriately cleaned up if the await
// waits are canceled, but the wait code path will handle that.
if (m_asyncHead != null)
{
- Contract.Assert(m_asyncTail != null, "tail should not be null if head isn't null");
+ Debug.Assert(m_asyncTail != null, "tail should not be null if head isn't null");
int maxAsyncToRelease = currentCount - waitCount;
while (maxAsyncToRelease > 0 && m_asyncHead != null)
{
private static void CancellationTokenCanceledEventHandler(object obj)
{
SemaphoreSlim semaphore = obj as SemaphoreSlim;
- Contract.Assert(semaphore != null, "Expected a SemaphoreSlim");
+ Debug.Assert(semaphore != null, "Expected a SemaphoreSlim");
lock (semaphore.m_lockObj)
{
Monitor.PulseAll(semaphore.m_lockObj); //wake up all waiters.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System;
-using System.Diagnostics;
using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Threading
if (!enableThreadOwnerTracking)
{
m_owner |= LOCK_ID_DISABLE_MASK;
- Contract.Assert(!IsThreadOwnerTrackingEnabled, "property should be false by now");
+ Debug.Assert(!IsThreadOwnerTrackingEnabled, "property should be false by now");
}
}
int newOwner = (observedOwner & WAITERS_MASK) == 0 ? // Gets the number of waiters, if zero
observedOwner | 1 // don't decrement it. just set the lock bit, it is zzero because a previous call of Exit(false) ehich corrupted the waiters
: (observedOwner - 2) | 1; // otherwise decrement the waiters and set the lock bit
- Contract.Assert((newOwner & WAITERS_MASK) >= 0);
+ Debug.Assert((newOwner & WAITERS_MASK) >= 0);
if (Interlocked.CompareExchange(ref m_owner, newOwner, observedOwner, ref lockTaken) == observedOwner)
{
int newOwner = (observedOwner & WAITERS_MASK) == 0 ? // Gets the number of waiters, if zero
observedOwner | 1 // don't decrement it. just set the lock bit, it is zzero because a previous call of Exit(false) ehich corrupted the waiters
: (observedOwner - 2) | 1; // otherwise decrement the waiters and set the lock bit
- Contract.Assert((newOwner & WAITERS_MASK) >= 0);
+ Debug.Assert((newOwner & WAITERS_MASK) >= 0);
if (Interlocked.CompareExchange(ref m_owner, newOwner, observedOwner, ref lockTaken) == observedOwner)
{
if ((observedOwner & WAITERS_MASK) == 0) return; // don't decrement the waiters if it's corrupted by previous call of Exit(false)
if (Interlocked.CompareExchange(ref m_owner, observedOwner - 2, observedOwner) == observedOwner)
{
- Contract.Assert(!IsThreadOwnerTrackingEnabled); // Make sure the waiters never be negative which will cause the thread tracking bit to be flipped
+ Debug.Assert(!IsThreadOwnerTrackingEnabled); // Make sure the waiters never be negative which will cause the thread tracking bit to be flipped
break;
}
spinner.SpinOnce();
/// </summary>
private void ContinueTryEnterWithThreadTracking(int millisecondsTimeout, uint startTime, ref bool lockTaken)
{
- Contract.Assert(IsThreadOwnerTrackingEnabled);
+ Debug.Assert(IsThreadOwnerTrackingEnabled);
int lockUnowned = 0;
// We are using thread IDs to mark ownership. Snap the thread ID and check for recursion.
using System.Runtime.ConstrainedExecution;
using System.Security.Permissions;
using System.Threading;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Diagnostics.CodeAnalysis;
#endif
SpinUntil(condition, Timeout.Infinite);
#if DEBUG
- Contract.Assert(result);
+ Debug.Assert(result);
#endif
}
s_lastProcessorCountRefreshTicks = now;
}
- Contract.Assert(procCount > 0 && procCount <= 64,
+ Debug.Assert(procCount > 0 && procCount <= 64,
"Processor count not within the expected range (1 - 64).");
return procCount;
public static int UpdateTimeOut(uint startTime, int originalWaitMillisecondsTimeout)
{
// The function must be called in case the time out is not infinite
- Contract.Assert(originalWaitMillisecondsTimeout != Timeout.Infinite);
+ Debug.Assert(originalWaitMillisecondsTimeout != Timeout.Infinite);
uint elapsedMilliseconds = (GetTime() - startTime);
using System.Runtime.ConstrainedExecution;
using System.Reflection;
using System.Security;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Diagnostics.CodeAnalysis;
#if FEATURE_APPX
private static SynchronizationContext GetWinRTContext()
{
- Contract.Assert(Environment.IsWinRTSupported);
- Contract.Assert(AppDomain.IsAppXModel());
+ Debug.Assert(Environment.IsWinRTSupported);
+ Debug.Assert(AppDomain.IsAppXModel());
//
// We call into the VM to get the dispatcher. This is because:
s_TracerFactory = (WFD.IAsyncCausalityTracerStatics)factory;
EventRegistrationToken token = s_TracerFactory.add_TracingStatusChanged(new EventHandler<WFD.TracingStatusChangedEventArgs>(TracingStatusChangedHandler));
- Contract.Assert(token != default(EventRegistrationToken), "EventRegistrationToken is null");
+ Debug.Assert(token != default(EventRegistrationToken), "EventRegistrationToken is null");
}
catch (Exception ex)
{
// See the LICENSE file in the project root for more information.
using System;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.IO;
using System.Runtime.CompilerServices;
/// It expects that an BeginEndAwaitableAdapter instance was supplied to the APM Begin method as the object state.</summary>
public readonly static AsyncCallback Callback = (asyncResult) => {
- Contract.Assert(asyncResult != null);
- Contract.Assert(asyncResult.IsCompleted);
- Contract.Assert(asyncResult.AsyncState is BeginEndAwaitableAdapter);
+ Debug.Assert(asyncResult != null);
+ Debug.Assert(asyncResult.IsCompleted);
+ Debug.Assert(asyncResult.AsyncState is BeginEndAwaitableAdapter);
// Get the adapter object supplied as the "object state" to the Begin method
BeginEndAwaitableAdapter adapter = (BeginEndAwaitableAdapter) asyncResult.AsyncState;
Action continuation = Interlocked.Exchange(ref adapter._continuation, CALLBACK_RAN);
if (continuation != null) {
- Contract.Assert(continuation != CALLBACK_RAN);
+ Debug.Assert(continuation != CALLBACK_RAN);
continuation();
}
};
/// <param name="continuation">The continuation.</param>
public void UnsafeOnCompleted(Action continuation) {
- Contract.Assert(continuation != null);
+ Debug.Assert(continuation != null);
OnCompleted(continuation);
}
/// <param name="continuation">The continuation.</param>
public void OnCompleted(Action continuation) {
- Contract.Assert(continuation != null);
+ Debug.Assert(continuation != null);
// If the continuation field is null, then set it to be the target continuation
// so that when the operation completes, it'll invoke the continuation. If it's non-null,
/// <returns>The IAsyncResult for the operation.</returns>
public IAsyncResult GetResult() {
- Contract.Assert(_asyncResult != null && _asyncResult.IsCompleted);
+ Debug.Assert(_asyncResult != null && _asyncResult.IsCompleted);
// Get the IAsyncResult
IAsyncResult result = _asyncResult;
ThreadPool.QueueUserWorkItem(state =>
{
var localCs = (CompletionState)state; // don't use 'cs', as it'll force a closure
- Contract.Assert(!localCs.Task.IsCompleted, "Completion should only happen once.");
+ Debug.Assert(!localCs.Task.IsCompleted, "Completion should only happen once.");
var exceptions = localCs.m_exceptions;
bool success = (exceptions != null && exceptions.Count > 0) ?
localCs.TrySetException(exceptions) :
localCs.TrySetResult(default(VoidTaskResult));
- Contract.Assert(success, "Expected to complete completion task.");
+ Debug.Assert(success, "Expected to complete completion task.");
}, cs);
}
}
// Check to see if all tasks have completed and if completion has been requested.
CleanupStateIfCompletingAndQuiesced();
}
- else Contract.Assert(m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL, "The processing count must be the sentinel if it's not >= 0.");
+ else Debug.Assert(m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL, "The processing count must be the sentinel if it's not >= 0.");
}
/// <summary>
try
{
// Note that we're processing exclusive tasks on the current thread
- Contract.Assert(!m_threadProcessingMapping.ContainsKey(Thread.CurrentThread.ManagedThreadId),
+ Debug.Assert(!m_threadProcessingMapping.ContainsKey(Thread.CurrentThread.ManagedThreadId),
"This thread should not yet be involved in this pair's processing.");
m_threadProcessingMapping[Thread.CurrentThread.ManagedThreadId] = ProcessingMode.ProcessingExclusiveTask;
// We're no longer processing exclusive tasks on the current thread
ProcessingMode currentMode;
m_threadProcessingMapping.TryRemove(Thread.CurrentThread.ManagedThreadId, out currentMode);
- Contract.Assert(currentMode == ProcessingMode.ProcessingExclusiveTask,
+ Debug.Assert(currentMode == ProcessingMode.ProcessingExclusiveTask,
"Somehow we ended up escaping exclusive mode.");
lock (ValueLock)
// There might be more concurrent tasks available, for example, if concurrent tasks arrived
// after we exited the loop, or if we exited the loop while concurrent tasks were still
// available but we hit our maxItemsPerTask limit.
- Contract.Assert(m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL, "The processing mode should not have deviated from exclusive.");
+ Debug.Assert(m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL, "The processing mode should not have deviated from exclusive.");
m_processingCount = 0;
ProcessAsyncIfNecessary(true);
}
try
{
// Note that we're processing concurrent tasks on the current thread
- Contract.Assert(!m_threadProcessingMapping.ContainsKey(Thread.CurrentThread.ManagedThreadId),
+ Debug.Assert(!m_threadProcessingMapping.ContainsKey(Thread.CurrentThread.ManagedThreadId),
"This thread should not yet be involved in this pair's processing.");
m_threadProcessingMapping[Thread.CurrentThread.ManagedThreadId] = ProcessingMode.ProcessingConcurrentTasks;
// We're no longer processing concurrent tasks on the current thread
ProcessingMode currentMode;
m_threadProcessingMapping.TryRemove(Thread.CurrentThread.ManagedThreadId, out currentMode);
- Contract.Assert(currentMode == ProcessingMode.ProcessingConcurrentTasks,
+ Debug.Assert(currentMode == ProcessingMode.ProcessingConcurrentTasks,
"Somehow we ended up escaping concurrent mode.");
lock (ValueLock)
// There might be more concurrent tasks available, for example, if concurrent tasks arrived
// after we exited the loop, or if we exited the loop while concurrent tasks were still
// available but we hit our maxItemsPerTask limit.
- Contract.Assert(m_processingCount > 0, "The procesing mode should not have deviated from concurrent.");
+ Debug.Assert(m_processingCount > 0, "The procesing mode should not have deviated from concurrent.");
if (m_processingCount > 0) --m_processingCount;
ProcessAsyncIfNecessary(true);
}
/// <param name="task">The task to be queued.</param>
protected internal override void QueueTask(Task task)
{
- Contract.Assert(task != null, "Infrastructure should have provided a non-null task.");
+ Debug.Assert(task != null, "Infrastructure should have provided a non-null task.");
lock (m_pair.ValueLock)
{
// If the scheduler has already had completion requested, no new work is allowed to be scheduled
/// <param name="task">The task to be executed.</param>
internal void ExecuteTask(Task task)
{
- Contract.Assert(task != null, "Infrastructure should have provided a non-null task.");
+ Debug.Assert(task != null, "Infrastructure should have provided a non-null task.");
base.TryExecuteTask(task);
}
/// <returns>true if the task could be executed; otherwise, false.</returns>
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
- Contract.Assert(task != null, "Infrastructure should have provided a non-null task.");
+ Debug.Assert(task != null, "Infrastructure should have provided a non-null task.");
// If the scheduler has had completion requested, no new work is allowed to be scheduled.
// A non-locked read on m_completionRequested (in CompletionRequested) is acceptable here because:
}
catch
{
- Contract.Assert(t.IsFaulted, "Task should be faulted due to the scheduler faulting it and throwing the exception.");
+ Debug.Assert(t.IsFaulted, "Task should be faulted due to the scheduler faulting it and throwing the exception.");
var ignored = t.Exception;
throw;
}
exceptionThrown = false;
}
catch (SynchronizationLockException) { exceptionThrown = true; }
- Contract.Assert(held == !exceptionThrown, "The locking scheme was not correctly followed.");
+ Debug.Assert(held == !exceptionThrown, "The locking scheme was not correctly followed.");
}
#endif
#else
- Contract.Assert(Monitor.IsEntered(syncObj) == held, "The locking scheme was not correctly followed.");
+ Debug.Assert(Monitor.IsEntered(syncObj) == held, "The locking scheme was not correctly followed.");
#endif
}
using System.Security.Permissions;
using System.Runtime.CompilerServices;
using System.Threading;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.Versioning;
}, state);
if (asyncResult.CompletedSynchronously)
{
- Contract.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed.");
+ Debug.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed.");
FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization: false);
}
}
}, state);
if (asyncResult.CompletedSynchronously)
{
- Contract.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed.");
+ Debug.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed.");
FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization: false);
}
}
}, state);
if (asyncResult.CompletedSynchronously)
{
- Contract.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed.");
+ Debug.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed.");
FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization: false);
}
}
}, state);
if (asyncResult.CompletedSynchronously)
{
- Contract.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed.");
+ Debug.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed.");
FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization: false);
}
}
where TInstance : class
{
// Validate arguments, but only with asserts, as this is an internal only implementation.
- Contract.Assert(thisRef != null, "Expected a non-null thisRef");
- Contract.Assert(beginMethod != null, "Expected a non-null beginMethod");
- Contract.Assert(endMethod != null, "Expected a non-null endMethod");
+ Debug.Assert(thisRef != null, "Expected a non-null thisRef");
+ Debug.Assert(beginMethod != null, "Expected a non-null beginMethod");
+ Debug.Assert(endMethod != null, "Expected a non-null endMethod");
// Create the promise and start the operation.
// No try/catch is necessary here as we want exceptions to bubble out, and because
// If it completed synchronously, we'll handle that here.
if (asyncResult.CompletedSynchronously)
{
- Contract.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed.");
+ Debug.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed.");
promise.Complete(thisRef, endMethod, asyncResult, requiresSynchronization: false);
}
TInstance thisRef, Func<TInstance, IAsyncResult, TResult> endMethod, IAsyncResult asyncResult,
bool requiresSynchronization)
{
- Contract.Assert(!IsCompleted, "The task should not have been completed yet.");
+ Debug.Assert(!IsCompleted, "The task should not have been completed yet.");
// Run the end method and complete the task
bool successfullySet = false;
{
successfullySet = TrySetException(exc);
}
- Contract.Assert(successfullySet, "Expected the task to not yet be completed");
+ Debug.Assert(successfullySet, "Expected the task to not yet be completed");
}
}
}
else
{
- Contract.Assert(continuationAction != null);
+ Debug.Assert(continuationAction != null);
return starter.ContinueWith<TResult>(
// use a cached delegate
}
else
{
- Contract.Assert(continuationAction != null);
+ Debug.Assert(continuationAction != null);
return starter.ContinueWith<TResult>(
//the following delegate avoids closure capture as much as possible
//completedTasks.Result == tasksCopy;
}
else
{
- Contract.Assert(continuationAction != null);
+ Debug.Assert(continuationAction != null);
return starter.ContinueWith<TResult>(
//the following delegate avoids closure capture as much as possible
//completedTask.Result is the winning task; state == continuationAction
}
else
{
- Contract.Assert(continuationAction != null);
+ Debug.Assert(continuationAction != null);
return starter.ContinueWith<TResult>(
// Use a cached delegate
GenericDelegateCache<TAntecedentResult,TResult>.CWAnyActionDelegate,
Func<int, ParallelLoopState, TLocal, TLocal> bodyWithLocal,
Func<TLocal> localInit, Action<TLocal> localFinally)
{
- Contract.Assert(((body == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) + (bodyWithLocal == null ? 0 : 1)) == 1,
+ Debug.Assert(((body == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) + (bodyWithLocal == null ? 0 : 1)) == 1,
"expected exactly one body function to be supplied");
- Contract.Assert(bodyWithLocal != null || (localInit == null && localFinally == null),
+ Debug.Assert(bodyWithLocal != null || (localInit == null && localFinally == null),
"thread local functions should only be supplied for loops w/ thread local bodies");
// Instantiate our result. Specifics will be filled in later.
if (bodyWithState != null)
{
- Contract.Assert(sharedPStateFlags != null);
+ Debug.Assert(sharedPStateFlags != null);
state = new ParallelLoopState32(sharedPStateFlags);
}
else if (bodyWithLocal != null)
{
- Contract.Assert(sharedPStateFlags != null);
+ Debug.Assert(sharedPStateFlags != null);
state = new ParallelLoopState32(sharedPStateFlags);
if (localInit != null)
{
Func<long, ParallelLoopState, TLocal, TLocal> bodyWithLocal,
Func<TLocal> localInit, Action<TLocal> localFinally)
{
- Contract.Assert(((body == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) + (bodyWithLocal == null ? 0 : 1)) == 1,
+ Debug.Assert(((body == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) + (bodyWithLocal == null ? 0 : 1)) == 1,
"expected exactly one body function to be supplied");
- Contract.Assert(bodyWithLocal != null || (localInit == null && localFinally == null),
+ Debug.Assert(bodyWithLocal != null || (localInit == null && localFinally == null),
"thread local functions should only be supplied for loops w/ thread local bodies");
// Instantiate our result. Specifics will be filled in later.
if (bodyWithState != null)
{
- Contract.Assert(sharedPStateFlags != null);
+ Debug.Assert(sharedPStateFlags != null);
state = new ParallelLoopState64(sharedPStateFlags);
}
else if (bodyWithLocal != null)
{
- Contract.Assert(sharedPStateFlags != null);
+ Debug.Assert(sharedPStateFlags != null);
state = new ParallelLoopState64(sharedPStateFlags);
// If a thread-local selector was supplied, invoke it. Otherwise, use the default.
Func<TSource, ParallelLoopState, long, TLocal, TLocal> bodyWithEverything,
Func<TLocal> localInit, Action<TLocal> localFinally)
{
- Contract.Assert(((body == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) +
+ Debug.Assert(((body == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) +
(bodyWithStateAndIndex == null ? 0 : 1) + (bodyWithStateAndLocal == null ? 0 : 1) + (bodyWithEverything == null ? 0 : 1)) == 1,
"expected exactly one body function to be supplied");
- Contract.Assert((bodyWithStateAndLocal != null) || (bodyWithEverything != null) || (localInit == null && localFinally == null),
+ Debug.Assert((bodyWithStateAndLocal != null) || (bodyWithEverything != null) || (localInit == null && localFinally == null),
"thread local functions should only be supplied for loops w/ thread local bodies");
// Before getting started, do a quick peek to see if we have been canceled already
Func<TSource, ParallelLoopState, long, TLocal, TLocal> bodyWithEverything,
Func<TLocal> localInit, Action<TLocal> localFinally)
{
- Contract.Assert(array != null);
- Contract.Assert(parallelOptions != null, "ForEachWorker(array): parallelOptions is null");
+ Debug.Assert(array != null);
+ Debug.Assert(parallelOptions != null, "ForEachWorker(array): parallelOptions is null");
int from = array.GetLowerBound(0);
int to = array.GetUpperBound(0) + 1;
Func<TSource, ParallelLoopState, long, TLocal, TLocal> bodyWithEverything,
Func<TLocal> localInit, Action<TLocal> localFinally)
{
- Contract.Assert(list != null);
- Contract.Assert(parallelOptions != null, "ForEachWorker(list): parallelOptions is null");
+ Debug.Assert(list != null);
+ Debug.Assert(parallelOptions != null, "ForEachWorker(list): parallelOptions is null");
if (body != null)
{
Func<TLocal> localInit,
Action<TLocal> localFinally)
{
- Contract.Assert(((simpleBody == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) +
+ Debug.Assert(((simpleBody == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) +
(bodyWithStateAndIndex == null ? 0 : 1) + (bodyWithStateAndLocal == null ? 0 : 1) + (bodyWithEverything == null ? 0 : 1)) == 1,
"PartitionForEach: expected exactly one body function to be supplied");
- Contract.Assert((bodyWithStateAndLocal != null) || (bodyWithEverything != null) || (localInit == null && localFinally == null),
+ Debug.Assert((bodyWithStateAndLocal != null) || (bodyWithEverything != null) || (localInit == null && localFinally == null),
"PartitionForEach: thread local functions should only be supplied for loops w/ thread local bodies");
OrderablePartitioner<TSource> orderedSource = source as OrderablePartitioner<TSource>;
- Contract.Assert((orderedSource != null) || (bodyWithStateAndIndex == null && bodyWithEverything == null),
+ Debug.Assert((orderedSource != null) || (bodyWithStateAndIndex == null && bodyWithEverything == null),
"PartitionForEach: bodies with indices are only allowable for OrderablePartitioner");
if (!source.SupportsDynamicPartitions)
else if (bodyWithStateAndLocal != null)
localValue = bodyWithStateAndLocal(t, state, localValue);
else
- Contract.Assert(false, "PartitionerForEach: illegal body type in Partitioner handler");
+ Debug.Assert(false, "PartitionerForEach: illegal body type in Partitioner handler");
// Any break, stop or exception causes us to halt
public bool LimitExceeded()
{
- Contract.Assert(m_timeLimit != 0, "Probably the default initializer for LoopTimer was used somewhere");
+ Debug.Assert(m_timeLimit != 0, "Probably the default initializer for LoopTimer was used somewhere");
// comparing against the next expected time saves an addition operation here
// Also we omit the comparison for wrap around here. The only side effect is one extra early yield every 38 days.
{
get
{
- Contract.Assert(false);
+ Debug.Assert(false);
throw new NotSupportedException(
Environment.GetResourceString("ParallelState_NotSupportedException_UnsupportedMethod"));
}
{
get
{
- Contract.Assert(false);
+ Debug.Assert(false);
throw new NotSupportedException(
Environment.GetResourceString("ParallelState_NotSupportedException_UnsupportedMethod"));
}
// Internal/virtual support for Break().
internal virtual void InternalBreak()
{
- Contract.Assert(false);
+ Debug.Assert(false);
throw new NotSupportedException(
Environment.GetResourceString("ParallelState_NotSupportedException_UnsupportedMethod"));
}
using System;
using System.Threading;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
#pragma warning disable 0420
bool bRetVal = FindNewWork(out nFromInclusiveLocal, out nToExclusiveLocal);
- Contract.Assert((nFromInclusiveLocal <= Int32.MaxValue) && (nFromInclusiveLocal >= Int32.MinValue) &&
+ Debug.Assert((nFromInclusiveLocal <= Int32.MaxValue) && (nFromInclusiveLocal >= Int32.MinValue) &&
(nToExclusiveLocal <= Int32.MaxValue) && (nToExclusiveLocal >= Int32.MinValue));
// convert to 32 bit before returning
//
// find the actual number of index ranges we will need
//
- Contract.Assert((uSpan / uRangeSize) < Int32.MaxValue);
+ Debug.Assert((uSpan / uRangeSize) < Int32.MaxValue);
int nNumRanges = (int)(uSpan / uRangeSize);
nCurrentIndex > nToExclusive)
{
// this should only happen at the last index
- Contract.Assert(i == nNumRanges - 1);
+ Debug.Assert(i == nNumRanges - 1);
nCurrentIndex = nToExclusive;
}
/// </summary>
internal RangeWorker RegisterNewWorker()
{
- Contract.Assert(m_indexRanges != null && m_indexRanges.Length != 0);
+ Debug.Assert(m_indexRanges != null && m_indexRanges.Length != 0);
int nInitialRange = (Interlocked.Increment(ref m_nCurrentIndexRangeToAssign) - 1) % m_indexRanges.Length;
internal SingleProducerSingleConsumerQueue()
{
// Validate constants in ctor rather than in an explicit cctor that would cause perf degradation
- Contract.Assert(INIT_SEGMENT_SIZE > 0, "Initial segment size must be > 0.");
- Contract.Assert((INIT_SEGMENT_SIZE & (INIT_SEGMENT_SIZE - 1)) == 0, "Initial segment size must be a power of 2");
- Contract.Assert(INIT_SEGMENT_SIZE <= MAX_SEGMENT_SIZE, "Initial segment size should be <= maximum.");
- Contract.Assert(MAX_SEGMENT_SIZE < Int32.MaxValue / 2, "Max segment size * 2 must be < Int32.MaxValue, or else overflow could occur.");
+ Debug.Assert(INIT_SEGMENT_SIZE > 0, "Initial segment size must be > 0.");
+ Debug.Assert((INIT_SEGMENT_SIZE & (INIT_SEGMENT_SIZE - 1)) == 0, "Initial segment size must be a power of 2");
+ Debug.Assert(INIT_SEGMENT_SIZE <= MAX_SEGMENT_SIZE, "Initial segment size should be <= maximum.");
+ Debug.Assert(MAX_SEGMENT_SIZE < Int32.MaxValue / 2, "Max segment size * 2 must be < Int32.MaxValue, or else overflow could occur.");
// Initialize the queue
m_head = m_tail = new Segment(INIT_SEGMENT_SIZE);
}
int newSegmentSize = m_tail.m_array.Length << 1; // double size
- Contract.Assert(newSegmentSize > 0, "The max size should always be small enough that we don't overflow.");
+ Debug.Assert(newSegmentSize > 0, "The max size should always be small enough that we don't overflow.");
if (newSegmentSize > MAX_SEGMENT_SIZE) newSegmentSize = MAX_SEGMENT_SIZE;
var newSegment = new Segment(newSegmentSize);
/// <remarks>The Count is not thread safe, so we need to acquire the lock.</remarks>
int IProducerConsumerQueue<T>.GetCountSafe(object syncObj)
{
- Contract.Assert(syncObj != null, "The syncObj parameter is null.");
+ Debug.Assert(syncObj != null, "The syncObj parameter is null.");
lock (syncObj)
{
return Count;
// (action,TCO). It should always be true.
internal Task(object state, TaskCreationOptions creationOptions, bool promiseStyle)
{
- Contract.Assert(promiseStyle, "Promise CTOR: promiseStyle was false");
+ Debug.Assert(promiseStyle, "Promise CTOR: promiseStyle was false");
// Check the creationOptions. We allow the AttachedToParent option to be specified for promise tasks.
// Also allow RunContinuationsAsynchronously because this is the constructor called by TCS
InternalTaskOptions.ContinuationTask |
InternalTaskOptions.LazyCancellation |
InternalTaskOptions.QueuedByRuntime));
- Contract.Assert(illegalInternalOptions == 0, "TaskConstructorCore: Illegal internal options");
+ Debug.Assert(illegalInternalOptions == 0, "TaskConstructorCore: Illegal internal options");
#endif
// Throw exception if the user specifies both LongRunning and SelfReplicating
}
// Assign options to m_stateAndOptionsFlag.
- Contract.Assert(m_stateFlags == 0, "TaskConstructorCore: non-zero m_stateFlags");
- Contract.Assert((((int)creationOptions) | OptionsMask) == OptionsMask, "TaskConstructorCore: options take too many bits");
+ Debug.Assert(m_stateFlags == 0, "TaskConstructorCore: non-zero m_stateFlags");
+ Debug.Assert((((int)creationOptions) | OptionsMask) == OptionsMask, "TaskConstructorCore: options take too many bits");
var tmpFlags = (int)creationOptions | (int)internalOptions;
if ((m_action == null) || ((internalOptions & InternalTaskOptions.ContinuationTask) != 0))
{
// we need to do this as the very last thing in the construction path, because the CT registration could modify m_stateFlags
if (cancellationToken.CanBeCanceled)
{
- Contract.Assert((internalOptions &
+ Debug.Assert((internalOptions &
(InternalTaskOptions.ChildReplica | InternalTaskOptions.SelfReplicating | InternalTaskOptions.ContinuationTask)) == 0,
"TaskConstructorCore: Did not expect to see cancelable token for replica/replicating or continuation task.");
antecedentTask.RemoveContinuation(continuation);
}
}
- Contract.Assert(targetTask != null,
+ Debug.Assert(targetTask != null,
"targetTask should have been non-null, with the supplied argument being a task or a tuple containing one");
targetTask.InternalCancel(false);
}
internal void PossiblyCaptureContext(ref StackCrawlMark stackMark)
{
- Contract.Assert(m_contingentProperties == null || m_contingentProperties.m_capturedContext == null,
+ Debug.Assert(m_contingentProperties == null || m_contingentProperties.m_capturedContext == null,
"Captured an ExecutionContext when one was already captured.");
// In the legacy .NET 3.5 build, we don't have the optimized overload of Capture()
// a read of the volatile m_stateFlags field.
internal static TaskCreationOptions OptionsMethod(int flags)
{
- Contract.Assert((OptionsMask & 1) == 1, "OptionsMask needs a shift in Options.get");
+ Debug.Assert((OptionsMask & 1) == 1, "OptionsMask needs a shift in Options.get");
return (TaskCreationOptions)(flags & OptionsMask);
}
/// <param name="enabled">true to set the bit; false to unset the bit.</param>
internal void SetNotificationForWaitCompletion(bool enabled)
{
- Contract.Assert((Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) != 0,
+ Debug.Assert((Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) != 0,
"Should only be used for promise-style tasks"); // hasn't been vetted on other kinds as there hasn't been a need
if (enabled)
// Atomically set the END_AWAIT_NOTIFICATION bit
bool success = AtomicStateUpdate(TASK_STATE_WAIT_COMPLETION_NOTIFICATION,
TASK_STATE_COMPLETED_MASK | TASK_STATE_COMPLETION_RESERVED);
- Contract.Assert(success, "Tried to set enabled on completed Task");
+ Debug.Assert(success, "Tried to set enabled on completed Task");
}
else
{
/// <returns>true if any of the tasks require notification; otherwise, false.</returns>
internal static bool AnyTaskRequiresNotifyDebuggerOfWaitCompletion(Task[] tasks)
{
- Contract.Assert(tasks != null, "Expected non-null array of tasks");
+ Debug.Assert(tasks != null, "Expected non-null array of tasks");
foreach (var task in tasks)
{
if (task != null &&
// bit was unset between the time that it was checked and this method was called.
// It's so remote a chance that it's worth having the assert to protect against misuse.
bool isWaitNotificationEnabled = IsWaitNotificationEnabled;
- Contract.Assert(isWaitNotificationEnabled, "Should only be called if the wait completion bit is set.");
+ Debug.Assert(isWaitNotificationEnabled, "Should only be called if the wait completion bit is set.");
return isWaitNotificationEnabled;
}
}
// It's theoretically possible but extremely rare that this assert could fire because the
// bit was unset between the time that it was checked and this method was called.
// It's so remote a chance that it's worth having the assert to protect against misuse.
- Contract.Assert(IsWaitNotificationEnabled, "Should only be called if the wait completion bit is set.");
+ Debug.Assert(IsWaitNotificationEnabled, "Should only be called if the wait completion bit is set.");
// Now that we're notifying the debugger, clear the bit. The debugger should do this anyway,
// but this adds a bit of protection in case it fails to, and given that the debugger is involved,
/// </summary>
internal void AddNewChild()
{
- Contract.Assert(Task.InternalCurrent == this || this.IsSelfReplicatingRoot, "Task.AddNewChild(): Called from an external context");
+ Debug.Assert(Task.InternalCurrent == this || this.IsSelfReplicatingRoot, "Task.AddNewChild(): Called from an external context");
var props = EnsureContingentPropertiesInitialized();
// We need to subtract that child from m_completionCountdown, or the parent will never complete.
internal void DisregardChild()
{
- Contract.Assert(Task.InternalCurrent == this, "Task.DisregardChild(): Called from an external context");
+ Debug.Assert(Task.InternalCurrent == this, "Task.DisregardChild(): Called from an external context");
var props = EnsureContingentPropertiesInitialized();
- Contract.Assert(props.m_completionCountdown >= 2, "Task.DisregardChild(): Expected parent count to be >= 2");
+ Debug.Assert(props.m_completionCountdown >= 2, "Task.DisregardChild(): Expected parent count to be >= 2");
Interlocked.Decrement(ref props.m_completionCountdown);
}
// Mark ourselves as "handled" to avoid crashing the finalizer thread if the caller neglects to
// call Wait() on this task.
// m_contingentProperties.m_exceptionsHolder *should* already exist after AddException()
- Contract.Assert(
+ Debug.Assert(
(m_contingentProperties != null) &&
(m_contingentProperties.m_exceptionsHolder != null) &&
(m_contingentProperties.m_exceptionsHolder.ContainsFaultList),
}
else
{
- Contract.Assert((m_stateFlags & TASK_STATE_CANCELED) != 0, "Task.RunSynchronously: expected TASK_STATE_CANCELED to be set");
+ Debug.Assert((m_stateFlags & TASK_STATE_CANCELED) != 0, "Task.RunSynchronously: expected TASK_STATE_CANCELED to be set");
// Can't call this method on canceled task.
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Task_RunSynchronously_TaskCompleted);
}
// Only return an exception in faulted state (skip manufactured exceptions)
// A "benevolent" race condition makes it possible to return null when IsFaulted is
// true (i.e., if IsFaulted is set just after the check to IsFaulted above).
- Contract.Assert((e == null) || IsFaulted, "Task.Exception_get(): returning non-null value when not Faulted");
+ Debug.Assert((e == null) || IsFaulted, "Task.Exception_get(): returning non-null value when not Faulted");
return e;
}
/// are not a problem.</param>
internal void ScheduleAndStart(bool needsProtection)
{
- Contract.Assert(m_taskScheduler != null, "expected a task scheduler to have been selected");
- Contract.Assert((m_stateFlags & TASK_STATE_STARTED) == 0, "task has already started");
+ Debug.Assert(m_taskScheduler != null, "expected a task scheduler to have been selected");
+ Debug.Assert((m_stateFlags & TASK_STATE_STARTED) == 0, "task has already started");
// Set the TASK_STATE_STARTED bit
if (needsProtection)
if ((Options & (TaskCreationOptions)InternalTaskOptions.ContinuationTask) == 0)
{
// m_contingentProperties.m_exceptionsHolder *should* already exist after AddException()
- Contract.Assert(
+ Debug.Assert(
(m_contingentProperties != null) &&
(m_contingentProperties.m_exceptionsHolder != null) &&
(m_contingentProperties.m_exceptionsHolder.ContainsFaultList),
var eoAsEdi = exceptionObject as ExceptionDispatchInfo;
var eoAsEnumerableEdi = exceptionObject as IEnumerable<ExceptionDispatchInfo>;
- Contract.Assert(
+ Debug.Assert(
eoAsException != null || eoAsEnumerableException != null || eoAsEdi != null || eoAsEnumerableEdi != null,
"Task.AddException: Expected an Exception, ExceptionDispatchInfo, or an IEnumerable<> of one of those");
var eoAsOce = exceptionObject as OperationCanceledException;
- Contract.Assert(
+ Debug.Assert(
!representsCancellation ||
eoAsOce != null ||
(eoAsEdi != null && eoAsEdi.SourceException is OperationCanceledException),
{
// There are exceptions; get the aggregate and optionally add the canceled
// exception to the aggregate (if applicable).
- Contract.Assert(m_contingentProperties != null); // ExceptionRecorded ==> m_contingentProperties != null
+ Debug.Assert(m_contingentProperties != null); // ExceptionRecorded ==> m_contingentProperties != null
// No need to lock around this, as other logic prevents the consumption of exceptions
// before they have been completely processed.
internal ReadOnlyCollection<ExceptionDispatchInfo> GetExceptionDispatchInfos()
{
bool exceptionsAvailable = IsFaulted && ExceptionRecorded;
- Contract.Assert(exceptionsAvailable, "Must only be used when the task has faulted with exceptions.");
+ Debug.Assert(exceptionsAvailable, "Must only be used when the task has faulted with exceptions.");
return exceptionsAvailable ?
m_contingentProperties.m_exceptionsHolder.GetExceptionDispatchInfos() :
new ReadOnlyCollection<ExceptionDispatchInfo>(new ExceptionDispatchInfo[0]);
/// <returns>The ExceptionDispatchInfo. May be null if no OCE was stored for the task.</returns>
internal ExceptionDispatchInfo GetCancellationExceptionDispatchInfo()
{
- Contract.Assert(IsCanceled, "Must only be used when the task has canceled.");
+ Debug.Assert(IsCanceled, "Must only be used when the task has canceled.");
return Volatile.Read(ref m_contingentProperties)?.m_exceptionsHolder?.GetCancellationExceptionDispatchInfo(); // may be null
}
Contract.Requires(childTask != null);
Contract.Requires(childTask.IsCompleted, "ProcessChildCompletion was called for an uncompleted task");
- Contract.Assert(childTask.m_contingentProperties?.m_parent == this, "ProcessChildCompletion should only be called for a child of this task");
+ Debug.Assert(childTask.m_contingentProperties?.m_parent == this, "ProcessChildCompletion should only be called for a child of this task");
var props = Volatile.Read(ref m_contingentProperties);
{
// Ensure any exceptions thrown by children are added to the parent.
// In doing this, we are implicitly marking children as being "handled".
- Contract.Assert(task.IsCompleted, "Expected all tasks in list to be completed");
+ Debug.Assert(task.IsCompleted, "Expected all tasks in list to be completed");
if (task.IsFaulted && !task.IsExceptionObservedByParent)
{
TaskExceptionHolder exceptionHolder = Volatile.Read(ref task.m_contingentProperties).m_exceptionsHolder;
- Contract.Assert(exceptionHolder != null);
+ Debug.Assert(exceptionHolder != null);
// No locking necessary since child task is finished adding exceptions
// and concurrent CreateExceptionObject() calls do not constitute
/// <param name="delegateRan">Whether the delegate was executed.</param>
internal void FinishThreadAbortedTask(bool bTAEAddedToExceptionHolder, bool delegateRan)
{
- Contract.Assert(!bTAEAddedToExceptionHolder || m_contingentProperties?.m_exceptionsHolder != null,
+ Debug.Assert(!bTAEAddedToExceptionHolder || m_contingentProperties?.m_exceptionsHolder != null,
"FinishThreadAbortedTask() called on a task whose exception holder wasn't initialized");
// this will only be false for non-root self replicating task copies, because all of their exceptions go to the root task.
private static void ExecutionContextCallback(object obj)
{
Task task = obj as Task;
- Contract.Assert(task != null, "expected a task object");
+ Debug.Assert(task != null, "expected a task object");
task.Execute();
}
internal virtual void InnerInvoke()
{
// Invoke the delegate
- Contract.Assert(m_action != null, "Null action in InnerInvoke()");
+ Debug.Assert(m_action != null, "Null action in InnerInvoke()");
var action = m_action as Action;
if (action != null)
{
actionWithState(m_stateObject);
return;
}
- Contract.Assert(false, "Invalid m_action in Task");
+ Debug.Assert(false, "Invalid m_action in Task");
}
/// <summary>
}
else
{
- Contract.Assert(!flowExecutionContext, "We already determined we're not required to flow context.");
+ Debug.Assert(!flowExecutionContext, "We already determined we're not required to flow context.");
if (!AddTaskContinuation(continuationAction, addBeforeOthers: false))
AwaitTaskContinuation.UnsafeScheduleAction(continuationAction, this);
}
Wait(Timeout.Infinite, default(CancellationToken));
#if DEBUG
- Contract.Assert(waitResult, "expected wait to succeed");
+ Debug.Assert(waitResult, "expected wait to succeed");
#endif
}
ThrowIfExceptional(true);
}
- Contract.Assert((m_stateFlags & TASK_STATE_FAULTED) == 0, "Task.Wait() completing when in Faulted state.");
+ Debug.Assert((m_stateFlags & TASK_STATE_FAULTED) == 0, "Task.Wait() completing when in Faulted state.");
return true;
}
}
}
- Contract.Assert(IsCompleted || millisecondsTimeout != Timeout.Infinite);
+ Debug.Assert(IsCompleted || millisecondsTimeout != Timeout.Infinite);
// ETW event for Task Wait End
if (etwIsEnabled)
if (bPopSucceeded)
{
// hitting this would mean something wrong with the AtomicStateUpdate above
- Contract.Assert(!mustCleanup, "Possibly an invalid state transition call was made in InternalCancel()");
+ Debug.Assert(!mustCleanup, "Possibly an invalid state transition call was made in InternalCancel()");
// Include TASK_STATE_DELEGATE_INVOKED in "illegal" bits to protect against the situation where
// TS.TryDequeue() returns true but the task is still left on the queue.
{
RecordInternalCancellationRequest();
- Contract.Assert((Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) != 0, "Task.RecordInternalCancellationRequest(CancellationToken) only valid for promise-style task");
- Contract.Assert(m_contingentProperties.m_cancellationToken == default(CancellationToken));
+ Debug.Assert((Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) != 0, "Task.RecordInternalCancellationRequest(CancellationToken) only valid for promise-style task");
+ Debug.Assert(m_contingentProperties.m_cancellationToken == default(CancellationToken));
// Store the supplied cancellation token as this task's token.
// Waiting on this task will then result in an OperationCanceledException containing this token.
if (oce == null)
{
var edi = cancellationException as ExceptionDispatchInfo;
- Contract.Assert(edi != null, "Expected either an OCE or an EDI");
+ Debug.Assert(edi != null, "Expected either an OCE or an EDI");
oce = edi.SourceException as OperationCanceledException;
- Contract.Assert(oce != null, "Expected EDI to contain an OCE");
+ Debug.Assert(oce != null, "Expected EDI to contain an OCE");
}
- Contract.Assert(oce.CancellationToken == tokenToRecord,
+ Debug.Assert(oce.CancellationToken == tokenToRecord,
"Expected OCE's token to match the provided token.");
#endif
AddException(cancellationException, representsCancellation: true);
// And this method should be called at most once per task.
internal void CancellationCleanupLogic()
{
- Contract.Assert((m_stateFlags & (TASK_STATE_CANCELED | TASK_STATE_COMPLETION_RESERVED)) != 0, "Task.CancellationCleanupLogic(): Task not canceled or reserved.");
+ Debug.Assert((m_stateFlags & (TASK_STATE_CANCELED | TASK_STATE_COMPLETION_RESERVED)) != 0, "Task.CancellationCleanupLogic(): Task not canceled or reserved.");
// I'd like to do this, but there is a small window for a race condition. If someone calls Wait() between InternalCancel() and
// here, that will set m_completionEvent, leading to a meaningless/harmless assertion.
- //Contract.Assert((m_completionEvent == null) || !m_completionEvent.IsSet, "Task.CancellationCleanupLogic(): Completion event already set.");
+ //Debug.Assert((m_completionEvent == null) || !m_completionEvent.IsSet, "Task.CancellationCleanupLogic(): Completion event already set.");
// This may have been set already, but we need to make sure.
Interlocked.Exchange(ref m_stateFlags, m_stateFlags | TASK_STATE_CANCELED);
/// </summary>
private void SetCancellationAcknowledged()
{
- Contract.Assert(this == Task.InternalCurrent, "SetCancellationAcknowledged() should only be called while this is still the current task");
- Contract.Assert(IsCancellationRequested, "SetCancellationAcknowledged() should not be called if the task's CT wasn't signaled");
+ Debug.Assert(this == Task.InternalCurrent, "SetCancellationAcknowledged() should only be called while this is still the current task");
+ Debug.Assert(IsCancellationRequested, "SetCancellationAcknowledged() should not be called if the task's CT wasn't signaled");
m_stateFlags |= TASK_STATE_CANCELLATIONACKNOWLEDGED;
}
// Otherwise, it must be an ITaskCompletionAction, so invoke it.
else
{
- Contract.Assert(currentContinuation is ITaskCompletionAction, "Expected continuation element to be Action, TaskContinuation, or ITaskContinuationAction");
+ Debug.Assert(currentContinuation is ITaskCompletionAction, "Expected continuation element to be Action, TaskContinuation, or ITaskContinuationAction");
var action = (ITaskCompletionAction)currentContinuation;
if (bCanInlineContinuations || !action.InvokeMayRunArbitraryCode)
// m_continuationObject is guaranteed at this point to be either a List or
// s_taskCompletionSentinel.
List<object> list = m_continuationObject as List<object>;
- Contract.Assert((list != null) || (m_continuationObject == s_taskCompletionSentinel),
+ Debug.Assert((list != null) || (m_continuationObject == s_taskCompletionSentinel),
"Expected m_continuationObject to be list or sentinel");
// If list is null, it can only mean that s_taskCompletionSentinel has been exchanged
WaitAll(tasks, Timeout.Infinite);
#if DEBUG
- Contract.Assert(waitResult, "expected wait to succeed");
+ Debug.Assert(waitResult, "expected wait to succeed");
#endif
}
// Now gather up and throw all of the exceptions.
foreach (var task in tasks) AddExceptionsForCompletedTask(ref exceptions, task);
- Contract.Assert(exceptions != null, "Should have seen at least one exception");
+ Debug.Assert(exceptions != null, "Should have seen at least one exception");
ThrowHelper.ThrowAggregateException(exceptions);
}
/// <returns>true if all of the tasks completed; otherwise, false.</returns>
private static bool WaitAllBlockingCore(List<Task> tasks, int millisecondsTimeout, CancellationToken cancellationToken)
{
- Contract.Assert(tasks != null, "Expected a non-null list of tasks");
- Contract.Assert(tasks.Count > 0, "Expected at least one task");
+ Debug.Assert(tasks != null, "Expected a non-null list of tasks");
+ Debug.Assert(tasks.Count > 0, "Expected at least one task");
bool waitCompleted = false;
var mres = new SetOnCountdownMres(tasks.Count);
internal SetOnCountdownMres(int count)
{
- Contract.Assert(count > 0, "Expected count > 0");
+ Debug.Assert(count > 0, "Expected count > 0");
_count = count;
}
public void Invoke(Task completingTask)
{
if (Interlocked.Decrement(ref _count) == 0) Set();
- Contract.Assert(_count >= 0, "Count should never go below 0");
+ Debug.Assert(_count >= 0, "Count should never go below 0");
}
public bool InvokeMayRunArbitraryCode { get { return false; } }
public static int WaitAny(params Task[] tasks)
{
int waitResult = WaitAny(tasks, Timeout.Infinite);
- Contract.Assert(tasks.Length == 0 || waitResult != -1, "expected wait to succeed");
+ Debug.Assert(tasks.Length == 0 || waitResult != -1, "expected wait to succeed");
return waitResult;
}
bool waitCompleted = firstCompleted.Wait(millisecondsTimeout, cancellationToken);
if (waitCompleted)
{
- Contract.Assert(firstCompleted.Status == TaskStatus.RanToCompletion);
+ Debug.Assert(firstCompleted.Status == TaskStatus.RanToCompletion);
signaledTaskIndex = Array.IndexOf(tasks, firstCompleted.Result);
- Contract.Assert(signaledTaskIndex >= 0);
+ Debug.Assert(signaledTaskIndex >= 0);
}
}
var task = new Task<TResult>();
bool succeeded = task.TrySetException(exception);
- Contract.Assert(succeeded, "This should always succeed on a new task.");
+ Debug.Assert(succeeded, "This should always succeed on a new task.");
return task;
}
var task = new Task<TResult>();
bool succeeded = task.TrySetCanceled(exception.CancellationToken, exception);
- Contract.Assert(succeeded, "This should always succeed on a new task.");
+ Debug.Assert(succeeded, "This should always succeed on a new task.");
return task;
}
for (int i = 0; i < m_tasks.Length; i++)
{
var task = m_tasks[i];
- Contract.Assert(task != null, "Constituent task in WhenAll should never be null");
+ Debug.Assert(task != null, "Constituent task in WhenAll should never be null");
if (task.IsFaulted)
{
if (observedExceptions != null)
{
- Contract.Assert(observedExceptions.Count > 0, "Expected at least one exception");
+ Debug.Assert(observedExceptions.Count > 0, "Expected at least one exception");
//We don't need to TraceOperationCompleted here because TrySetException will call Finish and we'll log it there
TrySetResult(default(VoidTaskResult));
}
}
- Contract.Assert(m_count >= 0, "Count should never go below 0");
+ Debug.Assert(m_count >= 0, "Count should never go below 0");
}
public bool InvokeMayRunArbitraryCode { get { return true; } }
for (int i = 0; i < m_tasks.Length; i++)
{
Task<T> task = m_tasks[i];
- Contract.Assert(task != null, "Constituent task in WhenAll should never be null");
+ Debug.Assert(task != null, "Constituent task in WhenAll should never be null");
if (task.IsFaulted)
{
}
else
{
- Contract.Assert(task.Status == TaskStatus.RanToCompletion);
+ Debug.Assert(task.Status == TaskStatus.RanToCompletion);
results[i] = task.GetResultCore(waitCompletionNotification: false); // avoid Result, which would triggering debug notification
}
if (observedExceptions != null)
{
- Contract.Assert(observedExceptions.Count > 0, "Expected at least one exception");
+ Debug.Assert(observedExceptions.Count > 0, "Expected at least one exception");
//We don't need to TraceOperationCompleted here because TrySetException will call Finish and we'll log it there
TrySetResult(results);
}
}
- Contract.Assert(m_count >= 0, "Count should never go below 0");
+ Debug.Assert(m_count >= 0, "Count should never go below 0");
}
public bool InvokeMayRunArbitraryCode { get { return true; } }
Task continuationTask = continuationObject as Task;
if (continuationTask != null)
{
- Contract.Assert(continuationTask.m_action == null);
+ Debug.Assert(continuationTask.m_action == null);
Delegate[] delegates = continuationTask.GetDelegateContinuationsForDebugger();
if (delegates != null)
return delegates;
internal void EndInliningScope()
{
m_inliningDepth--;
- Contract.Assert(m_inliningDepth >= 0, "Inlining depth count should never go negative.");
+ Debug.Assert(m_inliningDepth >= 0, "Inlining depth count should never go negative.");
// do the right thing just in case...
if (m_inliningDepth < 0) m_inliningDepth = 0;
case STATE_WAITING_ON_INNER_TASK:
bool result = TrySetFromTask(completingTask, lookForOce: false);
_state = STATE_DONE; // bump the state
- Contract.Assert(result, "Expected TrySetFromTask from inner task to succeed");
+ Debug.Assert(result, "Expected TrySetFromTask from inner task to succeed");
break;
default:
- Contract.Assert(false, "UnwrapPromise in illegal state");
+ Debug.Assert(false, "UnwrapPromise in illegal state");
break;
}
}
private void ProcessCompletedOuterTask(Task task)
{
Contract.Requires(task != null && task.IsCompleted, "Expected non-null, completed outer task");
- Contract.Assert(_state == STATE_WAITING_ON_OUTER_TASK, "We're in the wrong state!");
+ Debug.Assert(_state == STATE_WAITING_ON_OUTER_TASK, "We're in the wrong state!");
// Bump our state before proceeding any further
_state = STATE_WAITING_ON_INNER_TASK;
case TaskStatus.Canceled:
case TaskStatus.Faulted:
bool result = TrySetFromTask(task, _lookForOce);
- Contract.Assert(result, "Expected TrySetFromTask from outer task to succeed");
+ Debug.Assert(result, "Expected TrySetFromTask from outer task to succeed");
break;
// Otherwise, process the inner task it returned.
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
/// <remarks>Unlike the public methods, this method doesn't currently validate that its arguments are correct.</remarks>
internal bool TrySetException(IEnumerable<ExceptionDispatchInfo> exceptions)
{
- Contract.Assert(exceptions != null);
+ Debug.Assert(exceptions != null);
#if DEBUG
- foreach(var edi in exceptions) Contract.Assert(edi != null, "Contents must be non-null");
+ foreach(var edi in exceptions) Debug.Assert(edi != null, "Contents must be non-null");
#endif
bool rval = m_task.TrySetException(exceptions);
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Security;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.ExceptionServices;
using System.Runtime.CompilerServices;
// Get and null out the antecedent. This is crucial to avoid a memory
// leak with long chains of continuations.
var antecedent = m_antecedent;
- Contract.Assert(antecedent != null,
+ Debug.Assert(antecedent != null,
"No antecedent was set for the ContinuationTaskFromTask.");
m_antecedent = null;
antecedent.NotifyDebuggerOfWaitCompletionIfNecessary();
// Invoke the delegate
- Contract.Assert(m_action != null);
+ Debug.Assert(m_action != null);
var action = m_action as Action<Task>;
if (action != null)
{
actionWithState(antecedent, m_stateObject);
return;
}
- Contract.Assert(false, "Invalid m_action in ContinuationTaskFromTask");
+ Debug.Assert(false, "Invalid m_action in ContinuationTaskFromTask");
}
}
// Get and null out the antecedent. This is crucial to avoid a memory
// leak with long chains of continuations.
var antecedent = m_antecedent;
- Contract.Assert(antecedent != null,
+ Debug.Assert(antecedent != null,
"No antecedent was set for the ContinuationResultTaskFromTask.");
m_antecedent = null;
antecedent.NotifyDebuggerOfWaitCompletionIfNecessary();
// Invoke the delegate
- Contract.Assert(m_action != null);
+ Debug.Assert(m_action != null);
var func = m_action as Func<Task, TResult>;
if (func != null)
{
m_result = funcWithState(antecedent, m_stateObject);
return;
}
- Contract.Assert(false, "Invalid m_action in ContinuationResultTaskFromTask");
+ Debug.Assert(false, "Invalid m_action in ContinuationResultTaskFromTask");
}
}
// Get and null out the antecedent. This is crucial to avoid a memory
// leak with long chains of continuations.
var antecedent = m_antecedent;
- Contract.Assert(antecedent != null,
+ Debug.Assert(antecedent != null,
"No antecedent was set for the ContinuationTaskFromResultTask.");
m_antecedent = null;
antecedent.NotifyDebuggerOfWaitCompletionIfNecessary();
// Invoke the delegate
- Contract.Assert(m_action != null);
+ Debug.Assert(m_action != null);
var action = m_action as Action<Task<TAntecedentResult>>;
if (action != null)
{
actionWithState(antecedent, m_stateObject);
return;
}
- Contract.Assert(false, "Invalid m_action in ContinuationTaskFromResultTask");
+ Debug.Assert(false, "Invalid m_action in ContinuationTaskFromResultTask");
}
}
// Get and null out the antecedent. This is crucial to avoid a memory
// leak with long chains of continuations.
var antecedent = m_antecedent;
- Contract.Assert(antecedent != null,
+ Debug.Assert(antecedent != null,
"No antecedent was set for the ContinuationResultTaskFromResultTask.");
m_antecedent = null;
antecedent.NotifyDebuggerOfWaitCompletionIfNecessary();
// Invoke the delegate
- Contract.Assert(m_action != null);
+ Debug.Assert(m_action != null);
var func = m_action as Func<Task<TAntecedentResult>, TResult>;
if (func != null)
{
m_result = funcWithState(antecedent, m_stateObject);
return;
}
- Contract.Assert(false, "Invalid m_action in ContinuationResultTaskFromResultTask");
+ Debug.Assert(false, "Invalid m_action in ContinuationResultTaskFromResultTask");
}
}
protected static void InlineIfPossibleOrElseQueue(Task task, bool needsProtection)
{
Contract.Requires(task != null);
- Contract.Assert(task.m_taskScheduler != null);
+ Debug.Assert(task.m_taskScheduler != null);
// Set the TASK_STATE_STARTED flag. This only needs to be done
// if the task may be canceled or if someone else has a reference to it
/// <param name="bCanInlineContinuationTask">Whether the continuation can be inlined.</param>
internal override void Run(Task completedTask, bool bCanInlineContinuationTask)
{
- Contract.Assert(completedTask != null);
- Contract.Assert(completedTask.IsCompleted, "ContinuationTask.Run(): completedTask not completed");
+ Debug.Assert(completedTask != null);
+ Debug.Assert(completedTask.IsCompleted, "ContinuationTask.Run(): completedTask not completed");
// Check if the completion status of the task works with the desired
// activation criteria of the TaskContinuationOptions.
SynchronizationContext context, Action action, bool flowExecutionContext, ref StackCrawlMark stackMark) :
base(action, flowExecutionContext, ref stackMark)
{
- Contract.Assert(context != null);
+ Debug.Assert(context != null);
m_syncContext = context;
}
TaskScheduler scheduler, Action action, bool flowExecutionContext, ref StackCrawlMark stackMark) :
base(action, flowExecutionContext, ref stackMark)
{
- Contract.Assert(scheduler != null);
+ Debug.Assert(scheduler != null);
m_scheduler = scheduler;
}
protected void RunCallback(ContextCallback callback, object state, ref Task currentTask)
{
Contract.Requires(callback != null);
- Contract.Assert(currentTask == Task.t_currentTask);
+ Debug.Assert(currentTask == Task.t_currentTask);
// Pretend there's no current task, so that no task is seen as a parent
// and TaskScheduler.Current does not reflect false information
/// </remarks>
internal static void RunOrScheduleAction(Action action, bool allowInlining, ref Task currentTask)
{
- Contract.Assert(currentTask == Task.t_currentTask);
+ Debug.Assert(currentTask == Task.t_currentTask);
// If we're not allowed to run here, schedule the action
if (!allowInlining || !IsValidLocationForInlining)
internal override Delegate[] GetDelegateContinuationsForDebugger()
{
- Contract.Assert(m_action != null);
+ Debug.Assert(m_action != null);
return new Delegate[] { AsyncMethodBuilderCore.TryGetStateMachineForDebugger(m_action) };
}
}
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.ExceptionServices;
using System.Security;
{
Contract.Requires(exceptionObject != null, "Expected exceptionObject to be non-null.");
- Contract.Assert(m_cancellationException == null,
+ Debug.Assert(m_cancellationException == null,
"Expected SetCancellationException to be called only once.");
// Breaking this assumption will overwrite a previously OCE,
// and implies something may be wrong elsewhere, since there should only ever be one.
- Contract.Assert(m_faultExceptions == null,
+ Debug.Assert(m_faultExceptions == null,
"Expected SetCancellationException to be called before any faults were added.");
// Breaking this assumption shouldn't hurt anything here, but it implies something may be wrong elsewhere.
// If this changes, make sure to only conditionally mark as handled below.
else
{
var edi = exceptionObject as ExceptionDispatchInfo;
- Contract.Assert(edi != null && edi.SourceException is OperationCanceledException,
+ Debug.Assert(edi != null && edi.SourceException is OperationCanceledException,
"Expected an OCE or an EDI that contained an OCE");
m_cancellationException = edi;
}
// Initialize the exceptions list if necessary. The list should be non-null iff it contains exceptions.
var exceptions = m_faultExceptions;
if (exceptions == null) m_faultExceptions = exceptions = new List<ExceptionDispatchInfo>(1);
- else Contract.Assert(exceptions.Count > 0, "Expected existing exceptions list to have > 0 exceptions.");
+ else Debug.Assert(exceptions.Count > 0, "Expected existing exceptions list to have > 0 exceptions.");
// Handle Exception by capturing it into an ExceptionDispatchInfo and storing that
var exception = exceptionObject as Exception;
foreach (var exc in exColl)
{
#if DEBUG
- Contract.Assert(exc != null, "No exceptions should be null");
+ Debug.Assert(exc != null, "No exceptions should be null");
numExceptions++;
#endif
exceptions.Add(ExceptionDispatchInfo.Capture(exc));
}
#if DEBUG
- Contract.Assert(numExceptions > 0, "Collection should contain at least one exception.");
+ Debug.Assert(numExceptions > 0, "Collection should contain at least one exception.");
#endif
}
else
{
exceptions.AddRange(ediColl);
#if DEBUG
- Contract.Assert(exceptions.Count > 0, "There should be at least one dispatch info.");
+ Debug.Assert(exceptions.Count > 0, "There should be at least one dispatch info.");
foreach(var tmp in exceptions)
{
- Contract.Assert(tmp != null, "No dispatch infos should be null");
+ Debug.Assert(tmp != null, "No dispatch infos should be null");
}
#endif
}
internal AggregateException CreateExceptionObject(bool calledFromFinalizer, Exception includeThisException)
{
var exceptions = m_faultExceptions;
- Contract.Assert(exceptions != null, "Expected an initialized list.");
- Contract.Assert(exceptions.Count > 0, "Expected at least one exception.");
+ Debug.Assert(exceptions != null, "Expected an initialized list.");
+ Debug.Assert(exceptions.Count > 0, "Expected at least one exception.");
// Mark as handled and aggregate the exceptions.
MarkAsHandled(calledFromFinalizer);
internal ReadOnlyCollection<ExceptionDispatchInfo> GetExceptionDispatchInfos()
{
var exceptions = m_faultExceptions;
- Contract.Assert(exceptions != null, "Expected an initialized list.");
- Contract.Assert(exceptions.Count > 0, "Expected at least one exception.");
+ Debug.Assert(exceptions != null, "Expected an initialized list.");
+ Debug.Assert(exceptions.Count > 0, "Expected at least one exception.");
MarkAsHandled(false);
return new ReadOnlyCollection<ExceptionDispatchInfo>(exceptions);
}
internal ExceptionDispatchInfo GetCancellationExceptionDispatchInfo()
{
var edi = m_cancellationException;
- Contract.Assert(edi == null || edi.SourceException is OperationCanceledException,
+ Debug.Assert(edi == null || edi.SourceException is OperationCanceledException,
"Expected the EDI to be for an OperationCanceledException");
return edi;
}
using System.Security.Permissions;
using System.Runtime.CompilerServices;
using System.Threading;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Threading.Tasks
TrySetResult(_tasks);
}
- Contract.Assert(_count >= 0, "Count should never go below 0");
+ Debug.Assert(_count >= 0, "Count should never go below 0");
}
public bool InvokeMayRunArbitraryCode { get { return true; } }
TrySetResult(_tasks);
}
- Contract.Assert(_count >= 0, "Count should never go below 0");
+ Debug.Assert(_count >= 0, "Count should never go below 0");
}
public bool InvokeMayRunArbitraryCode { get { return true; } }
}
bool success = TrySetResult(completingTask);
- Contract.Assert(success, "Only one task should have gotten to this point, and thus this must be successful.");
+ Debug.Assert(success, "Only one task should have gotten to this point, and thus this must be successful.");
// We need to remove continuations that may be left straggling on other tasks.
// Otherwise, repeated calls to WhenAny using the same task could leak actions.
schedulers.CopyTo(arr, 0);
foreach (var scheduler in arr)
{
- Contract.Assert(scheduler != null, "Table returned an incorrect Count or CopyTo failed");
+ Debug.Assert(scheduler != null, "Table returned an incorrect Count or CopyTo failed");
int tmp = scheduler.Id; // force Ids for debugger
}
return arr;
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.IO;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Threading.Tasks
if (twar != null)
{
task = twar.Task;
- Contract.Assert(task != null, "TaskWrapperAsyncResult should never wrap a null Task.");
+ Debug.Assert(task != null, "TaskWrapperAsyncResult should never wrap a null Task.");
}
// Otherwise, the IAsyncResult should be a Task.
else
if (twar != null)
{
task = twar.Task as Task<TResult>;
- Contract.Assert(twar.Task != null, "TaskWrapperAsyncResult should never wrap a null Task.");
+ Debug.Assert(twar.Task != null, "TaskWrapperAsyncResult should never wrap a null Task.");
}
// Otherwise, the IAsyncResult should be a Task<TResult>.
else
using System;
using System.Security;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Collections.Generic;
using System.Text;
{
Contract.Requires(obj != null, "TaskScheduler.LongRunningThreadWork: obj is null");
Task t = obj as Task;
- Contract.Assert(t != null, "TaskScheduler.LongRunningThreadWork: t is null");
+ Debug.Assert(t != null, "TaskScheduler.LongRunningThreadWork: t is null");
t.ExecuteEntry(false);
}
internal bool TrySetResult(TResult result)
{
if (IsCompleted) return false;
- Contract.Assert(m_action == null, "Task<T>.TrySetResult(): non-null m_action");
+ Debug.Assert(m_action == null, "Task<T>.TrySetResult(): non-null m_action");
// "Reserve" the completion for this task, while making sure that: (1) No prior reservation
// has been made, (2) The result has not already been set, (3) An exception has not previously
// the task, avoiding expensive completion paths, before the task is actually given to anyone.
internal void DangerousSetResult(TResult result)
{
- Contract.Assert(!IsCompleted, "The promise must not yet be completed.");
+ Debug.Assert(!IsCompleted, "The promise must not yet be completed.");
// If we have a parent, we need to notify it of the completion. Take the slow path to handle that.
if (m_contingentProperties?.m_parent != null)
bool success = TrySetResult(result);
// Nobody else has had a chance to complete this Task yet, so we should succeed.
- Contract.Assert(success);
+ Debug.Assert(success);
}
else
{
{
get
{
- Contract.Assert(!IsWaitNotificationEnabledOrNotRanToCompletion,
+ Debug.Assert(!IsWaitNotificationEnabledOrNotRanToCompletion,
"Should only be used when the task completed successfully and there's no wait notification enabled");
return m_result;
}
if (!IsRanToCompletion) ThrowIfExceptional(includeTaskCanceledExceptions: true);
// We shouldn't be here if the result has not been set.
- Contract.Assert(IsRanToCompletion, "Task<T>.Result getter: Expected result to have been set.");
+ Debug.Assert(IsRanToCompletion, "Task<T>.Result getter: Expected result to have been set.");
return m_result;
}
// Called from TaskCompletionSource<T>.SetException(IEnumerable<Exception>).
internal bool TrySetException(object exceptionObject)
{
- Contract.Assert(m_action == null, "Task<T>.TrySetException(): non-null m_action");
+ Debug.Assert(m_action == null, "Task<T>.TrySetException(): non-null m_action");
// TCS.{Try}SetException() should have checked for this
- Contract.Assert(exceptionObject != null, "Expected non-null exceptionObject argument");
+ Debug.Assert(exceptionObject != null, "Expected non-null exceptionObject argument");
// Only accept these types.
- Contract.Assert(
+ Debug.Assert(
(exceptionObject is Exception) || (exceptionObject is IEnumerable<Exception>) ||
(exceptionObject is ExceptionDispatchInfo) || (exceptionObject is IEnumerable<ExceptionDispatchInfo>),
"Expected exceptionObject to be either Exception, ExceptionDispatchInfo, or IEnumerable<> of one of those");
// This method is only valid for promise tasks.
internal bool TrySetCanceled(CancellationToken tokenToRecord, object cancellationException)
{
- Contract.Assert(m_action == null, "Task<T>.TrySetCanceled(): non-null m_action");
+ Debug.Assert(m_action == null, "Task<T>.TrySetCanceled(): non-null m_action");
#if DEBUG
var ceAsEdi = cancellationException as ExceptionDispatchInfo;
- Contract.Assert(
+ Debug.Assert(
cancellationException == null ||
cancellationException is OperationCanceledException ||
(ceAsEdi != null && ceAsEdi.SourceException is OperationCanceledException),
internal override void InnerInvoke()
{
// Invoke the delegate
- Contract.Assert(m_action != null);
+ Debug.Assert(m_action != null);
var func = m_action as Func<TResult>;
if (func != null)
{
m_result = funcWithState(m_stateObject);
return;
}
- Contract.Assert(false, "Invalid m_action in Task<TResult>");
+ Debug.Assert(false, "Invalid m_action in Task<TResult>");
}
#region Await Support
using System.Runtime;
using System.Runtime.InteropServices;
using System;
- using System.Diagnostics;
using System.Security.Permissions;
using System.Security.Principal;
using System.Globalization;
using System.Runtime.ConstrainedExecution;
using System.Security;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
internal delegate Object InternalCrossContextDelegate(Object[] args);
private void SetStartHelper(Delegate start, int maxStackSize)
{
// We only support default stacks in CoreCLR
- Contract.Assert(maxStackSize == 0);
+ Debug.Assert(maxStackSize == 0);
ThreadHelper threadStartCallBack = new ThreadHelper(start);
if(start is ThreadStart)
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
-using System.Diagnostics;
using System.Collections.Generic;
using System.Security.Permissions;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Threading
if (id < 0 || !m_initialized)
{
- Contract.Assert(id >= 0 || !m_initialized, "expected id >= 0 if initialized");
+ Debug.Assert(id >= 0 || !m_initialized, "expected id >= 0 if initialized");
// Handle double Dispose calls or disposal of an instance whose constructor threw an exception.
return;
/// </summary>
private void GrowTable(ref LinkedSlotVolatile[] table, int minLength)
{
- Contract.Assert(table.Length < minLength);
+ Debug.Assert(table.Length < minLength);
// Determine the size of the new table and allocate it.
int newLen = GetNewTableSize(minLength);
// Intentionally return a value that will result in an OutOfMemoryException
return int.MaxValue;
}
- Contract.Assert(minSize > 0);
+ Debug.Assert(minSize > 0);
//
// Round up the size to the next power of 2
~FinalizationHelper()
{
LinkedSlotVolatile[] slotArray = SlotArray;
- Contract.Assert(slotArray != null);
+ Debug.Assert(slotArray != null);
for (int i = 0; i < slotArray.Length; i++)
{
}
// Since the list uses a dummy head node, the Previous reference should never be null.
- Contract.Assert(linkedSlot.Previous != null);
+ Debug.Assert(linkedSlot.Previous != null);
linkedSlot.Previous.Next = linkedSlot.Next;
}
}
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Collections.Generic;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Tracing;
//
m_headIndex = m_headIndex & m_mask;
m_tailIndex = tail = m_tailIndex & m_mask;
- Contract.Assert(m_headIndex <= m_tailIndex);
+ Debug.Assert(m_headIndex <= m_tailIndex);
}
}
finally
IThreadPoolWorkItem unused;
if (LocalPop(out unused))
{
- Contract.Assert(unused == obj);
+ Debug.Assert(unused == obj);
return true;
}
return false;
upper = (i >> 16) & SixteenBits;
lower = i & SixteenBits;
- Contract.Assert(upper >= lower);
- Contract.Assert(upper <= nodes.Length);
- Contract.Assert(lower <= nodes.Length);
- Contract.Assert(upper >= 0);
- Contract.Assert(lower >= 0);
+ Debug.Assert(upper >= lower);
+ Debug.Assert(upper <= nodes.Length);
+ Debug.Assert(lower <= nodes.Length);
+ Debug.Assert(upper >= 0);
+ Debug.Assert(lower >= 0);
}
bool CompareExchangeIndexes(ref int prevUpper, int newUpper, ref int prevLower, int newLower)
{
- Contract.Assert(newUpper >= newLower);
- Contract.Assert(newUpper <= nodes.Length);
- Contract.Assert(newLower <= nodes.Length);
- Contract.Assert(newUpper >= 0);
- Contract.Assert(newLower >= 0);
- Contract.Assert(newUpper >= prevUpper);
- Contract.Assert(newLower >= prevLower);
- Contract.Assert(newUpper == prevUpper ^ newLower == prevLower);
+ Debug.Assert(newUpper >= newLower);
+ Debug.Assert(newUpper <= nodes.Length);
+ Debug.Assert(newLower <= nodes.Length);
+ Debug.Assert(newUpper >= 0);
+ Debug.Assert(newLower >= 0);
+ Debug.Assert(newUpper >= prevUpper);
+ Debug.Assert(newLower >= prevLower);
+ Debug.Assert(newUpper == prevUpper ^ newLower == prevLower);
int oldIndexes = (prevUpper << 16) | (prevLower & SixteenBits);
int newIndexes = (newUpper << 16) | (newLower & SixteenBits);
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public QueueSegment()
{
- Contract.Assert(QueueSegmentLength <= SixteenBits);
+ Debug.Assert(QueueSegmentLength <= SixteenBits);
nodes = new IThreadPoolWorkItem[QueueSegmentLength];
}
// with a busy-wait loop, waiting for the element to become non-null. This implies
// that we can never store null nodes in this data structure.
//
- Contract.Assert(null != node);
+ Debug.Assert(null != node);
int upper, lower;
GetIndexes(out upper, out lower);
if (CompareExchangeIndexes(ref upper, upper + 1, ref lower, lower))
{
- Contract.Assert(Volatile.Read(ref nodes[upper]) == null);
+ Debug.Assert(Volatile.Read(ref nodes[upper]) == null);
Volatile.Write(ref nodes[upper], node);
return true;
}
WorkStealingQueue wsq = tl.workStealingQueue;
if (wsq.LocalPop(out callback))
- Contract.Assert(null != callback);
+ Debug.Assert(null != callback);
if (null == callback)
{
{
if (tail.TryDequeue(out callback))
{
- Contract.Assert(null != callback);
+ Debug.Assert(null != callback);
break;
}
otherQueue != wsq &&
otherQueue.TrySteal(out callback, ref missedSteal))
{
- Contract.Assert(null != callback);
+ Debug.Assert(null != callback);
break;
}
c--;
}
// we can never reach this point, but the C# compiler doesn't know that, because it doesn't know the ThreadAbortException will be reraised above.
- Contract.Assert(false);
+ Debug.Assert(false);
return true;
}
}
IThreadPoolWorkItem cb = null;
if (workStealingQueue.LocalPop(out cb))
{
- Contract.Assert(null != cb);
+ Debug.Assert(null != cb);
workQueue.Enqueue(cb, true);
}
else
~QueueUserWorkItemCallback()
{
- Contract.Assert(
+ Debug.Assert(
executed != 0 || Environment.HasShutdownStarted || AppDomain.CurrentDomain.IsFinalizingForUnload(),
"A QueueUserWorkItemCallback was never called!");
}
void MarkExecuted(bool aborted)
{
GC.SuppressFinalize(this);
- Contract.Assert(
+ Debug.Assert(
0 == Interlocked.Exchange(ref executed, 1) || aborted,
"A QueueUserWorkItemCallback was called twice!");
}
{
QueueUserWorkItemCallback obj = (QueueUserWorkItemCallback)state;
WaitCallback wc = obj.callback as WaitCallback;
- Contract.Assert(null != wc);
+ Debug.Assert(null != wc);
wc(obj.state);
}
}
~QueueUserWorkItemCallbackDefaultContext()
{
- Contract.Assert(
+ Debug.Assert(
executed != 0 || Environment.HasShutdownStarted || AppDomain.CurrentDomain.IsFinalizingForUnload(),
"A QueueUserWorkItemCallbackDefaultContext was never called!");
}
void MarkExecuted(bool aborted)
{
GC.SuppressFinalize(this);
- Contract.Assert(
+ Debug.Assert(
0 == Interlocked.Exchange(ref executed, 1) || aborted,
"A QueueUserWorkItemCallbackDefaultContext was called twice!");
}
{
QueueUserWorkItemCallbackDefaultContext obj = (QueueUserWorkItemCallbackDefaultContext)state;
WaitCallback wc = obj.callback as WaitCallback;
- Contract.Assert(null != wc);
+ Debug.Assert(null != wc);
obj.callback = null;
wc(obj.state);
}
static internal void PerformWaitOrTimerCallback(Object state, bool timedOut)
{
_ThreadPoolWaitOrTimerCallback helper = (_ThreadPoolWaitOrTimerCallback)state;
- Contract.Assert(helper != null, "Null state passed to PerformWaitOrTimerCallback!");
+ Debug.Assert(helper != null, "Null state passed to PerformWaitOrTimerCallback!");
// call directly if it is an unsafe call OR EC flow is suppressed
if (helper._executionContext == null)
{
internal static void UnsafeQueueCustomWorkItem(IThreadPoolWorkItem workItem, bool forceGlobal)
{
- Contract.Assert(null != workItem);
+ Debug.Assert(null != workItem);
EnsureVMInitialized();
//
// This method tries to take the target callback out of the current thread's queue.
internal static bool TryPopCustomWorkItem(IThreadPoolWorkItem workItem)
{
- Contract.Assert(null != workItem);
+ Debug.Assert(null != workItem);
if (!ThreadPoolGlobals.vmTpInitialized)
return false; //Not initialized, so there's no way this workitem was ever queued.
return ThreadPoolGlobals.workQueue.LocalFindAndPop(workItem);
using System.Runtime.InteropServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Diagnostics.Tracing;
using Microsoft.Win32.SafeHandles;
// A later update during resume will re-schedule
if(m_pauseTicks != 0)
{
- Contract.Assert(!m_isAppDomainTimerScheduled);
- Contract.Assert(m_appDomainTimer == null);
+ Debug.Assert(!m_isAppDomainTimerScheduled);
+ Debug.Assert(m_appDomainTimer == null);
return true;
}
if (m_appDomainTimer == null || m_appDomainTimer.IsInvalid)
{
- Contract.Assert(!m_isAppDomainTimerScheduled);
+ Debug.Assert(!m_isAppDomainTimerScheduled);
m_appDomainTimer = CreateAppDomainTimer(actualDuration);
if (!m_appDomainTimer.IsInvalid)
TimerQueueTimer timer = m_timers;
while (timer != null)
{
- Contract.Assert(timer.m_dueTime != Timeout.UnsignedInfinite);
- Contract.Assert(resumedTicks >= timer.m_startTicks);
+ Debug.Assert(timer.m_dueTime != Timeout.UnsignedInfinite);
+ Debug.Assert(resumedTicks >= timer.m_startTicks);
uint elapsed; // How much of the timer dueTime has already elapsed
TimerQueueTimer timer = m_timers;
while (timer != null)
{
- Contract.Assert(timer.m_dueTime != Timeout.UnsignedInfinite);
+ Debug.Assert(timer.m_dueTime != Timeout.UnsignedInfinite);
uint elapsed = (uint)(nowTicks - timer.m_startTicks);
if (elapsed >= timer.m_dueTime)
using Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[Pure]
// Second function in chain so as to not propergate the non-inlining to outside caller
[MethodImpl(MethodImplOptions.NoInlining)]
private static string GetArgumentNameInner(ExceptionArgument argument) {
- Contract.Assert(Enum.IsDefined(typeof(ExceptionArgument), argument),
+ Debug.Assert(Enum.IsDefined(typeof(ExceptionArgument), argument),
"The enum value is not defined, please check the ExceptionArgument Enum.");
return argument.ToString();
// Second function in chain so as to not propergate the non-inlining to outside caller
[MethodImpl(MethodImplOptions.NoInlining)]
private static string GetResourceStringInner(ExceptionResource resource) {
- Contract.Assert(Enum.IsDefined(typeof(ExceptionResource), resource),
+ Debug.Assert(Enum.IsDefined(typeof(ExceptionResource), resource),
"The enum value is not defined, please check the ExceptionResource Enum.");
return Environment.GetResourceString(resource.ToString());
private AdjustmentRule[] GetFilledRules()
{
- Contract.Assert(m_adjustmentRules != null, "m_adjustmentRules expected to be not null");
+ Debug.Assert(m_adjustmentRules != null, "m_adjustmentRules expected to be not null");
AdjustmentRule[] rules = new AdjustmentRule[m_adjustmentRules.Length];
for (int i = 0; i < m_adjustmentRules.Length; i++)
#if FEATURE_WIN32_REGISTRY
throw new InvalidTimeZoneException(Environment.GetResourceString("InvalidTimeZone_InvalidRegistryData", id), e);
#elif PLATFORM_UNIX
- Contract.Assert(e is InvalidTimeZoneException,
+ Debug.Assert(e is InvalidTimeZoneException,
"TryGetTimeZone must create an InvalidTimeZoneException when it returns TimeZoneInfoResult.InvalidTimeZoneException");
throw e;
#endif
using System.Text;
using System.Collections;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
//
case 7:
return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), t.GetHashCode(comparer));
}
- Contract.Assert(false, "Missed all cases for computing Tuple hash code");
+ Debug.Assert(false, "Missed all cases for computing Tuple hash code");
return -1;
}
// 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;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.IO;
using System.Reflection;
string asmName = GetAssemblyName();
// GetAssemblyName never returns null
- Contract.Assert(asmName != null);
+ Debug.Assert(asmName != null);
if (asmName.Length > 0)
{
if (baseType == null)
{
// Cannot resolve the type. If throwOnError is true we should have already thrown.
- Contract.Assert(throwOnError == false);
+ Debug.Assert(throwOnError == false);
return null;
}
types = new Type[typeArguments.Length];
for (int i = 0; i < typeArguments.Length; i++)
{
- Contract.Assert(typeArguments[i] != null);
+ Debug.Assert(typeArguments[i] != null);
using (TypeNameParser argParser = new TypeNameParser(typeArguments[i]))
{
if (types[i] == null)
{
// If throwOnError is true argParser.ConstructType should have already thrown.
- Contract.Assert(throwOnError == false);
+ Debug.Assert(throwOnError == false);
return null;
}
}
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[Serializable]
{
vt = VarEnum.VT_ERROR;
obj = (Object)(((ErrorWrapper)obj).ErrorCode);
- Contract.Assert(obj != null, "obj != null");
+ Debug.Assert(obj != null, "obj != null");
}
else if (obj is CurrencyWrapper)
{
vt = VarEnum.VT_CY;
obj = (Object)(((CurrencyWrapper)obj).WrappedObject);
- Contract.Assert(obj != null, "obj != null");
+ Debug.Assert(obj != null, "obj != null");
}
else if (obj is BStrWrapper)
{
===========================================================*/
namespace System {
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Text;
using CultureInfo = System.Globalization.CultureInfo;
private Version(Version version)
{
- Contract.Assert(version != null);
+ Debug.Assert(version != null);
_Major = version._Major;
_Minor = version._Minor;
private const int ZERO_CHAR_VALUE = (int) '0';
private static void AppendPositiveNumber(int num, StringBuilder sb)
{
- Contract.Assert(num >= 0, "AppendPositiveNumber expect positive numbers");
+ Debug.Assert(num >= 0, "AppendPositiveNumber expect positive numbers");
int index = sb.Length;
int reminder;
} catch (OverflowException e) {
return e;
}
- Contract.Assert(false, "Int32.Parse() did not throw exception but TryParse failed: " + m_exceptionArgument);
+ Debug.Assert(false, "Int32.Parse() did not throw exception but TryParse failed: " + m_exceptionArgument);
return new FormatException(Environment.GetResourceString("Format_InvalidString"));
default:
- Contract.Assert(false, "Unmatched case in Version.GetVersionParseException() for value: " + m_failure);
+ Debug.Assert(false, "Unmatched case in Version.GetVersionParseException() for value: " + m_failure);
return new ArgumentException(Environment.GetResourceString("Arg_VersionString"));
}
}
using System.Security.Permissions;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[System.Runtime.InteropServices.ComVisible(true)]
// Migrating InheritanceDemands requires this default ctor, so we can mark it SafeCritical
protected WeakReference() {
- Contract.Assert(false, "WeakReference's protected default ctor should never be used!");
+ Debug.Assert(false, "WeakReference's protected default ctor should never be used!");
throw new NotImplementedException();
}
using System;
using System.Threading;
using System.Runtime.CompilerServices;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
// Helper class to aid removal of LocalDataStore from the LocalDataStoreMgr
int capacity = m_Manager.GetSlotTableLength();
// Validate that the specified capacity is larger than the current one.
- Contract.Assert(capacity >= m_DataTable.Length, "LocalDataStore corrupted: capacity >= m_DataTable.Length");
+ Debug.Assert(capacity >= m_DataTable.Length, "LocalDataStore corrupted: capacity >= m_DataTable.Length");
// Allocate the new data table.
LocalDataStoreElement[] NewDataTable = new LocalDataStoreElement[capacity];
}
// Validate that there is enough space in the local data store now
- Contract.Assert(slotIdx < m_DataTable.Length, "LocalDataStore corrupted: slotIdx < m_DataTable.Length");
+ Debug.Assert(slotIdx < m_DataTable.Length, "LocalDataStore corrupted: slotIdx < m_DataTable.Length");
if (m_DataTable[slotIdx] == null)
m_DataTable[slotIdx] = new LocalDataStoreElement(slot.Cookie);