diff options
Diffstat (limited to 'src/mscorlib/src/System')
818 files changed, 43587 insertions, 107818 deletions
diff --git a/src/mscorlib/src/System/Action.cs b/src/mscorlib/src/System/Action.cs deleted file mode 100644 index 23c7e93194..0000000000 --- a/src/mscorlib/src/System/Action.cs +++ /dev/null @@ -1,35 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System -{ - public delegate void Action<in T>(T obj); - - public delegate void Action(); - public delegate void Action<in T1,in T2>(T1 arg1, T2 arg2); - public delegate void Action<in T1,in T2,in T3>(T1 arg1, T2 arg2, T3 arg3); - public delegate void Action<in T1,in T2,in T3,in T4>(T1 arg1, T2 arg2, T3 arg3, T4 arg4); - - public delegate TResult Func<out TResult>(); - public delegate TResult Func<in T, out TResult>(T arg); - public delegate TResult Func<in T1, in T2, out TResult>(T1 arg1, T2 arg2); - public delegate TResult Func<in T1, in T2, in T3, out TResult>(T1 arg1, T2 arg2, T3 arg3); - public delegate TResult Func<in T1, in T2, in T3, in T4, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4); - - public delegate void Action<in T1,in T2,in T3,in T4,in T5>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5); - public delegate void Action<in T1,in T2,in T3,in T4,in T5,in T6>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6); - public delegate void Action<in T1,in T2,in T3,in T4,in T5,in T6,in T7>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7); - public delegate void Action<in T1,in T2,in T3,in T4,in T5,in T6,in T7,in T8>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8); - - public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5); - public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6); - public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7); - public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8); - - public delegate int Comparison<in T>(T x, T y); - - public delegate TOutput Converter<in TInput, out TOutput>(TInput input); - - public delegate bool Predicate<in T>(T obj); -} diff --git a/src/mscorlib/src/System/Activator.cs b/src/mscorlib/src/System/Activator.cs index 323fbba9cc..34c6ea5874 100644 --- a/src/mscorlib/src/System/Activator.cs +++ b/src/mscorlib/src/System/Activator.cs @@ -11,8 +11,9 @@ // // // -namespace System { +namespace System +{ using System; using System.Reflection; using System.Runtime.Remoting; @@ -29,9 +30,9 @@ namespace System { // Only statics, does not need to be marked with the serializable attribute public sealed class Activator { - internal const int LookupMask = 0x000000FF; - internal const BindingFlags ConLookup = (BindingFlags) (BindingFlags.Instance | BindingFlags.Public); - internal const BindingFlags ConstructorDefault= BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance; + internal const int LookupMask = 0x000000FF; + internal const BindingFlags ConLookup = (BindingFlags)(BindingFlags.Instance | BindingFlags.Public); + internal const BindingFlags ConstructorDefault = BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance; // This class only contains statics, so hide the worthless constructor private Activator() @@ -47,12 +48,12 @@ namespace System { BindingFlags bindingAttr, Binder binder, Object[] args, - CultureInfo culture) + CultureInfo culture) { return CreateInstance(type, bindingAttr, binder, args, culture, null); } - [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable + [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod static public Object CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, @@ -65,23 +66,24 @@ namespace System { Contract.EndContractBlock(); if (type is System.Reflection.Emit.TypeBuilder) - throw new NotSupportedException(Environment.GetResourceString("NotSupported_CreateInstanceWithTypeBuilder")); + throw new NotSupportedException(SR.NotSupported_CreateInstanceWithTypeBuilder); // If they didn't specify a lookup, then we will provide the default lookup. - if ((bindingAttr & (BindingFlags) LookupMask) == 0) + if ((bindingAttr & (BindingFlags)LookupMask) == 0) bindingAttr |= Activator.ConstructorDefault; - if (activationAttributes != null && activationAttributes.Length > 0){ - throw new PlatformNotSupportedException(Environment.GetResourceString("NotSupported_ActivAttr" )); + if (activationAttributes != null && activationAttributes.Length > 0) + { + throw new PlatformNotSupportedException(SR.NotSupported_ActivAttr); } RuntimeType rt = type.UnderlyingSystemType as RuntimeType; if (rt == null) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(type)); + throw new ArgumentException(SR.Arg_MustBeType, nameof(type)); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; - return rt.CreateInstanceImpl(bindingAttr,binder,args,culture,activationAttributes, ref stackMark); + return rt.CreateInstanceImpl(bindingAttr, binder, args, culture, activationAttributes, ref stackMark); } static public Object CreateInstance(Type type, params Object[] args) @@ -98,14 +100,14 @@ namespace System { Object[] args, Object[] activationAttributes) { - return CreateInstance(type, - Activator.ConstructorDefault, - null, - args, - null, - activationAttributes); + return CreateInstance(type, + Activator.ConstructorDefault, + null, + args, + null, + activationAttributes); } - + static public Object CreateInstance(Type type) { return Activator.CreateInstance(type, false); @@ -116,13 +118,13 @@ namespace System { * types to be created remotely without having to load the type locally. */ - [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable + [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod static public ObjectHandle CreateInstance(String assemblyName, String typeName) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return CreateInstance(assemblyName, - typeName, + typeName, false, Activator.ConstructorDefault, null, @@ -133,15 +135,15 @@ namespace System { ref stackMark); } - [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable + [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod static public ObjectHandle CreateInstance(String assemblyName, String typeName, Object[] activationAttributes) - + { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return CreateInstance(assemblyName, - typeName, + typeName, false, Activator.ConstructorDefault, null, @@ -151,8 +153,8 @@ namespace System { null, ref stackMark); } - - [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable + + [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod static public Object CreateInstance(Type type, bool nonPublic) { if ((object)type == null) @@ -162,13 +164,13 @@ namespace System { RuntimeType rt = type.UnderlyingSystemType as RuntimeType; if (rt == null) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(type)); + throw new ArgumentException(SR.Arg_MustBeType, nameof(type)); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return rt.CreateInstanceDefaultCtor(!nonPublic, false, true, ref stackMark); } - [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable + [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod static public T CreateInstance<T>() { RuntimeType rt = typeof(T) as RuntimeType; @@ -176,7 +178,7 @@ namespace System { // This is a workaround to maintain compatibility with V2. Without this we would throw a NotSupportedException for void[]. // Array, Ref, and Pointer types don't have default constructors. if (rt.HasElementType) - throw new MissingMethodException(Environment.GetResourceString("Arg_NoDefCTor")); + throw new MissingMethodException(SR.Arg_NoDefCTor); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; @@ -186,7 +188,7 @@ namespace System { static public ObjectHandle CreateInstanceFrom(String assemblyFile, String typeName) - + { return CreateInstanceFrom(assemblyFile, typeName, null); } @@ -194,10 +196,10 @@ namespace System { static public ObjectHandle CreateInstanceFrom(String assemblyFile, String typeName, Object[] activationAttributes) - + { return CreateInstanceFrom(assemblyFile, - typeName, + typeName, false, Activator.ConstructorDefault, null, @@ -206,7 +208,7 @@ namespace System { activationAttributes); } - [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable + [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public static ObjectHandle CreateInstance(string assemblyName, string typeName, bool ignoreCase, @@ -229,10 +231,10 @@ namespace System { ref stackMark); } - static internal ObjectHandle CreateInstance(String assemblyString, - String typeName, + static internal ObjectHandle CreateInstance(String assemblyString, + String typeName, bool ignoreCase, - BindingFlags bindingAttr, + BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, @@ -242,18 +244,26 @@ namespace System { { Type type = null; Assembly assembly = null; - if (assemblyString == null) { + if (assemblyString == null) + { assembly = RuntimeAssembly.GetExecutingAssembly(ref stackMark); - } else { + } + else + { RuntimeAssembly assemblyFromResolveEvent; AssemblyName assemblyName = RuntimeAssembly.CreateAssemblyName(assemblyString, false /*forIntrospection*/, out assemblyFromResolveEvent); - if (assemblyFromResolveEvent != null) { + if (assemblyFromResolveEvent != null) + { // Assembly was resolved via AssemblyResolve event assembly = assemblyFromResolveEvent; - } else if (assemblyName.ContentType == AssemblyContentType.WindowsRuntime) { + } + else if (assemblyName.ContentType == AssemblyContentType.WindowsRuntime) + { // WinRT type - we have to use Type.GetType type = Type.GetType(typeName + ", " + assemblyString, true /*throwOnError*/, ignoreCase); - } else { + } + else + { // Classic managed type assembly = RuntimeAssembly.InternalLoadAssemblyName( assemblyName, securityInfo, null, ref stackMark, @@ -261,14 +271,15 @@ namespace System { } } - if (type == null) { + if (type == null) + { // It's classic managed type (not WinRT type) Log(assembly != null, "CreateInstance:: ", "Loaded " + assembly.FullName, "Failed to Load: " + assemblyString); - if(assembly == null) return null; + if (assembly == null) return null; type = assembly.GetType(typeName, true /*throwOnError*/, ignoreCase); } - + Object o = Activator.CreateInstance(type, bindingAttr, binder, @@ -277,9 +288,10 @@ namespace System { activationAttributes); Log(o != null, "CreateInstance:: ", "Created Instance of class " + typeName, "Failed to create instance of class " + typeName); - if(o == null) + if (o == null) return null; - else { + else + { ObjectHandle Handle = new ObjectHandle(o); return Handle; } @@ -306,9 +318,9 @@ namespace System { } private static ObjectHandle CreateInstanceFromInternal(String assemblyFile, - String typeName, + String typeName, bool ignoreCase, - BindingFlags bindingAttr, + BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, @@ -319,7 +331,7 @@ namespace System { Assembly assembly = Assembly.LoadFrom(assemblyFile, securityInfo); #pragma warning restore 618 Type t = assembly.GetType(typeName, true, ignoreCase); - + Object o = Activator.CreateInstance(t, bindingAttr, binder, @@ -328,9 +340,10 @@ namespace System { activationAttributes); Log(o != null, "CreateInstanceFrom:: ", "Created Instance of class " + typeName, "Failed to create instance of class " + typeName); - if(o == null) + if (o == null) return null; - else { + else + { ObjectHandle Handle = new ObjectHandle(o); return Handle; } @@ -343,30 +356,29 @@ namespace System { typeName, null, AssemblyHashAlgorithm.None); - } - + public static ObjectHandle CreateComInstanceFrom(String assemblyName, String typeName, - byte[] hashValue, + byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm) { Assembly assembly = Assembly.LoadFrom(assemblyName, hashValue, hashAlgorithm); Type t = assembly.GetType(typeName, true, false); - Object[] Attr = t.GetCustomAttributes(typeof(ComVisibleAttribute),false); + Object[] Attr = t.GetCustomAttributes(typeof(ComVisibleAttribute), false); if (Attr.Length > 0) { if (((ComVisibleAttribute)Attr[0]).Value == false) - throw new TypeLoadException(Environment.GetResourceString( "Argument_TypeMustBeVisibleFromCom" )); + throw new TypeLoadException(SR.Argument_TypeMustBeVisibleFromCom); } Log(assembly != null, "CreateInstance:: ", "Loaded " + assembly.FullName, "Failed to Load: " + assemblyName); - if(assembly == null) return null; + if (assembly == null) return null; + - Object o = Activator.CreateInstance(t, Activator.ConstructorDefault, null, @@ -375,9 +387,10 @@ namespace System { null); Log(o != null, "CreateInstance:: ", "Created Instance of class " + typeName, "Failed to create instance of class " + typeName); - if(o == null) + if (o == null) return null; - else { + else + { ObjectHandle Handle = new ObjectHandle(o); return Handle; } diff --git a/src/mscorlib/src/System/AggregateException.cs b/src/mscorlib/src/System/AggregateException.cs index c0f21229ed..22bc323215 100644 --- a/src/mscorlib/src/System/AggregateException.cs +++ b/src/mscorlib/src/System/AggregateException.cs @@ -23,7 +23,6 @@ using System.Threading; namespace System { - /// <summary>Represents one or more errors that occur during application execution.</summary> /// <remarks> /// <see cref="AggregateException"/> is used to consolidate multiple failures into a single, throwable @@ -33,14 +32,13 @@ namespace System [DebuggerDisplay("Count = {InnerExceptionCount}")] public class AggregateException : Exception { - private ReadOnlyCollection<Exception> m_innerExceptions; // Complete set of exceptions. /// <summary> /// Initializes a new instance of the <see cref="AggregateException"/> class. /// </summary> public AggregateException() - : base(Environment.GetResourceString("AggregateException_ctor_DefaultMessage")) + : base(SR.AggregateException_ctor_DefaultMessage) { m_innerExceptions = new ReadOnlyCollection<Exception>(new Exception[0]); } @@ -85,7 +83,7 @@ namespace System /// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptions"/> is /// null.</exception> public AggregateException(IEnumerable<Exception> innerExceptions) : - this(Environment.GetResourceString("AggregateException_ctor_DefaultMessage"), innerExceptions) + this(SR.AggregateException_ctor_DefaultMessage, innerExceptions) { } @@ -99,7 +97,7 @@ namespace System /// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptions"/> is /// null.</exception> public AggregateException(params Exception[] innerExceptions) : - this(Environment.GetResourceString("AggregateException_ctor_DefaultMessage"), innerExceptions) + this(SR.AggregateException_ctor_DefaultMessage, innerExceptions) { } @@ -163,7 +161,7 @@ namespace System if (exceptionsCopy[i] == null) { - throw new ArgumentException(Environment.GetResourceString("AggregateException_ctor_InnerExceptionNull")); + throw new ArgumentException(SR.AggregateException_ctor_InnerExceptionNull); } } @@ -182,7 +180,7 @@ namespace System /// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptionInfos"/> is /// null.</exception> internal AggregateException(IEnumerable<ExceptionDispatchInfo> innerExceptionInfos) : - this(Environment.GetResourceString("AggregateException_ctor_DefaultMessage"), innerExceptionInfos) + this(SR.AggregateException_ctor_DefaultMessage, innerExceptionInfos) { } @@ -202,9 +200,9 @@ namespace System internal AggregateException(string message, IEnumerable<ExceptionDispatchInfo> innerExceptionInfos) // If it's already an IList, pass that along (a defensive copy will be made in the delegated ctor). If it's null, just pass along // null typed correctly. Otherwise, create an IList from the enumerable and pass that along. - : this(message, innerExceptionInfos as IList<ExceptionDispatchInfo> ?? - (innerExceptionInfos == null ? - (List<ExceptionDispatchInfo>)null : + : this(message, innerExceptionInfos as IList<ExceptionDispatchInfo> ?? + (innerExceptionInfos == null ? + (List<ExceptionDispatchInfo>)null : new List<ExceptionDispatchInfo>(innerExceptionInfos))) { } @@ -242,7 +240,7 @@ namespace System if (exceptionsCopy[i] == null) { - throw new ArgumentException(Environment.GetResourceString("AggregateException_ctor_InnerExceptionNull")); + throw new ArgumentException(SR.AggregateException_ctor_InnerExceptionNull); } } @@ -269,7 +267,7 @@ namespace System Exception[] innerExceptions = info.GetValue("InnerExceptions", typeof(Exception[])) as Exception[]; if (innerExceptions == null) { - throw new SerializationException(Environment.GetResourceString("AggregateException_DeserializationFailure")); + throw new SerializationException(SR.AggregateException_DeserializationFailure); } m_innerExceptions = new ReadOnlyCollection<Exception>(innerExceptions); @@ -468,7 +466,7 @@ namespace System { text = String.Format( CultureInfo.InvariantCulture, - Environment.GetResourceString("AggregateException_ToString"), + SR.AggregateException_ToString, text, Environment.NewLine, i, m_innerExceptions[i].ToString(), "<---", Environment.NewLine); } @@ -492,5 +490,4 @@ namespace System } } } - } diff --git a/src/mscorlib/src/System/AppContext/AppContext.cs b/src/mscorlib/src/System/AppContext/AppContext.cs index 5a3b732fa8..7c7e74f19b 100644 --- a/src/mscorlib/src/System/AppContext/AppContext.cs +++ b/src/mscorlib/src/System/AppContext/AppContext.cs @@ -35,7 +35,7 @@ namespace System { // The value of APP_CONTEXT_BASE_DIRECTORY key has to be a string and it is not allowed to be any other type. // Otherwise the caller will get invalid cast exception - return (string) AppDomain.CurrentDomain.GetData("APP_CONTEXT_BASE_DIRECTORY") ?? AppDomain.CurrentDomain.BaseDirectory; + return (string)AppDomain.CurrentDomain.GetData("APP_CONTEXT_BASE_DIRECTORY") ?? AppDomain.CurrentDomain.BaseDirectory; } } @@ -72,16 +72,16 @@ namespace System } public static event System.EventHandler<System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs> FirstChanceException - { - add - { - AppDomain.CurrentDomain.FirstChanceException += value; - } - remove - { - AppDomain.CurrentDomain.FirstChanceException -= value; - } - } + { + add + { + AppDomain.CurrentDomain.FirstChanceException += value; + } + remove + { + AppDomain.CurrentDomain.FirstChanceException -= value; + } + } public static event System.EventHandler ProcessExit; internal static event System.EventHandler Unloading; @@ -116,7 +116,7 @@ namespace System if (switchName == null) throw new ArgumentNullException(nameof(switchName)); if (switchName.Length == 0) - throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(switchName)); + throw new ArgumentException(SR.Argument_EmptyName, nameof(switchName)); // By default, the switch is not enabled. isEnabled = false; @@ -144,7 +144,7 @@ namespace System } // We get the value of isEnabled from the value that we stored in the dictionary - isEnabled = (switchValue & SwitchValueState.HasTrueValue) == SwitchValueState.HasTrueValue; + isEnabled = (switchValue & SwitchValueState.HasTrueValue) == SwitchValueState.HasTrueValue; // 2. The switch has a valid value AND we have checked for overrides if ((switchValue & SwitchValueState.HasLookedForOverride) == SwitchValueState.HasLookedForOverride) @@ -212,7 +212,7 @@ namespace System if (switchName == null) throw new ArgumentNullException(nameof(switchName)); if (switchName.Length == 0) - throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(switchName)); + throw new ArgumentException(SR.Argument_EmptyName, nameof(switchName)); SwitchValueState switchValue = (isEnabled ? SwitchValueState.HasTrueValue : SwitchValueState.HasFalseValue) | SwitchValueState.HasLookedForOverride; diff --git a/src/mscorlib/src/System/AppContext/AppContextDefaultValues.Defaults.cs b/src/mscorlib/src/System/AppContext/AppContextDefaultValues.Defaults.cs index 52bdf9d427..ddecf18646 100644 --- a/src/mscorlib/src/System/AppContext/AppContextDefaultValues.Defaults.cs +++ b/src/mscorlib/src/System/AppContext/AppContextDefaultValues.Defaults.cs @@ -8,7 +8,6 @@ namespace System { internal static partial class AppContextDefaultValues { - internal static readonly string SwitchNoAsyncCurrentCulture = "Switch.System.Globalization.NoAsyncCurrentCulture"; internal static readonly string SwitchThrowExceptionIfDisposedCancellationTokenSource = "Switch.System.Threading.ThrowExceptionIfDisposedCancellationTokenSource"; internal static readonly string SwitchPreserveEventListnerObjectIdentity = "Switch.System.Diagnostics.EventSource.PreserveEventListnerObjectIdentity"; diff --git a/src/mscorlib/src/System/AppContext/AppContextSwitches.cs b/src/mscorlib/src/System/AppContext/AppContextSwitches.cs index 5fdd2bc1e6..03b535bda2 100644 --- a/src/mscorlib/src/System/AppContext/AppContextSwitches.cs +++ b/src/mscorlib/src/System/AppContext/AppContextSwitches.cs @@ -2,11 +2,11 @@ // 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.Runtime.CompilerServices; + namespace System { - using System; - using System.Runtime.CompilerServices; - internal static class AppContextSwitches { private static int _noAsyncCurrentCulture; diff --git a/src/mscorlib/src/System/AppDomain.cs b/src/mscorlib/src/System/AppDomain.cs index c6987392d5..7d2f2ceaf8 100644 --- a/src/mscorlib/src/System/AppDomain.cs +++ b/src/mscorlib/src/System/AppDomain.cs @@ -37,59 +37,6 @@ namespace System using System.Diagnostics.Contracts; using System.Runtime.ExceptionServices; - public class ResolveEventArgs : EventArgs - { - private String _Name; - private Assembly _RequestingAssembly; - - public String Name { - get { - return _Name; - } - } - - public Assembly RequestingAssembly - { - get - { - return _RequestingAssembly; - } - } - - public ResolveEventArgs(String name) - { - _Name = name; - } - - public ResolveEventArgs(String name, Assembly requestingAssembly) - { - _Name = name; - _RequestingAssembly = requestingAssembly; - } - } - - public class AssemblyLoadEventArgs : EventArgs - { - private Assembly _LoadedAssembly; - - public Assembly LoadedAssembly { - get { - return _LoadedAssembly; - } - } - - public AssemblyLoadEventArgs(Assembly loadedAssembly) - { - _LoadedAssembly = loadedAssembly; - } - } - - [Serializable] - public delegate Assembly ResolveEventHandler(Object sender, ResolveEventArgs args); - - [Serializable] - public delegate void AssemblyLoadEventHandler(Object sender, AssemblyLoadEventArgs args); - [Serializable] internal delegate void AppDomainInitializer(string[] args); @@ -106,62 +53,61 @@ namespace System internal AppDomainInitializerInfo(AppDomainInitializer init) { - Info=null; - if (init==null) + Info = null; + if (init == null) return; List<ItemInfo> itemInfo = new List<ItemInfo>(); List<AppDomainInitializer> nestedDelegates = new List<AppDomainInitializer>(); nestedDelegates.Add(init); - int idx=0; - - while (nestedDelegates.Count>idx) + int idx = 0; + + while (nestedDelegates.Count > idx) { AppDomainInitializer curr = nestedDelegates[idx++]; - Delegate[] list= curr.GetInvocationList(); - for (int i=0;i<list.Length;i++) + Delegate[] list = curr.GetInvocationList(); + for (int i = 0; i < list.Length; i++) { - if (!list[i].Method.IsStatic) + if (!list[i].Method.IsStatic) { - if(list[i].Target==null) + if (list[i].Target == null) continue; - + AppDomainInitializer nested = list[i].Target as AppDomainInitializer; - if (nested!=null) + if (nested != null) nestedDelegates.Add(nested); else - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeStatic"), - list[i].Method.ReflectedType.FullName+"::"+list[i].Method.Name); + throw new ArgumentException(SR.Arg_MustBeStatic, + list[i].Method.ReflectedType.FullName + "::" + list[i].Method.Name); } else { - ItemInfo info=new ItemInfo(); - info.TargetTypeAssembly=list[i].Method.ReflectedType.Module.Assembly.FullName; - info.TargetTypeName=list[i].Method.ReflectedType.FullName; - info.MethodName=list[i].Method.Name; + ItemInfo info = new ItemInfo(); + info.TargetTypeAssembly = list[i].Method.ReflectedType.Module.Assembly.FullName; + info.TargetTypeName = list[i].Method.ReflectedType.FullName; + info.MethodName = list[i].Method.Name; itemInfo.Add(info); } - } } - Info = itemInfo.ToArray(); + Info = itemInfo.ToArray(); } - + internal AppDomainInitializer Unwrap() { - if (Info==null) + if (Info == null) return null; - AppDomainInitializer retVal=null; - for (int i=0;i<Info.Length;i++) + AppDomainInitializer retVal = null; + for (int i = 0; i < Info.Length; i++) { - Assembly assembly=Assembly.Load(Info[i].TargetTypeAssembly); - AppDomainInitializer newVal=(AppDomainInitializer)Delegate.CreateDelegate(typeof(AppDomainInitializer), + Assembly assembly = Assembly.Load(Info[i].TargetTypeAssembly); + AppDomainInitializer newVal = (AppDomainInitializer)Delegate.CreateDelegate(typeof(AppDomainInitializer), assembly.GetType(Info[i].TargetTypeName), Info[i].MethodName); - if(retVal==null) - retVal=newVal; + if (retVal == null) + retVal = newVal; else - retVal+=newVal; + retVal += newVal; } return retVal; } @@ -176,10 +122,10 @@ namespace System private AppDomainManager _domainManager; private Dictionary<String, Object> _LocalStore; - private AppDomainSetup _FusionStore; - private Evidence _SecurityIdentity; + private AppDomainSetup _FusionStore; + private Evidence _SecurityIdentity; #pragma warning disable 169 - private Object[] _Policies; // Called from the VM. + private Object[] _Policies; // Called from the VM. #pragma warning restore 169 public event AssemblyLoadEventHandler AssemblyLoad; @@ -246,30 +192,27 @@ namespace System } } -#if FEATURE_REFLECTION_ONLY_LOAD - public event ResolveEventHandler ReflectionOnlyAssemblyResolve; -#endif // FEATURE_REFLECTION_ONLY private ApplicationTrust _applicationTrust; - private EventHandler _processExit; + private EventHandler _processExit; - private EventHandler _domainUnload; + private EventHandler _domainUnload; private UnhandledExceptionEventHandler _unhandledException; // The compat flags are set at domain creation time to indicate that the given breaking // changes (named in the strings) should not be used in this domain. We only use the // keys, the vhe values are ignored. - private Dictionary<String, object> _compatFlags; + private Dictionary<String, object> _compatFlags; // Delegate that will hold references to FirstChance exception notifications private EventHandler<FirstChanceExceptionEventArgs> _firstChanceException; - private IntPtr _pDomain; // this is an unmanaged pointer (AppDomain * m_pDomain)` used from the VM. + private IntPtr _pDomain; // this is an unmanaged pointer (AppDomain * m_pDomain)` used from the VM. - private bool _HasSetPolicy; - private bool _IsFastFullTrustDomain; // quick check to see if the AppDomain is fully trusted and homogenous - private bool _compatFlagsInitialized; + private bool _HasSetPolicy; + private bool _IsFastFullTrustDomain; // quick check to see if the AppDomain is fully trusted and homogenous + private bool _compatFlagsInitialized; internal const String TargetFrameworkNameAppCompatSetting = "TargetFrameworkName"; @@ -282,16 +225,12 @@ namespace System [Flags] private enum APPX_FLAGS { - APPX_FLAGS_INITIALIZED = 0x01, - - APPX_FLAGS_APPX_MODEL = 0x02, - APPX_FLAGS_APPX_DESIGN_MODE = 0x04, - APPX_FLAGS_APPX_NGEN = 0x08, - APPX_FLAGS_APPX_MASK = APPX_FLAGS_APPX_MODEL | - APPX_FLAGS_APPX_DESIGN_MODE | - APPX_FLAGS_APPX_NGEN, + APPX_FLAGS_INITIALIZED = 0x01, - APPX_FLAGS_API_CHECK = 0x10, + APPX_FLAGS_APPX_MODEL = 0x02, + APPX_FLAGS_APPX_DESIGN_MODE = 0x04, + APPX_FLAGS_APPX_MASK = APPX_FLAGS_APPX_MODEL | + APPX_FLAGS_APPX_DESIGN_MODE, } private static APPX_FLAGS Flags @@ -305,22 +244,6 @@ namespace System return s_flags; } } - - internal static bool ProfileAPICheck - { - get - { - return (Flags & APPX_FLAGS.APPX_FLAGS_API_CHECK) != 0; - } - } - - internal static bool IsAppXNGen - { - get - { - return (Flags & APPX_FLAGS.APPX_FLAGS_APPX_NGEN) != 0; - } - } #endif // FEATURE_APPX [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] @@ -361,7 +284,7 @@ namespace System // uninitialized object through remoting, etc. if (_pDomain.IsNull()) { - throw new InvalidOperationException(Environment.GetResourceString("Argument_InvalidHandle")); + throw new InvalidOperationException(SR.Argument_InvalidHandle); } return new AppDomainHandle(_pDomain); @@ -417,20 +340,20 @@ namespace System } catch (FileNotFoundException e) { - throw new TypeLoadException(Environment.GetResourceString("Argument_NoDomainManager"), e); + throw new TypeLoadException(SR.Argument_NoDomainManager, e); } catch (SecurityException e) { - throw new TypeLoadException(Environment.GetResourceString("Argument_NoDomainManager"), e); + throw new TypeLoadException(SR.Argument_NoDomainManager, e); } catch (TypeLoadException e) { - throw new TypeLoadException(Environment.GetResourceString("Argument_NoDomainManager"), e); + throw new TypeLoadException(SR.Argument_NoDomainManager, e); } if (_domainManager == null) { - throw new TypeLoadException(Environment.GetResourceString("Argument_NoDomainManager")); + throw new TypeLoadException(SR.Argument_NoDomainManager); } // If this domain was not created by a managed call to CreateDomain, then the AppDomainSetup @@ -463,7 +386,7 @@ namespace System private void InitializeCompatibilityFlags() { AppDomainSetup adSetup = FusionStore; - + // set up shim flags regardless of whether we create a DomainManager in this method. if (adSetup.GetCompatibilityFlags() != null) { @@ -521,7 +444,7 @@ namespace System { #if FEATURE_APPX if (IsAppXModel()) - throw new NotSupportedException(Environment.GetResourceString("NotSupported_AppX", "Assembly.LoadFrom")); + throw new NotSupportedException(SR.Format(SR.NotSupported_AppX, "Assembly.LoadFrom")); #endif } @@ -533,7 +456,7 @@ namespace System { #if FEATURE_APPX if (IsAppXModel()) - throw new NotSupportedException(Environment.GetResourceString("NotSupported_AppX", "Assembly.LoadFile")); + throw new NotSupportedException(SR.Format(SR.NotSupported_AppX, "Assembly.LoadFile")); #endif } @@ -545,7 +468,7 @@ namespace System { #if FEATURE_APPX if (IsAppXModel()) - throw new NotSupportedException(Environment.GetResourceString("NotSupported_AppX", "Assembly.ReflectionOnlyLoad")); + throw new NotSupportedException(SR.Format(SR.NotSupported_AppX, "Assembly.ReflectionOnlyLoad")); #endif } @@ -557,7 +480,7 @@ namespace System { #if FEATURE_APPX if (IsAppXModel()) - throw new NotSupportedException(Environment.GetResourceString("NotSupported_AppX", "Assembly.Load(byte[], ...)")); + throw new NotSupportedException(SR.Format(SR.NotSupported_AppX, "Assembly.Load(byte[], ...)")); #endif } @@ -603,17 +526,20 @@ namespace System bool runtimeSuppliedHomogenousGrant = false; ApplicationTrust appTrust = adSetup.ApplicationTrust; - if (appTrust != null) { + if (appTrust != null) + { SetupDomainSecurityForHomogeneousDomain(appTrust, runtimeSuppliedHomogenousGrant); } - else if (_IsFastFullTrustDomain) { + else if (_IsFastFullTrustDomain) + { SetSecurityHomogeneousFlag(GetNativeHandle(), runtimeSuppliedHomogenousGrant); } // Get the evidence supplied for the domain. If no evidence was supplied, it means that we want // to use the default evidence creation strategy for this domain Evidence newAppDomainEvidence = (providedSecurityInfo != null ? providedSecurityInfo : creatorsSecurityInfo); - if (newAppDomainEvidence == null && generateDefaultEvidence) { + if (newAppDomainEvidence == null && generateDefaultEvidence) + { newAppDomainEvidence = new Evidence(); } @@ -650,63 +576,18 @@ namespace System runtimeSuppliedHomogenousGrantSet); } - public AppDomainManager DomainManager { - get { - return _domainManager; - } - } - -#if FEATURE_REFLECTION_ONLY_LOAD - private Assembly ResolveAssemblyForIntrospection(Object sender, ResolveEventArgs args) - { - Contract.Requires(args != null); - return Assembly.ReflectionOnlyLoad(ApplyPolicy(args.Name)); - } - - // Helper class for method code:EnableResolveAssembliesForIntrospection - private class NamespaceResolverForIntrospection + public AppDomainManager DomainManager { - private IEnumerable<string> _packageGraphFilePaths; - public NamespaceResolverForIntrospection(IEnumerable<string> packageGraphFilePaths) - { - _packageGraphFilePaths = packageGraphFilePaths; - } - - public void ResolveNamespace( - object sender, - System.Runtime.InteropServices.WindowsRuntime.NamespaceResolveEventArgs args) + get { - Contract.Requires(args != null); - - IEnumerable<string> fileNames = System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMetadata.ResolveNamespace( - args.NamespaceName, - null, // windowsSdkFilePath ... Use OS installed .winmd files - _packageGraphFilePaths); - foreach (string fileName in fileNames) - { - args.ResolvedAssemblies.Add(Assembly.ReflectionOnlyLoadFrom(fileName)); - } + return _domainManager; } } - - // Called only by native function code:ValidateWorker - private void EnableResolveAssembliesForIntrospection(string verifiedFileDirectory) - { - CurrentDomain.ReflectionOnlyAssemblyResolve += new ResolveEventHandler(ResolveAssemblyForIntrospection); - - string[] packageGraphFilePaths = null; - if (verifiedFileDirectory != null) - packageGraphFilePaths = new string[] { verifiedFileDirectory }; - NamespaceResolverForIntrospection namespaceResolver = new NamespaceResolverForIntrospection(packageGraphFilePaths); - - System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMetadata.ReflectionOnlyNamespaceResolve += - new EventHandler<System.Runtime.InteropServices.WindowsRuntime.NamespaceResolveEventArgs>(namespaceResolver.ResolveNamespace); - } -#endif // FEATURE_REFLECTION_ONLY_LOAD + public ObjectHandle CreateInstance(String assemblyName, String typeName) - + { // jit does not check for that, so we should do it ... if (this == null) @@ -722,7 +603,8 @@ namespace System public static AppDomain CurrentDomain { - get { + get + { Contract.Ensures(Contract.Result<AppDomain>() != null); return Thread.GetDomain(); } @@ -730,7 +612,8 @@ namespace System public String BaseDirectory { - get { + get + { return FusionStore.ApplicationBase; } } @@ -740,26 +623,29 @@ namespace System StringBuilder sb = StringBuilderCache.Acquire(); String fn = nGetFriendlyName(); - if (fn != null) { - sb.Append(Environment.GetResourceString("Loader_Name") + fn); + if (fn != null) + { + sb.Append(SR.Loader_Name + fn); sb.Append(Environment.NewLine); } - if(_Policies == null || _Policies.Length == 0) - sb.Append(Environment.GetResourceString("Loader_NoContextPolicies") + if (_Policies == null || _Policies.Length == 0) + sb.Append(SR.Loader_NoContextPolicies + Environment.NewLine); - else { - sb.Append(Environment.GetResourceString("Loader_ContextPolicies") + else + { + sb.Append(SR.Loader_ContextPolicies + Environment.NewLine); - for(int i = 0;i < _Policies.Length; i++) { + for (int i = 0; i < _Policies.Length; i++) + { sb.Append(_Policies[i]); sb.Append(Environment.NewLine); } } - + return StringBuilderCache.GetStringAndRelease(sb); } - + // this is true when we've removed the handles etc so really can't do anything [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern bool IsUnloadingForcedFinalize(); @@ -772,22 +658,25 @@ namespace System [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void PublishAnonymouslyHostedDynamicMethodsAssembly(RuntimeAssembly assemblyHandle); - public void SetData (string name, object data) { + public void SetData(string name, object data) + { if (name == null) throw new ArgumentNullException(nameof(name)); Contract.EndContractBlock(); // SetData should only be used to set values that don't already exist. object currentVal; - lock (((ICollection)LocalStore).SyncRoot) { + lock (((ICollection)LocalStore).SyncRoot) + { LocalStore.TryGetValue(name, out currentVal); } if (currentVal != null) { - throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_SetData_OnlyOnce")); + throw new InvalidOperationException(SR.InvalidOperation_SetData_OnlyOnce); } - lock (((ICollection)LocalStore).SyncRoot) { + lock (((ICollection)LocalStore).SyncRoot) + { LocalStore[name] = data; } } @@ -795,19 +684,20 @@ namespace System [Pure] public Object GetData(string name) { - if(name == null) + if (name == null) throw new ArgumentNullException(nameof(name)); Contract.EndContractBlock(); int key = AppDomainSetup.Locate(name); - if(key == -1) + if (key == -1) { - if(name.Equals(AppDomainSetup.LoaderOptimizationKey)) + if (name.Equals(AppDomainSetup.LoaderOptimizationKey)) return FusionStore.LoaderOptimization; - else + else { object data; - lock (((ICollection)LocalStore).SyncRoot) { + lock (((ICollection)LocalStore).SyncRoot) + { LocalStore.TryGetValue(name, out data); } if (data == null) @@ -815,27 +705,30 @@ namespace System return data; } } - else { + else + { // Be sure to call these properties, not Value, so // that the appropriate permission demand will be done - switch(key) { - case (int) AppDomainSetup.LoaderInformation.ApplicationBaseValue: - return FusionStore.ApplicationBase; - case (int) AppDomainSetup.LoaderInformation.ApplicationNameValue: - return FusionStore.ApplicationName; - default: - Debug.Assert(false, "Need to handle new LoaderInformation value in AppDomain.GetData()"); - return null; + switch (key) + { + case (int)AppDomainSetup.LoaderInformation.ApplicationBaseValue: + return FusionStore.ApplicationBase; + case (int)AppDomainSetup.LoaderInformation.ApplicationNameValue: + return FusionStore.ApplicationName; + default: + Debug.Assert(false, "Need to handle new LoaderInformation value in AppDomain.GetData()"); + return null; } } } - + [Obsolete("AppDomain.GetCurrentThreadId has been deprecated because it does not provide a stable Id when managed threads are running on fibers (aka lightweight threads). To get a stable identifier for a managed thread, use the ManagedThreadId property on Thread. http://go.microsoft.com/fwlink/?linkid=14202", false)] [DllImport(Microsoft.Win32.Win32Native.KERNEL32)] public static extern int GetCurrentThreadId(); - private AppDomain() { - throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_Constructor)); + private AppDomain() + { + throw new NotSupportedException(SR.GetResourceString(ResId.NotSupported_Constructor)); } [MethodImplAttribute(MethodImplOptions.InternalCall)] @@ -866,13 +759,13 @@ namespace System if (value != null) { RuntimeHelpers.PrepareContractedDelegate(value); - lock(this) + lock (this) _processExit += value; } } remove { - lock(this) + lock (this) _processExit -= value; } } @@ -885,13 +778,13 @@ namespace System if (value != null) { RuntimeHelpers.PrepareContractedDelegate(value); - lock(this) + lock (this) _domainUnload += value; } } remove { - lock(this) + lock (this) _domainUnload -= value; } } @@ -904,13 +797,13 @@ namespace System if (value != null) { RuntimeHelpers.PrepareContractedDelegate(value); - lock(this) + lock (this) _unhandledException += value; } } remove { - lock(this) + lock (this) _unhandledException -= value; } } @@ -926,13 +819,13 @@ namespace System if (value != null) { RuntimeHelpers.PrepareContractedDelegate(value); - lock(this) + lock (this) _firstChanceException += value; } } remove { - lock(this) + lock (this) _firstChanceException -= value; } } @@ -940,22 +833,24 @@ namespace System private void OnAssemblyLoadEvent(RuntimeAssembly LoadedAssembly) { AssemblyLoadEventHandler eventHandler = AssemblyLoad; - if (eventHandler != null) { + if (eventHandler != null) + { AssemblyLoadEventArgs ea = new AssemblyLoadEventArgs(LoadedAssembly); eventHandler(this, ea); } } - + // This method is called by the VM. private RuntimeAssembly OnResourceResolveEvent(RuntimeAssembly assembly, String resourceName) { ResolveEventHandler eventHandler = _ResourceResolve; - if ( eventHandler == null) + if (eventHandler == null) return null; Delegate[] ds = eventHandler.GetInvocationList(); int len = ds.Length; - for (int i = 0; i < len; i++) { + for (int i = 0; i < len; i++) + { Assembly asm = ((ResolveEventHandler)ds[i])(this, new ResolveEventArgs(resourceName, assembly)); RuntimeAssembly ret = GetRuntimeAssembly(asm); if (ret != null) @@ -964,7 +859,7 @@ namespace System return null; } - + // This method is called by the VM private RuntimeAssembly OnTypeResolveEvent(RuntimeAssembly assembly, String typeName) { @@ -974,7 +869,8 @@ namespace System Delegate[] ds = eventHandler.GetInvocationList(); int len = ds.Length; - for (int i = 0; i < len; i++) { + for (int i = 0; i < len; i++) + { Assembly asm = ((ResolveEventHandler)ds[i])(this, new ResolveEventArgs(typeName, assembly)); RuntimeAssembly ret = GetRuntimeAssembly(asm); if (ret != null) @@ -996,13 +892,14 @@ namespace System Delegate[] ds = eventHandler.GetInvocationList(); int len = ds.Length; - for (int i = 0; i < len; i++) { + for (int i = 0; i < len; i++) + { Assembly asm = ((ResolveEventHandler)ds[i])(this, new ResolveEventArgs(assemblyFullName, assembly)); RuntimeAssembly ret = GetRuntimeAssembly(asm); if (ret != null) return ret; } - + return null; } @@ -1016,8 +913,9 @@ namespace System internal AppDomainSetup FusionStore { - get { - Debug.Assert(_FusionStore != null, + get + { + Debug.Assert(_FusionStore != null, "Fusion store has not been correctly setup in this domain"); return _FusionStore; } @@ -1041,10 +939,12 @@ namespace System private Dictionary<String, Object> LocalStore { - get { + get + { if (_LocalStore != null) return _LocalStore; - else { + else + { _LocalStore = new Dictionary<String, Object>(); return _LocalStore; } @@ -1061,7 +961,7 @@ namespace System if (info.ApplicationBase == null) { - info.SetupDefaults(RuntimeEnvironment.GetModuleFileName(), imageLocationAlreadyNormalized : true); + info.SetupDefaults(RuntimeEnvironment.GetModuleFileName(), imageLocationAlreadyNormalized: true); } nCreateContext(); @@ -1074,11 +974,11 @@ namespace System private static void RunInitializer(AppDomainSetup setup) { - if (setup.AppDomainInitializer!=null) + if (setup.AppDomainInitializer != null) { - string[] args=null; - if (setup.AppDomainInitializerArguments!=null) - args=(string[])setup.AppDomainInitializerArguments.Clone(); + string[] args = null; + if (setup.AppDomainInitializerArguments != null) + args = (string[])setup.AppDomainInitializerArguments.Clone(); setup.AppDomainInitializer(args); } } @@ -1101,8 +1001,8 @@ namespace System bool generateDefaultEvidence = false; AppDomainInitializerInfo initializerInfo = null; - if (setup!=null && setup.AppDomainInitializer!=null) - initializerInfo=new AppDomainInitializerInfo(setup.AppDomainInitializer); + if (setup != null && setup.AppDomainInitializer != null) + initializerInfo = new AppDomainInitializerInfo(setup.AppDomainInitializer); // will travel x-Ad, drop non-agile data AppDomainSetup newSetup = new AppDomainSetup(setup, false); @@ -1115,63 +1015,61 @@ namespace System // System.AppDomainManager.CreateDomain() and add the flags to the AppDomainSetup List<String> compatList = new List<String>(); - if(propertyNames!=null && propertyValues != null) + if (propertyNames != null && propertyValues != null) { - for (int i=0; i<propertyNames.Length; i++) + for (int i = 0; i < propertyNames.Length; i++) { - if(String.Compare(propertyNames[i], "AppDomainCompatSwitch", StringComparison.OrdinalIgnoreCase) == 0) + if (String.Compare(propertyNames[i], "AppDomainCompatSwitch", StringComparison.OrdinalIgnoreCase) == 0) { compatList.Add(propertyValues[i]); propertyNames[i] = null; propertyValues[i] = null; } - } - + if (compatList.Count > 0) { newSetup.SetCompatibilitySwitches(compatList); } } - return new Object[] + return new Object[] { - friendlyName, - newSetup, - parentSecurityDescriptor, + friendlyName, + newSetup, + parentSecurityDescriptor, generateDefaultEvidence, serializedEvidence, initializerInfo, sandboxName, propertyNames, propertyValues - }; + }; } // PrepareDataForSetup - [MethodImplAttribute(MethodImplOptions.NoInlining)] private static Object Setup(Object arg) { Contract.Requires(arg != null && arg is Object[]); Contract.Requires(((Object[])arg).Length >= 8); - Object[] args=(Object[])arg; - String friendlyName = (String)args[0]; - AppDomainSetup setup = (AppDomainSetup)args[1]; - IntPtr parentSecurityDescriptor = (IntPtr)args[2]; - bool generateDefaultEvidence = (bool)args[3]; - byte[] serializedEvidence = (byte[])args[4]; - AppDomainInitializerInfo initializerInfo = (AppDomainInitializerInfo)args[5]; - string sandboxName = (string)args[6]; - string[] propertyNames = (string[])args[7]; // can contain null elements - string[] propertyValues = (string[])args[8]; // can contain null elements + Object[] args = (Object[])arg; + String friendlyName = (String)args[0]; + AppDomainSetup setup = (AppDomainSetup)args[1]; + IntPtr parentSecurityDescriptor = (IntPtr)args[2]; + bool generateDefaultEvidence = (bool)args[3]; + byte[] serializedEvidence = (byte[])args[4]; + AppDomainInitializerInfo initializerInfo = (AppDomainInitializerInfo)args[5]; + string sandboxName = (string)args[6]; + string[] propertyNames = (string[])args[7]; // can contain null elements + string[] propertyValues = (string[])args[8]; // can contain null elements // extract evidence Evidence providedSecurityInfo = null; Evidence creatorsSecurityInfo = null; AppDomain ad = AppDomain.CurrentDomain; - AppDomainSetup newSetup=new AppDomainSetup(setup,false); + AppDomainSetup newSetup = new AppDomainSetup(setup, false); - if(propertyNames!=null && propertyValues != null) + if (propertyNames != null && propertyValues != null) { for (int i = 0; i < propertyNames.Length; i++) { @@ -1190,55 +1088,55 @@ namespace System } } - for (int i=0; i<propertyNames.Length; i++) + for (int i = 0; i < propertyNames.Length; i++) { - if(propertyNames[i]=="APPBASE") // make sure in sync with Fusion + if (propertyNames[i] == "APPBASE") // make sure in sync with Fusion { - if(propertyValues[i]==null) + if (propertyValues[i] == null) throw new ArgumentNullException("APPBASE"); if (PathInternal.IsPartiallyQualified(propertyValues[i])) - throw new ArgumentException( Environment.GetResourceString( "Argument_AbsolutePathRequired" ) ); + throw new ArgumentException(SR.Argument_AbsolutePathRequired); newSetup.ApplicationBase = NormalizePath(propertyValues[i], fullCheck: true); } - else if(propertyNames[i]=="LOADER_OPTIMIZATION") + else if (propertyNames[i] == "LOADER_OPTIMIZATION") { - if(propertyValues[i]==null) + if (propertyValues[i] == null) throw new ArgumentNullException("LOADER_OPTIMIZATION"); - switch(propertyValues[i]) + switch (propertyValues[i]) { - case "SingleDomain": newSetup.LoaderOptimization=LoaderOptimization.SingleDomain;break; - case "MultiDomain": newSetup.LoaderOptimization=LoaderOptimization.MultiDomain;break; - case "MultiDomainHost": newSetup.LoaderOptimization=LoaderOptimization.MultiDomainHost;break; - case "NotSpecified": newSetup.LoaderOptimization=LoaderOptimization.NotSpecified;break; - default: throw new ArgumentException(Environment.GetResourceString("Argument_UnrecognizedLoaderOptimization"), "LOADER_OPTIMIZATION"); + case "SingleDomain": newSetup.LoaderOptimization = LoaderOptimization.SingleDomain; break; + case "MultiDomain": newSetup.LoaderOptimization = LoaderOptimization.MultiDomain; break; + case "MultiDomainHost": newSetup.LoaderOptimization = LoaderOptimization.MultiDomainHost; break; + case "NotSpecified": newSetup.LoaderOptimization = LoaderOptimization.NotSpecified; break; + default: throw new ArgumentException(SR.Argument_UnrecognizedLoaderOptimization, "LOADER_OPTIMIZATION"); } } - else if(propertyNames[i]=="TRUSTED_PLATFORM_ASSEMBLIES" || - propertyNames[i]=="PLATFORM_RESOURCE_ROOTS" || - propertyNames[i]=="APP_PATHS" || - propertyNames[i]=="APP_NI_PATHS") + else if (propertyNames[i] == "TRUSTED_PLATFORM_ASSEMBLIES" || + propertyNames[i] == "PLATFORM_RESOURCE_ROOTS" || + propertyNames[i] == "APP_PATHS" || + propertyNames[i] == "APP_NI_PATHS") { string values = propertyValues[i]; - if(values == null) + if (values == null) throw new ArgumentNullException(propertyNames[i]); ad.SetData(propertyNames[i], NormalizeAppPaths(values)); } - else if(propertyNames[i]!= null) + else if (propertyNames[i] != null) { - ad.SetData(propertyNames[i],propertyValues[i]); // just propagate + ad.SetData(propertyNames[i], propertyValues[i]); // just propagate } } } ad.SetupFusionStore(newSetup, null); // makes FusionStore a ref to newSetup - + // technically, we don't need this, newSetup refers to the same object as FusionStore // but it's confusing since it isn't immediately obvious whether we have a ref or a copy - AppDomainSetup adSetup = ad.FusionStore; + AppDomainSetup adSetup = ad.FusionStore; adSetup.InternalSetApplicationTrust(sandboxName); @@ -1264,10 +1162,10 @@ namespace System generateDefaultEvidence, parentSecurityDescriptor, true); - + // can load user code now - if(initializerInfo!=null) - adSetup.AppDomainInitializer=initializerInfo.Unwrap(); + if (initializerInfo != null) + adSetup.AppDomainInitializer = initializerInfo.Unwrap(); RunInitializer(adSetup); return null; @@ -1299,7 +1197,7 @@ namespace System continue; if (PathInternal.IsPartiallyQualified(path)) - throw new ArgumentException(Environment.GetResourceString("Argument_AbsolutePathRequired")); + throw new ArgumentException(SR.Argument_AbsolutePathRequired); string appPath = NormalizePath(path, fullCheck: true); sb.Append(appPath); @@ -1329,7 +1227,7 @@ namespace System // (eg. one thread doing a com call and another doing attach for IJW) lock (this) { - if(_FusionStore == null) + if (_FusionStore == null) { AppDomainSetup setup = new AppDomainSetup(); @@ -1349,7 +1247,6 @@ namespace System JitHelpers.GetObjectHandleOnStack(ref stackEvidence), creatorsSecurityDescriptor, publishAppDomain); - } [SuppressUnmanagedCodeSecurity] @@ -1372,8 +1269,9 @@ namespace System public AppDomainSetup SetupInformation { - get { - return new AppDomainSetup(FusionStore,true); + get + { + return new AppDomainSetup(FusionStore, true); } } @@ -1382,7 +1280,7 @@ namespace System [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern String GetOrInternString(String str); - + [SuppressUnmanagedCodeSecurity] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] private static extern void GetGrantSet(AppDomainHandle domain, ObjectHandleOnStack retGrantSet); @@ -1407,14 +1305,14 @@ namespace System public Int32 Id { - get { + get + { return GetId(); } } [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern Int32 GetId(); - } /// <summary> diff --git a/src/mscorlib/src/System/AppDomainAttributes.cs b/src/mscorlib/src/System/AppDomainAttributes.cs index 960f9c1cac..deb43eadf9 100644 --- a/src/mscorlib/src/System/AppDomainAttributes.cs +++ b/src/mscorlib/src/System/AppDomainAttributes.cs @@ -11,19 +11,19 @@ ** =============================================================================*/ -namespace System { - +namespace System +{ [Serializable] - internal enum LoaderOptimization + internal enum LoaderOptimization { - NotSpecified = 0, - SingleDomain = 1, - MultiDomain = 2, - MultiDomainHost = 3, + NotSpecified = 0, + SingleDomain = 1, + MultiDomain = 2, + MultiDomainHost = 3, [Obsolete("This method has been deprecated. Please use Assembly.Load() instead. http://go.microsoft.com/fwlink/?linkid=14202")] - DomainMask = 3, + DomainMask = 3, [Obsolete("This method has been deprecated. Please use Assembly.Load() instead. http://go.microsoft.com/fwlink/?linkid=14202")] - DisallowBindings = 4 + DisallowBindings = 4 } } diff --git a/src/mscorlib/src/System/AppDomainManager.cs b/src/mscorlib/src/System/AppDomainManager.cs index bd2faa0110..830de29c16 100644 --- a/src/mscorlib/src/System/AppDomainManager.cs +++ b/src/mscorlib/src/System/AppDomainManager.cs @@ -8,18 +8,18 @@ // participate in the creation and control the settings of new AppDomains. // +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Security; +using System.Runtime.InteropServices; + namespace System { - using System.Reflection; - using System.Runtime.CompilerServices; - using System.Security; - using System.Runtime.InteropServices; - internal class AppDomainManager : MarshalByRefObject { - public AppDomainManager () {} + public AppDomainManager() { } - public virtual void InitializeNewDomain (AppDomainSetup appDomainInfo) + public virtual void InitializeNewDomain(AppDomainSetup appDomainInfo) { // By default, InitializeNewDomain does nothing. AppDomain.CreateAppDomainManager relies on this fact. } @@ -28,8 +28,10 @@ namespace System private static extern void GetEntryAssembly(ObjectHandleOnStack retAssembly); private Assembly m_entryAssembly = null; - public virtual Assembly EntryAssembly { - get { + public virtual Assembly EntryAssembly + { + get + { // The default AppDomainManager sets the EntryAssembly depending on whether the // AppDomain is a manifest application domain or not. In the first case, we parse // the application manifest to find out the entry point assembly and return that assembly. @@ -46,15 +48,12 @@ namespace System } } - internal static AppDomainManager CurrentAppDomainManager { - get { + internal static AppDomainManager CurrentAppDomainManager + { + get + { return AppDomain.CurrentDomain.DomainManager; } } - - public virtual bool CheckSecuritySettings (SecurityState state) - { - return false; - } } } diff --git a/src/mscorlib/src/System/AppDomainSetup.cs b/src/mscorlib/src/System/AppDomainSetup.cs index 0d19ad237f..142b8a05f7 100644 --- a/src/mscorlib/src/System/AppDomainSetup.cs +++ b/src/mscorlib/src/System/AppDomainSetup.cs @@ -4,15 +4,12 @@ /*============================================================================= ** -** Class: AppDomainSetup ** ** Purpose: Defines the settings that the loader uses to find assemblies in an ** AppDomain ** -** Date: Dec 22, 2000 ** =============================================================================*/ - namespace System { using System.Text; @@ -34,49 +31,29 @@ namespace System // If you add a new value, add the corresponding property // to AppDomain.GetData() and SetData()'s switch statements, // as well as fusionsetup.h. - ApplicationBaseValue = 0, // LOADER_APPLICATION_BASE - ConfigurationFileValue = 1, // LOADER_CONFIGURATION_BASE - DynamicBaseValue = 2, // LOADER_DYNAMIC_BASE - DevPathValue = 3, // LOADER_DEVPATH - ApplicationNameValue = 4, // LOADER_APPLICATION_NAME - PrivateBinPathValue = 5, // LOADER_PRIVATE_PATH - PrivateBinPathProbeValue = 6, // LOADER_PRIVATE_BIN_PATH_PROBE - ShadowCopyDirectoriesValue = 7, // LOADER_SHADOW_COPY_DIRECTORIES - ShadowCopyFilesValue = 8, // LOADER_SHADOW_COPY_FILES - CachePathValue = 9, // LOADER_CACHE_PATH - LicenseFileValue = 10, // LOADER_LICENSE_FILE - DisallowPublisherPolicyValue = 11, // LOADER_DISALLOW_PUBLISHER_POLICY - DisallowCodeDownloadValue = 12, // LOADER_DISALLOW_CODE_DOWNLOAD + ApplicationBaseValue = 0, // LOADER_APPLICATION_BASE + ConfigurationFileValue = 1, // LOADER_CONFIGURATION_BASE + DynamicBaseValue = 2, // LOADER_DYNAMIC_BASE + DevPathValue = 3, // LOADER_DEVPATH + ApplicationNameValue = 4, // LOADER_APPLICATION_NAME + PrivateBinPathValue = 5, // LOADER_PRIVATE_PATH + PrivateBinPathProbeValue = 6, // LOADER_PRIVATE_BIN_PATH_PROBE + ShadowCopyDirectoriesValue = 7, // LOADER_SHADOW_COPY_DIRECTORIES + ShadowCopyFilesValue = 8, // LOADER_SHADOW_COPY_FILES + CachePathValue = 9, // LOADER_CACHE_PATH + LicenseFileValue = 10, // LOADER_LICENSE_FILE + DisallowPublisherPolicyValue = 11, // LOADER_DISALLOW_PUBLISHER_POLICY + DisallowCodeDownloadValue = 12, // LOADER_DISALLOW_CODE_DOWNLOAD DisallowBindingRedirectsValue = 13, // LOADER_DISALLOW_BINDING_REDIRECTS - DisallowAppBaseProbingValue = 14, // LOADER_DISALLOW_APPBASE_PROBING - ConfigurationBytesValue = 15, // LOADER_CONFIGURATION_BYTES - LoaderMaximum = 18 // LOADER_MAXIMUM + DisallowAppBaseProbingValue = 14, // LOADER_DISALLOW_APPBASE_PROBING + ConfigurationBytesValue = 15, // LOADER_CONFIGURATION_BYTES + LoaderMaximum = 18 // LOADER_MAXIMUM } - + // Constants from fusionsetup.h. private const string LOADER_OPTIMIZATION = "LOADER_OPTIMIZATION"; - private const string CONFIGURATION_EXTENSION = ".config"; - private const string APPENV_RELATIVEPATH = "RELPATH"; - private const string MACHINE_CONFIGURATION_FILE = "config\\machine.config"; - private const string ACTAG_HOST_CONFIG_FILE = "HOST_CONFIG"; - - // Constants from fusionpriv.h - private const string ACTAG_APP_CONFIG_FILE = "APP_CONFIG_FILE"; - private const string ACTAG_MACHINE_CONFIG = "MACHINE_CONFIG"; + private const string ACTAG_APP_BASE_URL = "APPBASE"; - private const string ACTAG_APP_NAME = "APP_NAME"; - private const string ACTAG_BINPATH_PROBE_ONLY = "BINPATH_PROBE_ONLY"; - private const string ACTAG_APP_CACHE_BASE = "CACHE_BASE"; - private const string ACTAG_DEV_PATH = "DEV_PATH"; - private const string ACTAG_APP_DYNAMIC_BASE = "DYNAMIC_BASE"; - private const string ACTAG_FORCE_CACHE_INSTALL = "FORCE_CACHE_INSTALL"; - private const string ACTAG_APP_PRIVATE_BINPATH = "PRIVATE_BINPATH"; - private const string ACTAG_APP_SHADOW_COPY_DIRS = "SHADOW_COPY_DIRS"; - private const string ACTAG_DISALLOW_APPLYPUBLISHERPOLICY = "DISALLOW_APP"; - private const string ACTAG_CODE_DOWNLOAD_DISABLED = "CODE_DOWNLOAD_DISABLED"; - private const string ACTAG_DISALLOW_APP_BINDING_REDIRECTS = "DISALLOW_APP_REDIRECTS"; - private const string ACTAG_DISALLOW_APP_BASE_PROBING = "DISALLOW_APP_BASE_PROBING"; - private const string ACTAG_APP_CONFIG_BLOB = "APP_CONFIG_BLOB"; // This class has an unmanaged representation so be aware you will need to make edits in vm\object.h if you change the order // of these fields or add new ones. @@ -87,7 +64,7 @@ namespace System private String _AppBase; // for compat with v1.1 #pragma warning restore 169 [OptionalField(VersionAdded = 2)] - private AppDomainInitializer _AppDomainInitializer; + private AppDomainInitializer _AppDomainInitializer; [OptionalField(VersionAdded = 2)] private string[] _AppDomainInitializerArguments; @@ -125,7 +102,8 @@ namespace System internal AppDomainSetup(AppDomainSetup copy, bool copyDomainBoundData) { string[] mine = Value; - if(copy != null) { + if (copy != null) + { string[] other = copy.Value; int mineSize = _Entries.Length; int otherSize = other.Length; @@ -152,7 +130,7 @@ namespace System else _AppDomainInitializer = null; - _ConfigurationBytes = copy.GetConfigurationBytes(); + _ConfigurationBytes = null; #if FEATURE_COMINTEROP _DisableInterfaceCache = copy._DisableInterfaceCache; #endif // FEATURE_COMINTEROP @@ -171,7 +149,7 @@ namespace System #endif } - else + else _LoaderOptimization = LoaderOptimization.NotSpecified; } @@ -180,39 +158,37 @@ namespace System _LoaderOptimization = LoaderOptimization.NotSpecified; } - internal void SetupDefaults(string imageLocation, bool imageLocationAlreadyNormalized = false) { - char[] sep = {'\\', '/'}; + internal void SetupDefaults(string imageLocation, bool imageLocationAlreadyNormalized = false) + { + char[] sep = { '\\', '/' }; int i = imageLocation.LastIndexOfAny(sep); - if (i == -1) { + if (i == -1) + { ApplicationName = imageLocation; } - else { - ApplicationName = imageLocation.Substring(i+1); - string appBase = imageLocation.Substring(0, i+1); + else + { + ApplicationName = imageLocation.Substring(i + 1); + string appBase = imageLocation.Substring(0, i + 1); if (imageLocationAlreadyNormalized) - Value[(int) LoaderInformation.ApplicationBaseValue] = appBase; - else + Value[(int)LoaderInformation.ApplicationBaseValue] = appBase; + else ApplicationBase = appBase; } - ConfigurationFile = ApplicationName + AppDomainSetup.ConfigurationExtension; } internal string[] Value { - get { - if( _Entries == null) + get + { + if (_Entries == null) _Entries = new String[(int)LoaderInformation.LoaderMaximum]; return _Entries; } } - internal String GetUnsecureApplicationBase() - { - return Value[(int) LoaderInformation.ApplicationBaseValue]; - } - public string AppDomainManagerAssembly { get { return _AppDomainManagerAssembly; } @@ -228,233 +204,17 @@ namespace System public String ApplicationBase { [Pure] - get { - return VerifyDir(GetUnsecureApplicationBase(), false); - } - - set { - Value[(int) LoaderInformation.ApplicationBaseValue] = NormalizePath(value, false); - } - } - - private String NormalizePath(String path, bool useAppBase) - { - if(path == null) - return null; - - // If we add very long file name support ("\\?\") to the Path class then this is unnecesary, - // but we do not plan on doing this for now. - - // Long path checks can be quirked, and as loading default quirks too early in the setup of an AppDomain is risky - // we'll avoid checking path lengths- we'll still fail at MAX_PATH later if we're !useAppBase when we call Path's - // NormalizePath. - if (!useAppBase) - path = Security.Util.URLString.PreProcessForExtendedPathRemoval( - checkPathLength: false, - url: path, - isFileUrl: false); - - - int len = path.Length; - if (len == 0) - return null; - -#if !PLATFORM_UNIX - bool UNCpath = false; -#endif // !PLATFORM_UNIX - - if ((len > 7) && - (String.Compare( path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0)) { - int trim; - - if (path[6] == '\\') { - if ((path[7] == '\\') || (path[7] == '/')) { - - // Don't allow "file:\\\\", because we can't tell the difference - // with it for "file:\\" + "\\server" and "file:\\\" + "\localpath" - if ( (len > 8) && - ((path[8] == '\\') || (path[8] == '/')) ) - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPathChars")); - - // file:\\\ means local path - else -#if !PLATFORM_UNIX - trim = 8; -#else - // For Unix platform, trim the first 7 charcaters only. - // Trimming the first 8 characters will cause - // the root path separator to be trimmed away, - // and the absolute local path becomes a relative local path. - trim = 7; -#endif // !PLATFORM_UNIX - } - - // file:\\ means remote server - else { - trim = 5; -#if !PLATFORM_UNIX - UNCpath = true; -#endif // !PLATFORM_UNIX - } - } - - // local path - else if (path[7] == '/') -#if !PLATFORM_UNIX - trim = 8; -#else - // For Unix platform, trim the first 7 characters only. - // Trimming the first 8 characters will cause - // the root path separator to be trimmed away, - // and the absolute local path becomes a relative local path. - trim = 7; -#endif // !PLATFORM_UNIX - - // remote - else { - // file://\\remote - if ( (len > 8) && (path[7] == '\\') && (path[8] == '\\') ) - trim = 7; - else { // file://remote - trim = 5; -#if !PLATFORM_UNIX - // Create valid UNC path by changing - // all occurences of '/' to '\\' in path - System.Text.StringBuilder winPathBuilder = - new System.Text.StringBuilder(len); - for (int i = 0; i < len; i++) { - char c = path[i]; - if (c == '/') - winPathBuilder.Append('\\'); - else - winPathBuilder.Append(c); - } - path = winPathBuilder.ToString(); -#endif // !PLATFORM_UNIX - } -#if !PLATFORM_UNIX - UNCpath = true; -#endif // !PLATFORM_UNIX - } - - path = path.Substring(trim); - len -= trim; - } - -#if !PLATFORM_UNIX - bool localPath; - - // UNC - if (UNCpath || - ( (len > 1) && - ( (path[0] == '/') || (path[0] == '\\') ) && - ( (path[1] == '/') || (path[1] == '\\') ) )) - localPath = false; - - else { - int colon = path.IndexOf(':') + 1; - - // protocol other than file: - if ((colon != 0) && - (len > colon+1) && - ( (path[colon] == '/') || (path[colon] == '\\') ) && - ( (path[colon+1] == '/') || (path[colon+1] == '\\') )) - localPath = false; - - else - localPath = true; - } - - if (localPath) -#else - if ( (len == 1) || - ( (path[0] != '/') && (path[0] != '\\') ) ) -#endif // !PLATFORM_UNIX + get { - - if (useAppBase && - ( (len == 1) || (path[1] != ':') )) { - String appBase = Value[(int) LoaderInformation.ApplicationBaseValue]; - - if ((appBase == null) || (appBase.Length == 0)) - throw new MemberAccessException(Environment.GetResourceString("AppDomain_AppBaseNotSet")); - - StringBuilder result = StringBuilderCache.Acquire(); - - bool slash = false; - if ((path[0] == '/') || (path[0] == '\\')) { - string pathRoot = AppDomain.NormalizePath(appBase, fullCheck: false); - pathRoot = pathRoot.Substring(0, IO.PathInternal.GetRootLength(pathRoot)); - - if (pathRoot.Length == 0) { // URL - int index = appBase.IndexOf(":/", StringComparison.Ordinal); - if (index == -1) - index = appBase.IndexOf(":\\", StringComparison.Ordinal); - - // Get past last slashes of "url:http://" - int urlLen = appBase.Length; - for (index += 1; - (index < urlLen) && ((appBase[index] == '/') || (appBase[index] == '\\')); - index++); - - // Now find the next slash to get domain name - for(; (index < urlLen) && (appBase[index] != '/') && (appBase[index] != '\\'); - index++); - - pathRoot = appBase.Substring(0, index); - } - - result.Append(pathRoot); - slash = true; - } - else - result.Append(appBase); - - // Make sure there's a slash separator (and only one) - int aLen = result.Length - 1; - if ((result[aLen] != '/') && - (result[aLen] != '\\')) { - if (!slash) { -#if !PLATFORM_UNIX - if (appBase.IndexOf(":/", StringComparison.Ordinal) == -1) - result.Append('\\'); - else -#endif // !PLATFORM_UNIX - result.Append('/'); - } - } - else if (slash) - result.Remove(aLen, 1); - - result.Append(path); - path = StringBuilderCache.GetStringAndRelease(result); - } - else - path = AppDomain.NormalizePath(path, fullCheck: true); + return Value[(int)LoaderInformation.ApplicationBaseValue]; } - return path; - } - - public String ConfigurationFile - { - get { - return VerifyDir(Value[(int) LoaderInformation.ConfigurationFileValue], true); - } - - set { - Value[(int) LoaderInformation.ConfigurationFileValue] = value; + set + { + Value[(int)LoaderInformation.ApplicationBaseValue] = (value == null || value.Length == 0)?null:Path.GetFullPath(value); } } - - public byte[] GetConfigurationBytes() - { - if (_ConfigurationBytes == null) - return null; - - return (byte[]) _ConfigurationBytes.Clone(); - } - + // only needed by AppDomain.Setup(). Not really needed by users. internal Dictionary<string, object> GetCompatibilityFlags() { @@ -469,10 +229,11 @@ namespace System if (switches != null) { _CompatFlags = new Dictionary<string, object>(); - foreach (String str in switches) + foreach (String str in switches) { #if FEATURE_RANDOMIZED_STRING_HASHING - if(StringComparer.OrdinalIgnoreCase.Equals("UseRandomizedStringHashAlgorithm", str)) { + if (StringComparer.OrdinalIgnoreCase.Equals("UseRandomizedStringHashAlgorithm", str)) + { _UseRandomizedStringHashing = true; } #endif @@ -483,62 +244,55 @@ namespace System { _CompatFlags = null; } - } // A target Framework moniker, in a format parsible by the FrameworkName class. - public String TargetFrameworkName { - get { + public String TargetFrameworkName + { + get + { return _TargetFrameworkName; } - set { + set + { _TargetFrameworkName = value; } } - private String VerifyDir(String dir, bool normalize) - { - if (dir != null) { - if (dir.Length == 0) - dir = null; - else { - if (normalize) - dir = NormalizePath(dir, true); - } - } - - return dir; - } - public String ApplicationName { - get { - return Value[(int) LoaderInformation.ApplicationNameValue]; + get + { + return Value[(int)LoaderInformation.ApplicationNameValue]; } - set { - Value[(int) LoaderInformation.ApplicationNameValue] = value; + set + { + Value[(int)LoaderInformation.ApplicationNameValue] = value; } } - [XmlIgnoreMember] public AppDomainInitializer AppDomainInitializer { - get { + get + { return _AppDomainInitializer; } - set { + set + { _AppDomainInitializer = value; } } public string[] AppDomainInitializerArguments { - get { + get + { return _AppDomainInitializerArguments; } - set { + set + { _AppDomainInitializerArguments = value; } } @@ -555,7 +309,6 @@ namespace System _ApplicationTrust = permissionSetName; } - [XmlIgnoreMember] internal ApplicationTrust ApplicationTrust { get @@ -566,36 +319,32 @@ namespace System public LoaderOptimization LoaderOptimization { - get { + get + { return _LoaderOptimization; } - set { + set + { _LoaderOptimization = value; } } internal static string LoaderOptimizationKey { - get { + get + { return LOADER_OPTIMIZATION; } } - internal static string ConfigurationExtension - { - get { - return CONFIGURATION_EXTENSION; - } - } - static internal int Locate(String s) { - if(String.IsNullOrEmpty(s)) + if (String.IsNullOrEmpty(s)) return -1; - Debug.Assert('A' == ACTAG_APP_BASE_URL[0] , "Assumption violated"); - if (s[0]=='A' && s == ACTAG_APP_BASE_URL) + Debug.Assert('A' == ACTAG_APP_BASE_URL[0], "Assumption violated"); + if (s[0] == 'A' && s == ACTAG_APP_BASE_URL) return (int)LoaderInformation.ApplicationBaseValue; return -1; diff --git a/src/mscorlib/src/System/AppDomainUnloadedException.cs b/src/mscorlib/src/System/AppDomainUnloadedException.cs index 30bee7c7de..52cbb980af 100644 --- a/src/mscorlib/src/System/AppDomainUnloadedException.cs +++ b/src/mscorlib/src/System/AppDomainUnloadedException.cs @@ -11,21 +11,25 @@ ** =============================================================================*/ -namespace System { - using System.Runtime.Serialization; +using System.Runtime.Serialization; +namespace System +{ [Serializable] - internal class AppDomainUnloadedException : SystemException { - public AppDomainUnloadedException() - : base(Environment.GetResourceString("Arg_AppDomainUnloadedException")) { - SetErrorCode(__HResults.COR_E_APPDOMAINUNLOADED); + internal class AppDomainUnloadedException : SystemException + { + public AppDomainUnloadedException() + : base(SR.Arg_AppDomainUnloadedException) + { + HResult = __HResults.COR_E_APPDOMAINUNLOADED; } // //This constructor is required for serialization. // - protected AppDomainUnloadedException(SerializationInfo info, StreamingContext context) : base(info, context) { + protected AppDomainUnloadedException(SerializationInfo info, StreamingContext context) : base(info, context) + { } } } diff --git a/src/mscorlib/src/System/ApplicationException.cs b/src/mscorlib/src/System/ApplicationException.cs deleted file mode 100644 index 900feb57f9..0000000000 --- a/src/mscorlib/src/System/ApplicationException.cs +++ /dev/null @@ -1,56 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -/*============================================================================= -** -** -** -** Purpose: The base class for all "less serious" exceptions that must be -** declared or caught. -** -** -=============================================================================*/ - -using System.Runtime.Serialization; - -namespace System -{ - // The ApplicationException is the base class for nonfatal, - // application errors that occur. These exceptions are generated - // (i.e., thrown) by an application, not the Runtime. Applications that need - // to create their own exceptions do so by extending this class. - // ApplicationException extends but adds no new functionality to - // RecoverableException. - // - [Serializable] - public class ApplicationException : Exception - { - // Creates a new ApplicationException with its message string set to - // the empty string, its HRESULT set to COR_E_APPLICATION, - // and its ExceptionInfo reference set to null. - public ApplicationException() - : base(SR.Arg_ApplicationException) - { - HResult = __HResults.COR_E_APPLICATION; - } - - // Creates a new ApplicationException with its message string set to - // message, its HRESULT set to COR_E_APPLICATION, - // and its ExceptionInfo reference set to null. - // - public ApplicationException(String message) - : base(message) - { - HResult = __HResults.COR_E_APPLICATION; - } - - public ApplicationException(String message, Exception innerException) - : base(message, innerException) - { - HResult = __HResults.COR_E_APPLICATION; - } - - protected ApplicationException(SerializationInfo info, StreamingContext context) : base(info, context) { } - } -} diff --git a/src/mscorlib/src/System/ArgIterator.cs b/src/mscorlib/src/System/ArgIterator.cs index 83a60b95e1..584f85fbd3 100644 --- a/src/mscorlib/src/System/ArgIterator.cs +++ b/src/mscorlib/src/System/ArgIterator.cs @@ -2,8 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System { - +namespace System +{ using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; @@ -24,10 +24,10 @@ namespace System { // Note, sigPtrLen is actually a DWORD, but on 64bit systems this structure becomes // 8-byte aligned, which requires us to pad it. - + private IntPtr ArgPtr; // Pointer to remaining args. - private int RemainingArgs; // # of remaining args. - + private int RemainingArgs; // # of remaining args. + #if VARARGS_ENABLED //The JIT doesn't support Varargs calling convention. [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern ArgIterator(IntPtr arglist); @@ -131,55 +131,55 @@ namespace System { // Inherited from object public override bool Equals(Object o) { - throw new NotSupportedException(Environment.GetResourceString("NotSupported_NYI")); + throw new NotSupportedException(SR.NotSupported_NYI); } #else public ArgIterator(RuntimeArgumentHandle arglist) { - throw new PlatformNotSupportedException(); //The JIT requires work to enable ArgIterator see: https://github.com/dotnet/coreclr/issues/9204. + throw new PlatformNotSupportedException(SR.PlatformNotSupported_ArgIterator); // https://github.com/dotnet/coreclr/issues/9204 } [CLSCompliant(false)] public unsafe ArgIterator(RuntimeArgumentHandle arglist, void* ptr) { - throw new PlatformNotSupportedException(); //The JIT requires work to enable ArgIterator see: https://github.com/dotnet/coreclr/issues/9204. + throw new PlatformNotSupportedException(SR.PlatformNotSupported_ArgIterator); // https://github.com/dotnet/coreclr/issues/9204 } - public void End() - { - throw new PlatformNotSupportedException(); //The JIT requires work to enable ArgIterator see: https://github.com/dotnet/coreclr/issues/9204. + public void End() + { + throw new PlatformNotSupportedException(SR.PlatformNotSupported_ArgIterator); // https://github.com/dotnet/coreclr/issues/9204 } - public override bool Equals(Object o) - { - throw new PlatformNotSupportedException(); //The JIT requires work to enable ArgIterator see: https://github.com/dotnet/coreclr/issues/9204. + public override bool Equals(Object o) + { + throw new PlatformNotSupportedException(SR.PlatformNotSupported_ArgIterator); // https://github.com/dotnet/coreclr/issues/9204 } public override int GetHashCode() - { - throw new PlatformNotSupportedException(); //The JIT requires work to enable ArgIterator see: https://github.com/dotnet/coreclr/issues/9204. + { + throw new PlatformNotSupportedException(SR.PlatformNotSupported_ArgIterator); // https://github.com/dotnet/coreclr/issues/9204 } [System.CLSCompliantAttribute(false)] public System.TypedReference GetNextArg() { - throw new PlatformNotSupportedException(); //The JIT requires work to enable ArgIterator see: https://github.com/dotnet/coreclr/issues/9204. + throw new PlatformNotSupportedException(SR.PlatformNotSupported_ArgIterator); // https://github.com/dotnet/coreclr/issues/9204 } [System.CLSCompliantAttribute(false)] public System.TypedReference GetNextArg(System.RuntimeTypeHandle rth) { - throw new PlatformNotSupportedException(); //The JIT requires work to enable ArgIterator see: https://github.com/dotnet/coreclr/issues/9204. + throw new PlatformNotSupportedException(SR.PlatformNotSupported_ArgIterator); // https://github.com/dotnet/coreclr/issues/9204 } public unsafe System.RuntimeTypeHandle GetNextArgType() { - throw new PlatformNotSupportedException(); //The JIT requires work to enable ArgIterator see: https://github.com/dotnet/coreclr/issues/9204. + throw new PlatformNotSupportedException(SR.PlatformNotSupported_ArgIterator); // https://github.com/dotnet/coreclr/issues/9204 } public int GetRemainingCount() - { - throw new PlatformNotSupportedException(); //The JIT requires work to enable ArgIterator see: https://github.com/dotnet/coreclr/issues/9204. + { + throw new PlatformNotSupportedException(SR.PlatformNotSupported_ArgIterator); // https://github.com/dotnet/coreclr/issues/9204 } #endif //VARARGS_ENABLED } diff --git a/src/mscorlib/src/System/ArgumentException.cs b/src/mscorlib/src/System/ArgumentException.cs deleted file mode 100644 index fe054a9aa0..0000000000 --- a/src/mscorlib/src/System/ArgumentException.cs +++ /dev/null @@ -1,97 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -/*============================================================================= -** -** -** -** Purpose: Exception class for invalid arguments to a method. -** -** -=============================================================================*/ - -using System.Globalization; -using System.Runtime.Serialization; - -namespace System -{ - // The ArgumentException is thrown when an argument does not meet - // the contract of the method. Ideally it should give a meaningful error - // message describing what was wrong and which parameter is incorrect. - // - [Serializable] - public class ArgumentException : SystemException, ISerializable - { - private String _paramName; - - // Creates a new ArgumentException with its message - // string set to the empty string. - public ArgumentException() - : base(SR.Arg_ArgumentException) - { - HResult = __HResults.COR_E_ARGUMENT; - } - - // Creates a new ArgumentException with its message - // string set to message. - // - public ArgumentException(String message) - : base(message) - { - HResult = __HResults.COR_E_ARGUMENT; - } - - public ArgumentException(String message, Exception innerException) - : base(message, innerException) - { - HResult = __HResults.COR_E_ARGUMENT; - } - - public ArgumentException(String message, String paramName, Exception innerException) - : base(message, innerException) - { - _paramName = paramName; - HResult = __HResults.COR_E_ARGUMENT; - } - - public ArgumentException(String message, String paramName) - : base(message) - { - _paramName = paramName; - HResult = __HResults.COR_E_ARGUMENT; - } - - protected ArgumentException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - _paramName = info.GetString("ParamName"); - } - - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - base.GetObjectData(info, context); - info.AddValue("ParamName", _paramName, typeof(String)); - } - - public override String Message - { - get - { - String s = base.Message; - if (!String.IsNullOrEmpty(_paramName)) - { - String resourceString = SR.Format(SR.Arg_ParamName_Name, _paramName); - return s + Environment.NewLine + resourceString; - } - else - return s; - } - } - - public virtual String ParamName - { - get { return _paramName; } - } - } -} diff --git a/src/mscorlib/src/System/ArgumentNullException.cs b/src/mscorlib/src/System/ArgumentNullException.cs deleted file mode 100644 index 3a86223ccf..0000000000 --- a/src/mscorlib/src/System/ArgumentNullException.cs +++ /dev/null @@ -1,53 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -/*============================================================================= -** -** -** -** Purpose: Exception class for null arguments to a method. -** -** -=============================================================================*/ - -using System.Runtime.Serialization; - -namespace System -{ - // The ArgumentException is thrown when an argument - // is null when it shouldn't be. - // - [Serializable] - public class ArgumentNullException : ArgumentException - { - // Creates a new ArgumentNullException with its message - // string set to a default message explaining an argument was null. - public ArgumentNullException() - : base(SR.ArgumentNull_Generic) - { - // Use E_POINTER - COM used that for null pointers. Description is "invalid pointer" - HResult = __HResults.E_POINTER; - } - - public ArgumentNullException(String paramName) - : base(SR.ArgumentNull_Generic, paramName) - { - HResult = __HResults.E_POINTER; - } - - public ArgumentNullException(String message, Exception innerException) - : base(message, innerException) - { - HResult = __HResults.E_POINTER; - } - - public ArgumentNullException(String paramName, String message) - : base(message, paramName) - { - HResult = __HResults.E_POINTER; - } - - protected ArgumentNullException(SerializationInfo info, StreamingContext context) : base(info, context) { } - } -} diff --git a/src/mscorlib/src/System/ArgumentOutOfRangeException.cs b/src/mscorlib/src/System/ArgumentOutOfRangeException.cs index 59a8434089..90837810d1 100644 --- a/src/mscorlib/src/System/ArgumentOutOfRangeException.cs +++ b/src/mscorlib/src/System/ArgumentOutOfRangeException.cs @@ -11,92 +11,107 @@ ** =============================================================================*/ -namespace System { - using System; - using System.Runtime.Remoting; - using System.Runtime.Serialization; - using System.Globalization; - using System.Diagnostics.Contracts; - +using System; +using System.Runtime.Remoting; +using System.Runtime.Serialization; +using System.Globalization; +using System.Diagnostics.Contracts; + +namespace System +{ // The ArgumentOutOfRangeException is thrown when an argument // is outside the legal range for that argument. [Serializable] - public class ArgumentOutOfRangeException : ArgumentException, ISerializable { - + public class ArgumentOutOfRangeException : ArgumentException, ISerializable + { private static volatile String _rangeMessage; private Object m_actualValue; - private static String RangeMessage { - get { + private static String RangeMessage + { + get + { if (_rangeMessage == null) - _rangeMessage = Environment.GetResourceString("Arg_ArgumentOutOfRangeException"); + _rangeMessage = SR.Arg_ArgumentOutOfRangeException; return _rangeMessage; } } // Creates a new ArgumentOutOfRangeException with its message // string set to a default message explaining an argument was out of range. - public ArgumentOutOfRangeException() - : base(RangeMessage) { - SetErrorCode(__HResults.COR_E_ARGUMENTOUTOFRANGE); + public ArgumentOutOfRangeException() + : base(RangeMessage) + { + HResult = __HResults.COR_E_ARGUMENTOUTOFRANGE; } - - public ArgumentOutOfRangeException(String paramName) - : base(RangeMessage, paramName) { - SetErrorCode(__HResults.COR_E_ARGUMENTOUTOFRANGE); + + public ArgumentOutOfRangeException(String paramName) + : base(RangeMessage, paramName) + { + HResult = __HResults.COR_E_ARGUMENTOUTOFRANGE; } - - public ArgumentOutOfRangeException(String paramName, String message) - : base(message, paramName) { - SetErrorCode(__HResults.COR_E_ARGUMENTOUTOFRANGE); + + public ArgumentOutOfRangeException(String paramName, String message) + : base(message, paramName) + { + HResult = __HResults.COR_E_ARGUMENTOUTOFRANGE; } - public ArgumentOutOfRangeException(String message, Exception innerException) - : base(message, innerException) { - SetErrorCode(__HResults.COR_E_ARGUMENTOUTOFRANGE); + public ArgumentOutOfRangeException(String message, Exception innerException) + : base(message, innerException) + { + HResult = __HResults.COR_E_ARGUMENTOUTOFRANGE; } - + // We will not use this in the classlibs, but we'll provide it for // anyone that's really interested so they don't have to stick a bunch // of printf's in their code. - public ArgumentOutOfRangeException(String paramName, Object actualValue, String message) - : base(message, paramName) { + public ArgumentOutOfRangeException(String paramName, Object actualValue, String message) + : base(message, paramName) + { m_actualValue = actualValue; - SetErrorCode(__HResults.COR_E_ARGUMENTOUTOFRANGE); + HResult = __HResults.COR_E_ARGUMENTOUTOFRANGE; } - - public override String Message { - get { + + public override String Message + { + get + { String s = base.Message; - if (m_actualValue != null) { - String valueMessage = Environment.GetResourceString("ArgumentOutOfRange_ActualValue", m_actualValue.ToString()); + if (m_actualValue != null) + { + String valueMessage = SR.Format(SR.ArgumentOutOfRange_ActualValue, m_actualValue.ToString()); if (s == null) return valueMessage; - return s + Environment.NewLine + valueMessage; + return s + Environment.NewLine + valueMessage; } return s; } } - + // Gets the value of the argument that caused the exception. // Note - we don't set this anywhere in the class libraries in // version 1, but it might come in handy for other developers who // want to avoid sticking printf's in their code. - public virtual Object ActualValue { + public virtual Object ActualValue + { get { return m_actualValue; } } - - public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info==null) { + + public override void GetObjectData(SerializationInfo info, StreamingContext context) + { + if (info == null) + { throw new ArgumentNullException(nameof(info)); } Contract.EndContractBlock(); base.GetObjectData(info, context); info.AddValue("ActualValue", m_actualValue, typeof(Object)); } - - protected ArgumentOutOfRangeException(SerializationInfo info, StreamingContext context) : base(info, context) { + + protected ArgumentOutOfRangeException(SerializationInfo info, StreamingContext context) : base(info, context) + { m_actualValue = info.GetValue("ActualValue", typeof(Object)); } } diff --git a/src/mscorlib/src/System/ArithmeticException.cs b/src/mscorlib/src/System/ArithmeticException.cs deleted file mode 100644 index 081ba454f5..0000000000 --- a/src/mscorlib/src/System/ArithmeticException.cs +++ /dev/null @@ -1,51 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -/*============================================================================= -** -** -** -** Purpose: Exception class for bad arithmetic conditions! -** -** -=============================================================================*/ - -using System.Runtime.Serialization; - -namespace System -{ - // The ArithmeticException is thrown when overflow or underflow - // occurs. - // - [Serializable] - public class ArithmeticException : SystemException - { - // Creates a new ArithmeticException with its message string set to - // the empty string, its HRESULT set to COR_E_ARITHMETIC, - // and its ExceptionInfo reference set to null. - public ArithmeticException() - : base(SR.Arg_ArithmeticException) - { - HResult = __HResults.COR_E_ARITHMETIC; - } - - // Creates a new ArithmeticException with its message string set to - // message, its HRESULT set to COR_E_ARITHMETIC, - // and its ExceptionInfo reference set to null. - // - public ArithmeticException(String message) - : base(message) - { - HResult = __HResults.COR_E_ARITHMETIC; - } - - public ArithmeticException(String message, Exception innerException) - : base(message, innerException) - { - HResult = __HResults.COR_E_ARITHMETIC; - } - - protected ArithmeticException(SerializationInfo info, StreamingContext context) : base(info, context) { } - } -} diff --git a/src/mscorlib/src/System/Array.cs b/src/mscorlib/src/System/Array.cs index 23989f30fb..05c4804cc5 100644 --- a/src/mscorlib/src/System/Array.cs +++ b/src/mscorlib/src/System/Array.cs @@ -8,32 +8,35 @@ ** Purpose: Base class which can be used to access any array ** ===========================================================*/ -namespace System { - - using System; - using System.Collections; - using System.Collections.Generic; - using System.Collections.ObjectModel; - using System.Runtime.InteropServices; - using System.Runtime.CompilerServices; - using System.Runtime.ConstrainedExecution; - using System.Runtime.Versioning; - using System.Security; - using System.Diagnostics; - using System.Diagnostics.Contracts; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.InteropServices; +using System.Runtime.CompilerServices; +using System.Runtime.ConstrainedExecution; +using System.Runtime.Versioning; +using System.Security; +using System.Diagnostics; +using System.Diagnostics.Contracts; + +namespace System +{ // Note that we make a T[] (single-dimensional w/ zero as the lower bound) implement both // IList<U> and IReadOnlyList<U>, where T : U dynamically. See the SZArrayHelper class for details. [Serializable] - public abstract class Array : ICloneable, IList, IStructuralComparable, IStructuralEquatable + public abstract class Array : ICloneable, IList, IStructuralComparable, IStructuralEquatable { // This ctor exists solely to prevent C# from generating a protected .ctor that violates the surface area. I really want this to be a // "protected-and-internal" rather than "internal" but C# has no keyword for the former. - internal Array() {} + internal Array() { } - public static ReadOnlyCollection<T> AsReadOnly<T>(T[] array) { - if (array == null) { - ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); + public static ReadOnlyCollection<T> AsReadOnly<T>(T[] array) + { + if (array == null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } Contract.Ensures(Contract.Result<ReadOnlyCollection<T>>() != null); @@ -41,22 +44,25 @@ namespace System { return new ReadOnlyCollection<T>(array); } - public static void Resize<T>(ref T[] array, int newSize) { + public static void Resize<T>(ref T[] array, int newSize) + { if (newSize < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.newSize, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); Contract.Ensures(Contract.ValueAtReturn(out array) != null); Contract.Ensures(Contract.ValueAtReturn(out array).Length == newSize); Contract.EndContractBlock(); - T[] larray = array; - if (larray == null) { + T[] larray = array; + if (larray == null) + { array = new T[newSize]; return; } - - if (larray.Length != newSize) { + + if (larray.Length != newSize) + { T[] newArray = new T[newSize]; - Array.Copy(larray, 0, newArray, 0, larray.Length > newSize? newSize : larray.Length); + Array.Copy(larray, 0, newArray, 0, larray.Length > newSize ? newSize : larray.Length); array = newArray; } } @@ -76,9 +82,9 @@ namespace System { RuntimeType t = elementType.UnderlyingSystemType as RuntimeType; if (t == null) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_MustBeType, ExceptionArgument.elementType); - return InternalCreate((void*)t.TypeHandle.Value,1,&length,null); + return InternalCreate((void*)t.TypeHandle.Value, 1, &length, null); } - + public unsafe static Array CreateInstance(Type elementType, int length1, int length2) { if ((object)elementType == null) @@ -98,9 +104,9 @@ namespace System { int* pLengths = stackalloc int[2]; pLengths[0] = length1; pLengths[1] = length2; - return InternalCreate((void*)t.TypeHandle.Value,2,pLengths,null); + return InternalCreate((void*)t.TypeHandle.Value, 2, pLengths, null); } - + public unsafe static Array CreateInstance(Type elementType, int length1, int length2, int length3) { if ((object)elementType == null) @@ -124,9 +130,9 @@ namespace System { pLengths[0] = length1; pLengths[1] = length2; pLengths[2] = length3; - return InternalCreate((void*)t.TypeHandle.Value,3,pLengths,null); + return InternalCreate((void*)t.TypeHandle.Value, 3, pLengths, null); } - + public unsafe static Array CreateInstance(Type elementType, params int[] lengths) { if ((object)elementType == null) @@ -152,12 +158,13 @@ namespace System { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.lengths, i, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); fixed (int* pLengths = &lengths[0]) - return InternalCreate((void*)t.TypeHandle.Value,lengths.Length,pLengths,null); + return InternalCreate((void*)t.TypeHandle.Value, lengths.Length, pLengths, null); } public static Array CreateInstance(Type elementType, params long[] lengths) { - if( lengths == null) { + if (lengths == null) + { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.lengths); } if (lengths.Length == 0) @@ -165,22 +172,22 @@ namespace System { Contract.Ensures(Contract.Result<Array>() != null); Contract.Ensures(Contract.Result<Array>().Rank == lengths.Length); Contract.EndContractBlock(); - + int[] intLengths = new int[lengths.Length]; - for (int i = 0; i < lengths.Length; ++i) + for (int i = 0; i < lengths.Length; ++i) { long len = lengths[i]; if (len > Int32.MaxValue || len < Int32.MinValue) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.len, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); - intLengths[i] = (int) len; + intLengths[i] = (int)len; } return Array.CreateInstance(elementType, intLengths); } - - public unsafe static Array CreateInstance(Type elementType, int[] lengths,int[] lowerBounds) + + public unsafe static Array CreateInstance(Type elementType, int[] lengths, int[] lowerBounds) { if (elementType == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.elementType); @@ -204,17 +211,17 @@ namespace System { // a good exception message if they are not; however we check this again inside the execution // engine's low level allocation function after having made a copy of the array to prevent a // malicious caller from mutating the array after this check. - for (int i=0;i<lengths.Length;i++) + for (int i = 0; i < lengths.Length; i++) if (lengths[i] < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.lengths, i, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); fixed (int* pLengths = &lengths[0]) - fixed(int* pLowerBounds = &lowerBounds[0]) - return InternalCreate((void*)t.TypeHandle.Value,lengths.Length,pLengths,pLowerBounds); + fixed (int* pLowerBounds = &lowerBounds[0]) + return InternalCreate((void*)t.TypeHandle.Value, lengths.Length, pLengths, pLowerBounds); } [MethodImplAttribute(MethodImplOptions.InternalCall)] - private unsafe static extern Array InternalCreate(void* elementType,int rank,int *pLengths,int *pLowerBounds); + private unsafe static extern Array InternalCreate(void* elementType, int rank, int* pLengths, int* pLowerBounds); internal static Array UnsafeCreateInstance(Type elementType, int length) { @@ -240,11 +247,11 @@ namespace System { Copy(sourceArray, sourceArray.GetLowerBound(0), destinationArray, destinationArray.GetLowerBound(0), length, false); } - + // Copies length elements from sourceArray, starting at sourceIndex, to // destinationArray, starting at destinationIndex. // - public static void Copy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length) + public static void Copy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length) { Copy(sourceArray, sourceIndex, destinationArray, destinationIndex, length, false); } @@ -271,7 +278,7 @@ namespace System { if (length > Int32.MaxValue || length < Int32.MinValue) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); - Array.Copy(sourceArray, destinationArray, (int) length); + Array.Copy(sourceArray, destinationArray, (int)length); } public static void Copy(Array sourceArray, long sourceIndex, Array destinationArray, long destinationIndex, long length) @@ -283,16 +290,16 @@ namespace System { if (length > Int32.MaxValue || length < Int32.MinValue) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); - Array.Copy(sourceArray, (int) sourceIndex, destinationArray, (int) destinationIndex, (int) length); + Array.Copy(sourceArray, (int)sourceIndex, destinationArray, (int)destinationIndex, (int)length); } - + // Sets length elements in array to 0 (or null for Object arrays), starting // at index. // [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void Clear(Array array, int index, int length); - + // The various Get values... public unsafe Object GetValue(params int[] indices) { @@ -303,11 +310,11 @@ namespace System { Contract.EndContractBlock(); TypedReference elemref = new TypedReference(); - fixed(int* pIndices = &indices[0]) + fixed (int* pIndices = &indices[0]) InternalGetReference(&elemref, indices.Length, pIndices); return TypedReference.InternalToObject(&elemref); } - + public unsafe Object GetValue(int index) { if (Rank != 1) @@ -318,7 +325,7 @@ namespace System { InternalGetReference(&elemref, 1, &index); return TypedReference.InternalToObject(&elemref); } - + public unsafe Object GetValue(int index1, int index2) { if (Rank != 2) @@ -333,7 +340,7 @@ namespace System { InternalGetReference(&elemref, 2, pIndices); return TypedReference.InternalToObject(&elemref); } - + public unsafe Object GetValue(int index1, int index2, int index3) { if (Rank != 3) @@ -356,7 +363,7 @@ namespace System { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); Contract.EndContractBlock(); - return this.GetValue((int) index); + return this.GetValue((int)index); } public Object GetValue(long index1, long index2) @@ -367,7 +374,7 @@ namespace System { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index2, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); Contract.EndContractBlock(); - return this.GetValue((int) index1, (int) index2); + return this.GetValue((int)index1, (int)index2); } public Object GetValue(long index1, long index2, long index3) @@ -379,8 +386,8 @@ namespace System { if (index3 > Int32.MaxValue || index3 < Int32.MinValue) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index3, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); Contract.EndContractBlock(); - - return this.GetValue((int) index1, (int) index2, (int) index3); + + return this.GetValue((int)index1, (int)index2, (int)index3); } public Object GetValue(params long[] indices) @@ -393,19 +400,19 @@ namespace System { int[] intIndices = new int[indices.Length]; - for (int i = 0; i < indices.Length; ++i) + for (int i = 0; i < indices.Length; ++i) { long index = indices[i]; if (index > Int32.MaxValue || index < Int32.MinValue) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); - intIndices[i] = (int) index; + intIndices[i] = (int)index; } return this.GetValue(intIndices); } - - public unsafe void SetValue(Object value,int index) + + public unsafe void SetValue(Object value, int index) { if (Rank != 1) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_Need1DArray); @@ -413,10 +420,10 @@ namespace System { TypedReference elemref = new TypedReference(); InternalGetReference(&elemref, 1, &index); - InternalSetValue(&elemref,value); + InternalSetValue(&elemref, value); } - - public unsafe void SetValue(Object value,int index1, int index2) + + public unsafe void SetValue(Object value, int index1, int index2) { if (Rank != 2) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_Need2DArray); @@ -428,10 +435,10 @@ namespace System { TypedReference elemref = new TypedReference(); InternalGetReference(&elemref, 2, pIndices); - InternalSetValue(&elemref,value); + InternalSetValue(&elemref, value); } - - public unsafe void SetValue(Object value,int index1, int index2, int index3) + + public unsafe void SetValue(Object value, int index1, int index2, int index3) { if (Rank != 3) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_Need3DArray); @@ -444,10 +451,10 @@ namespace System { TypedReference elemref = new TypedReference(); InternalGetReference(&elemref, 3, pIndices); - InternalSetValue(&elemref,value); + InternalSetValue(&elemref, value); } - - public unsafe void SetValue(Object value,params int[] indices) + + public unsafe void SetValue(Object value, params int[] indices) { if (indices == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.indices); @@ -456,9 +463,9 @@ namespace System { Contract.EndContractBlock(); TypedReference elemref = new TypedReference(); - fixed(int* pIndices = &indices[0]) + fixed (int* pIndices = &indices[0]) InternalGetReference(&elemref, indices.Length, pIndices); - InternalSetValue(&elemref,value); + InternalSetValue(&elemref, value); } public void SetValue(Object value, long index) @@ -467,7 +474,7 @@ namespace System { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); Contract.EndContractBlock(); - this.SetValue(value, (int) index); + this.SetValue(value, (int)index); } public void SetValue(Object value, long index1, long index2) @@ -478,7 +485,7 @@ namespace System { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index2, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); Contract.EndContractBlock(); - this.SetValue(value, (int) index1, (int) index2); + this.SetValue(value, (int)index1, (int)index2); } public void SetValue(Object value, long index1, long index2, long index3) @@ -491,7 +498,7 @@ namespace System { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index3, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); Contract.EndContractBlock(); - this.SetValue(value, (int) index1, (int) index2, (int) index3); + this.SetValue(value, (int)index1, (int)index2, (int)index3); } public void SetValue(Object value, params long[] indices) @@ -504,12 +511,12 @@ namespace System { int[] intIndices = new int[indices.Length]; - for (int i = 0; i < indices.Length; ++i) + for (int i = 0; i < indices.Length; ++i) { long index = indices[i]; if (index > Int32.MaxValue || index < Int32.MinValue) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); - intIndices[i] = (int) index; + intIndices[i] = (int)index; } this.SetValue(value, intIndices); @@ -517,23 +524,25 @@ namespace System { [MethodImplAttribute(MethodImplOptions.InternalCall)] // reference to TypedReference is banned, so have to pass result as pointer - private unsafe extern void InternalGetReference(void * elemRef, int rank, int * pIndices); + private unsafe extern void InternalGetReference(void* elemRef, int rank, int* pIndices); // Ideally, we would like to use TypedReference.SetValue instead. Unfortunately, TypedReference.SetValue // always throws not-supported exception [MethodImplAttribute(MethodImplOptions.InternalCall)] - private unsafe extern static void InternalSetValue(void * target, Object value); + private unsafe extern static void InternalSetValue(void* target, Object value); - public extern int Length { + public extern int Length + { [Pure] [MethodImpl(MethodImplOptions.InternalCall)] get; } - private static int GetMedian(int low, int hi) { + 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); - Debug.Assert( hi - low >= 0, "Length overflow!"); + Debug.Assert(hi - low >= 0, "Length overflow!"); return low + ((hi - low) >> 1); } @@ -545,7 +554,8 @@ namespace System { internal const int MaxArrayLength = 0X7FEFFFFF; internal const int MaxByteArrayLength = 0x7FFFFFC7; - public extern long LongLength { + public extern long LongLength + { [Pure] [MethodImpl(MethodImplOptions.InternalCall)] get; @@ -556,12 +566,14 @@ namespace System { public extern int GetLength(int dimension); [Pure] - public long GetLongLength(int dimension) { + public long GetLongLength(int dimension) + { //This method should throw an IndexOufOfRangeException for compat if dimension < 0 or >= Rank return GetLength(dimension); } - public extern int Rank { + public extern int Rank + { [Pure] [MethodImplAttribute(MethodImplOptions.InternalCall)] get; @@ -582,20 +594,21 @@ namespace System { int ICollection.Count { get { return Length; } } - + // Returns an object appropriate for synchronizing access to this // Array. public Object SyncRoot { get { return this; } } - + // Is this Array read-only? public bool IsReadOnly { get { return false; } } - public bool IsFixedSize { + public bool IsFixedSize + { get { return true; } } - + // Is this Array synchronized (i.e., thread-safe)? If you want a synchronized // collection, you can use SyncRoot as an object to synchronize your // collection with. You could also call GetSynchronized() @@ -604,7 +617,8 @@ namespace System { { get { return false; } } - Object IList.this[int index] { + Object IList.this[int index] + { get { return GetValue(index); } set { SetValue(value, index); } } @@ -652,8 +666,10 @@ namespace System { return MemberwiseClone(); } - Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) { - if (other == null) { + Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) + { + if (other == null) + { return 1; } @@ -667,39 +683,45 @@ namespace System { int i = 0; int c = 0; - while (i < o.Length && c == 0) { + while (i < o.Length && c == 0) + { object left = GetValue(i); object right = o.GetValue(i); c = comparer.Compare(left, right); i++; } - + return c; } - Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) { - - if (other == null) { + Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) + { + if (other == null) + { return false; } - if (Object.ReferenceEquals(this, other)) { + if (Object.ReferenceEquals(this, other)) + { return true; } Array o = other as Array; - if (o == null || o.Length != this.Length) { + if (o == null || o.Length != this.Length) + { return false; } int i = 0; - while (i < o.Length) { + while (i < o.Length) + { object left = GetValue(i); object right = o.GetValue(i); - if (!comparer.Equals(left, right)) { + if (!comparer.Equals(left, right)) + { return false; } i++; @@ -709,18 +731,21 @@ namespace System { } // From System.Web.Util.HashCodeCombiner - internal static int CombineHashCodes(int h1, int h2) { + internal static int CombineHashCodes(int h1, int h2) + { return (((h1 << 5) + h1) ^ h2); } - int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { + int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) + { if (comparer == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparer); Contract.EndContractBlock(); int ret = 0; - for (int i = (this.Length >= 8 ? this.Length - 8 : 0); i < this.Length; i++) { + for (int i = (this.Length >= 8 ? this.Length - 8 : 0); i < this.Length; i++) + { ret = CombineHashCodes(ret, comparer.GetHashCode(GetValue(i))); } @@ -741,15 +766,16 @@ namespace System { // is larger than the given search value. // [Pure] - public static int BinarySearch(Array array, Object value) { - if (array==null) + public static int BinarySearch(Array array, Object value) + { + if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); Contract.Ensures((Contract.Result<int>() >= array.GetLowerBound(0) && Contract.Result<int>() <= array.GetUpperBound(0)) || (Contract.Result<int>() < array.GetLowerBound(0) && ~Contract.Result<int>() <= array.GetUpperBound(0) + 1)); Contract.EndContractBlock(); int lb = array.GetLowerBound(0); return BinarySearch(array, lb, array.Length, value, null); } - + // Searches a section of an array for a given element using a binary search // algorithm. Elements of the array are compared to the search value using // the IComparable interface, which must be implemented by all @@ -764,10 +790,11 @@ namespace System { // is larger than the given search value. // [Pure] - public static int BinarySearch(Array array, int index, int length, Object value) { + public static int BinarySearch(Array array, int index, int length, Object value) + { return BinarySearch(array, index, length, value, null); } - + // Searches an array for a given element using a binary search algorithm. // Elements of the array are compared to the search value using the given // IComparer interface. If comparer is null, elements of the @@ -783,14 +810,15 @@ namespace System { // is larger than the given search value. // [Pure] - public static int BinarySearch(Array array, Object value, IComparer comparer) { - if (array==null) + public static int BinarySearch(Array array, Object value, IComparer comparer) + { + if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); Contract.EndContractBlock(); int lb = array.GetLowerBound(0); return BinarySearch(array, lb, array.Length, value, comparer); } - + // Searches a section of an array for a given element using a binary search // algorithm. Elements of the array are compared to the search value using // the given IComparer interface. If comparer is null, @@ -807,8 +835,9 @@ namespace System { // is larger than the given search value. // [Pure] - public static int BinarySearch(Array array, int index, int length, Object value, IComparer comparer) { - if (array==null) + public static int BinarySearch(Array array, int index, int length, Object value, IComparer comparer) + { + if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); Contract.EndContractBlock(); int lb = array.GetLowerBound(0); @@ -820,9 +849,10 @@ namespace System { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); if (array.Rank != 1) ThrowHelper.ThrowRankException(ExceptionResource.Rank_MultiDimNotSupported); - + if (comparer == null) comparer = Comparer.Default; - if (comparer == Comparer.Default) { + if (comparer == Comparer.Default) + { int retval; bool r = TrySZBinarySearch(array, index, length, value, out retval); if (r) @@ -830,45 +860,57 @@ namespace System { } int lo = index; - int hi = index + length - 1; + int hi = index + length - 1; Object[] objArray = array as Object[]; - if(objArray != null) { - while (lo <= hi) { + if (objArray != null) + { + while (lo <= hi) + { // i might overflow if lo and hi are both large positive numbers. int i = GetMedian(lo, hi); int c = 0; - try { + try + { c = comparer.Compare(objArray[i], value); } - catch (Exception e) { + catch (Exception e) + { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); } if (c == 0) return i; - if (c < 0) { + if (c < 0) + { lo = i + 1; } - else { + else + { hi = i - 1; } } } - else { - while (lo <= hi) { - int i = GetMedian(lo, hi); + else + { + while (lo <= hi) + { + int i = GetMedian(lo, hi); int c = 0; - try { + try + { c = comparer.Compare(array.GetValue(i), value); } - catch (Exception e) { + catch (Exception e) + { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); } if (c == 0) return i; - if (c < 0) { + if (c < 0) + { lo = i + 1; } - else { + else + { hi = i - 1; } } @@ -878,31 +920,35 @@ namespace System { [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool TrySZBinarySearch(Array sourceArray, int sourceIndex, int count, Object value, out int retVal); - + [Pure] - public static int BinarySearch<T>(T[] array, T value) { - if (array==null) + public static int BinarySearch<T>(T[] array, T value) + { + if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); Contract.EndContractBlock(); return BinarySearch<T>(array, 0, array.Length, value, null); } [Pure] - public static int BinarySearch<T>(T[] array, T value, System.Collections.Generic.IComparer<T> comparer) { - if (array==null) + public static int BinarySearch<T>(T[] array, T value, System.Collections.Generic.IComparer<T> comparer) + { + if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); Contract.EndContractBlock(); return BinarySearch<T>(array, 0, array.Length, value, comparer); } [Pure] - public static int BinarySearch<T>(T[] array, int index, int length, T value) { + public static int BinarySearch<T>(T[] array, int index, int length, T value) + { return BinarySearch<T>(array, index, length, value, null); } [Pure] - public static int BinarySearch<T>(T[] array, int index, int length, T value, System.Collections.Generic.IComparer<T> comparer) { - if (array==null) + public static int BinarySearch<T>(T[] array, int index, int length, T value, System.Collections.Generic.IComparer<T> comparer) + { + if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); if (index < 0) ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); @@ -916,12 +962,15 @@ namespace System { return ArraySortHelper<T>.Default.BinarySearch(array, index, length, value, comparer); } - public static TOutput[] ConvertAll<TInput, TOutput>(TInput[] array, Converter<TInput,TOutput> converter) { - if( array == null) { + public static TOutput[] ConvertAll<TInput, TOutput>(TInput[] array, Converter<TInput, TOutput> converter) + { + if (array == null) + { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - if( converter == null) { + if (converter == null) + { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.converter); } Contract.Ensures(Contract.Result<TOutput[]>() != null); @@ -929,7 +978,8 @@ namespace System { Contract.EndContractBlock(); TOutput[] newArray = new TOutput[array.Length]; - for( int i = 0; i< array.Length; i++) { + for (int i = 0; i < array.Length; i++) + { newArray[i] = converter(array[i]); } return newArray; @@ -959,7 +1009,12 @@ namespace System { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); Contract.EndContractBlock(); - this.CopyTo(array, (int) index); + this.CopyTo(array, (int)index); + } + + private static class EmptyArray<T> + { + internal static readonly T[] Value = new T[0]; } [Pure] @@ -972,7 +1027,8 @@ namespace System { return EmptyArray<T>.Value; } - public static bool Exists<T>(T[] array, Predicate<T> match) { + public static bool Exists<T>(T[] array, Predicate<T> match) + { return Array.FindIndex(array, match) != -1; } @@ -1012,45 +1068,57 @@ namespace System { } } - public static T Find<T>(T[] array, Predicate<T> match) { - if( array == null) { + public static T Find<T>(T[] array, Predicate<T> match) + { + if (array == null) + { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - if( match == null) { + if (match == null) + { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } Contract.EndContractBlock(); - for(int i = 0 ; i < array.Length; i++) { - if(match(array[i])) { + for (int i = 0; i < array.Length; i++) + { + if (match(array[i])) + { return array[i]; } } return default(T); } - public static T[] FindAll<T>(T[] array, Predicate<T> match) { - if( array == null) { + public static T[] FindAll<T>(T[] array, Predicate<T> match) + { + if (array == null) + { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - if( match == null) { + if (match == null) + { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } Contract.EndContractBlock(); - List<T> list = new List<T>(); - for(int i = 0 ; i < array.Length; i++) { - if(match(array[i])) { + List<T> list = new List<T>(); + for (int i = 0; i < array.Length; i++) + { + if (match(array[i])) + { list.Add(array[i]); } } return list.ToArray(); } - public static int FindIndex<T>(T[] array, Predicate<T> match) { - if (array==null) { + public static int FindIndex<T>(T[] array, Predicate<T> match) + { + if (array == null) + { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } Contract.Ensures(Contract.Result<int>() < array.Length); @@ -1059,62 +1127,77 @@ namespace System { return FindIndex(array, 0, array.Length, match); } - public static int FindIndex<T>(T[] array, int startIndex, Predicate<T> match) { - if (array==null) { + public static int FindIndex<T>(T[] array, int startIndex, Predicate<T> match) + { + if (array == null) + { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } Contract.Ensures(Contract.Result<int>() < array.Length); Contract.EndContractBlock(); - + return FindIndex(array, startIndex, array.Length - startIndex, match); } - public static int FindIndex<T>(T[] array, int startIndex, int count, Predicate<T> match) { - if (array==null) { + public static int FindIndex<T>(T[] array, int startIndex, int count, Predicate<T> match) + { + if (array == null) + { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - if( startIndex < 0 || startIndex > array.Length ) { + if (startIndex < 0 || startIndex > array.Length) + { ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); } - if (count < 0 || startIndex > array.Length - count) { + if (count < 0 || startIndex > array.Length - count) + { ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count(); } - if( match == null) { + if (match == null) + { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } Contract.Ensures(Contract.Result<int>() < array.Length); Contract.EndContractBlock(); int endIndex = startIndex + count; - for( int i = startIndex; i < endIndex; i++) { - if( match(array[i])) return i; + for (int i = startIndex; i < endIndex; i++) + { + if (match(array[i])) return i; } return -1; } - public static T FindLast<T>(T[] array, Predicate<T> match) { - if( array == null) { + public static T FindLast<T>(T[] array, Predicate<T> match) + { + if (array == null) + { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - if( match == null) { + if (match == null) + { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } Contract.EndContractBlock(); - - for(int i = array.Length - 1 ; i >= 0; i--) { - if(match(array[i])) { + + for (int i = array.Length - 1; i >= 0; i--) + { + if (match(array[i])) + { return array[i]; } } return default(T); } - public static int FindLastIndex<T>(T[] array, Predicate<T> match) { - if( array == null) { + public static int FindLastIndex<T>(T[] array, Predicate<T> match) + { + if (array == null) + { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } Contract.EndContractBlock(); @@ -1122,63 +1205,79 @@ namespace System { return FindLastIndex(array, array.Length - 1, array.Length, match); } - public static int FindLastIndex<T>(T[] array, int startIndex, Predicate<T> match) { - if( array == null) { + public static int FindLastIndex<T>(T[] array, int startIndex, Predicate<T> match) + { + if (array == null) + { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } Contract.EndContractBlock(); - + return FindLastIndex(array, startIndex, startIndex + 1, match); } - public static int FindLastIndex<T>(T[] array, int startIndex, int count, Predicate<T> match) { - if( array == null) { + public static int FindLastIndex<T>(T[] array, int startIndex, int count, Predicate<T> match) + { + if (array == null) + { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - if( match == null) { + if (match == null) + { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } Contract.EndContractBlock(); - if(array.Length == 0) { + if (array.Length == 0) + { // Special case for 0 length List - if( startIndex != -1) { + if (startIndex != -1) + { ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); } } - else { + else + { // Make sure we're not out of range - if ( startIndex < 0 || startIndex >= array.Length) { + if (startIndex < 0 || startIndex >= array.Length) + { ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); } } - + // 2nd have of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0. - if (count < 0 || startIndex - count + 1 < 0) { + if (count < 0 || startIndex - count + 1 < 0) + { ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count(); } int endIndex = startIndex - count; - for( int i = startIndex; i > endIndex; i--) { - if( match(array[i])) { + for (int i = startIndex; i > endIndex; i--) + { + if (match(array[i])) + { return i; } } return -1; } - public static void ForEach<T>(T[] array, Action<T> action) { - if( array == null) { + public static void ForEach<T>(T[] array, Action<T> action) + { + if (array == null) + { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - if( action == null) { + if (action == null) + { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.action); } Contract.EndContractBlock(); - for(int i = 0 ; i < array.Length; i++) { + for (int i = 0; i < array.Length; i++) + { action(array[i]); } } @@ -1195,43 +1294,46 @@ namespace System { else return new ArrayEnumerator(this, lowerBound, Length); } - + // Returns the index of the first occurrence of a given value in an array. // The array is searched forwards, and the elements of the array are // compared to the given value using the Object.Equals method. // - public static int IndexOf(Array array, Object value) { - if (array==null) + public static int IndexOf(Array array, Object value) + { + if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); Contract.Ensures(Contract.Result<int>() < array.GetLowerBound(0) + array.Length); Contract.EndContractBlock(); int lb = array.GetLowerBound(0); return IndexOf(array, value, lb, array.Length); } - + // Returns the index of the first occurrence of a given value in a range of // an array. The array is searched forwards, starting at index // startIndex and ending at the last element of the array. The // elements of the array are compared to the given value using the // Object.Equals method. // - public static int IndexOf(Array array, Object value, int startIndex) { - if (array==null) + public static int IndexOf(Array array, Object value, int startIndex) + { + if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); Contract.Ensures(Contract.Result<int>() < array.GetLowerBound(0) + array.Length); Contract.EndContractBlock(); int lb = array.GetLowerBound(0); return IndexOf(array, value, startIndex, array.Length - startIndex + lb); } - + // Returns the index of the first occurrence of a given value in a range of // an array. The array is searched forwards, starting at index // startIndex and upto count elements. The // elements of the array are compared to the given value using the // Object.Equals method. // - public static int IndexOf(Array array, Object value, int startIndex, int count) { - if (array==null) + public static int IndexOf(Array array, Object value, int startIndex, int count) + { + if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); if (array.Rank != 1) ThrowHelper.ThrowRankException(ExceptionResource.Rank_MultiDimNotSupported); @@ -1252,27 +1354,36 @@ namespace System { Object[] objArray = array as Object[]; int endIndex = startIndex + count; - if (objArray != null) { - if (value == null) { - for (int i = startIndex; i < endIndex; i++) { + if (objArray != null) + { + if (value == null) + { + for (int i = startIndex; i < endIndex; i++) + { if (objArray[i] == null) return i; } } - else { - for (int i = startIndex; i < endIndex; i++) { + else + { + for (int i = startIndex; i < endIndex; i++) + { Object obj = objArray[i]; if (obj != null && obj.Equals(value)) return i; } } } - else { - for (int i = startIndex; i < endIndex; i++) { + else + { + for (int i = startIndex; i < endIndex; i++) + { Object obj = array.GetValue(i); - if( obj == null) { - if(value == null) return i; + if (obj == null) + { + if (value == null) return i; } - else { - if( obj.Equals(value)) return i; + else + { + if (obj.Equals(value)) return i; } } } @@ -1280,12 +1391,14 @@ namespace System { // for arrays with a lower bound of -1 we will not return -1 when the // item was not found. And for SZArrays (the vast majority), -1 still // works for them. - return lb-1; + return lb - 1; } [Pure] - public static int IndexOf<T>(T[] array, T value) { - if (array==null) { + public static int IndexOf<T>(T[] array, T value) + { + if (array == null) + { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } Contract.Ensures((Contract.Result<int>() < 0) || @@ -1295,8 +1408,10 @@ namespace System { return IndexOf(array, value, 0, array.Length); } - public static int IndexOf<T>(T[] array, T value, int startIndex) { - if (array==null) { + public static int IndexOf<T>(T[] array, T value, int startIndex) + { + if (array == null) + { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } Contract.Ensures(Contract.Result<int>() < array.Length); @@ -1305,16 +1420,20 @@ namespace System { return IndexOf(array, value, startIndex, array.Length - startIndex); } - public static int IndexOf<T>(T[] array, T value, int startIndex, int count) { - if (array==null) { + public static int IndexOf<T>(T[] array, T value, int startIndex, int count) + { + if (array == null) + { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - if (startIndex < 0 || startIndex > array.Length ) { + if (startIndex < 0 || startIndex > array.Length) + { ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); } - if (count < 0 || count > array.Length - startIndex) { + if (count < 0 || count > array.Length - startIndex) + { ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count(); } Contract.Ensures(Contract.Result<int>() < array.Length); @@ -1325,27 +1444,29 @@ namespace System { [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool TrySZIndexOf(Array sourceArray, int sourceIndex, int count, Object value, out int retVal); - + // Returns the index of the last occurrence of a given value in an array. // The array is searched backwards, and the elements of the array are // compared to the given value using the Object.Equals method. // - public static int LastIndexOf(Array array, Object value) { - if (array==null) + public static int LastIndexOf(Array array, Object value) + { + if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); Contract.Ensures(Contract.Result<int>() < array.GetLowerBound(0) + array.Length); Contract.EndContractBlock(); int lb = array.GetLowerBound(0); return LastIndexOf(array, value, array.Length - 1 + lb, array.Length); } - + // Returns the index of the last occurrence of a given value in a range of // an array. The array is searched backwards, starting at index // startIndex and ending at index 0. The elements of the array are // compared to the given value using the Object.Equals method. // - public static int LastIndexOf(Array array, Object value, int startIndex) { + public static int LastIndexOf(Array array, Object value, int startIndex) + { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); Contract.Ensures(Contract.Result<int>() < array.GetLowerBound(0) + array.Length); @@ -1353,21 +1474,23 @@ namespace System { int lb = array.GetLowerBound(0); return LastIndexOf(array, value, startIndex, startIndex + 1 - lb); } - + // Returns the index of the last occurrence of a given value in a range of // an array. The array is searched backwards, starting at index // startIndex and counting uptocount elements. The elements of // the array are compared to the given value using the Object.Equals // method. // - public static int LastIndexOf(Array array, Object value, int startIndex, int count) { - if (array==null) + public static int LastIndexOf(Array array, Object value, int startIndex, int count) + { + if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); Contract.Ensures(Contract.Result<int>() < array.GetLowerBound(0) + array.Length); Contract.EndContractBlock(); int lb = array.GetLowerBound(0); - if (array.Length == 0) { - return lb-1; + if (array.Length == 0) + { + return lb - 1; } if (startIndex < lb || startIndex >= array.Length + lb) @@ -1387,35 +1510,46 @@ namespace System { Object[] objArray = array as Object[]; int endIndex = startIndex - count + 1; - if (objArray!=null) { - if (value == null) { - for (int i = startIndex; i >= endIndex; i--) { + if (objArray != null) + { + if (value == null) + { + for (int i = startIndex; i >= endIndex; i--) + { if (objArray[i] == null) return i; } } - else { - for (int i = startIndex; i >= endIndex; i--) { + else + { + for (int i = startIndex; i >= endIndex; i--) + { Object obj = objArray[i]; if (obj != null && obj.Equals(value)) return i; } } } - else { - for (int i = startIndex; i >= endIndex; i--) { + else + { + for (int i = startIndex; i >= endIndex; i--) + { Object obj = array.GetValue(i); - if( obj == null) { - if(value == null) return i; + if (obj == null) + { + if (value == null) return i; } - else { - if( obj.Equals(value)) return i; + else + { + if (obj.Equals(value)) return i; } } } - return lb-1; // Return lb-1 for arrays with negative lower bounds. + return lb - 1; // Return lb-1 for arrays with negative lower bounds. } - - public static int LastIndexOf<T>(T[] array, T value) { - if (array==null) { + + public static int LastIndexOf<T>(T[] array, T value) + { + if (array == null) + { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } Contract.Ensures(Contract.Result<int>() < array.Length); @@ -1424,50 +1558,59 @@ namespace System { return LastIndexOf(array, value, array.Length - 1, array.Length); } - public static int LastIndexOf<T>(T[] array, T value, int startIndex) { - if (array==null) { + public static int LastIndexOf<T>(T[] array, T value, int startIndex) + { + if (array == null) + { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } Contract.Ensures(Contract.Result<int>() < array.Length); Contract.EndContractBlock(); // if array is empty and startIndex is 0, we need to pass 0 as count - return LastIndexOf(array, value, startIndex, (array.Length == 0)? 0 : (startIndex + 1)); + return LastIndexOf(array, value, startIndex, (array.Length == 0) ? 0 : (startIndex + 1)); } - public static int LastIndexOf<T>(T[] array, T value, int startIndex, int count) { - if (array==null) { + public static int LastIndexOf<T>(T[] array, T value, int startIndex, int count) + { + if (array == null) + { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } Contract.Ensures(Contract.Result<int>() < array.Length); Contract.EndContractBlock(); - - if(array.Length == 0) { + + if (array.Length == 0) + { // // Special case for 0 length List // accept -1 and 0 as valid startIndex for compablility reason. // - if( startIndex != -1 && startIndex != 0) { + if (startIndex != -1 && startIndex != 0) + { ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); } // only 0 is a valid value for count if array is empty - if( count != 0) { + if (count != 0) + { ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count(); } return -1; } // Make sure we're not out of range - if ( startIndex < 0 || startIndex >= array.Length) { + if (startIndex < 0 || startIndex >= array.Length) + { ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); } - + // 2nd have of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0. - if (count < 0 || startIndex - count + 1 < 0) { + if (count < 0 || startIndex - count + 1 < 0) + { ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count(); } - return EqualityComparer<T>.Default.LastIndexOf(array, value, startIndex, count); + return EqualityComparer<T>.Default.LastIndexOf(array, value, startIndex, count); } [MethodImplAttribute(MethodImplOptions.InternalCall)] @@ -1479,21 +1622,23 @@ namespace System { // located at index length - i - 1, where length is the // length of the array. // - public static void Reverse(Array array) { - if (array==null) + public static void Reverse(Array array) + { + if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); Contract.EndContractBlock(); Reverse(array, array.GetLowerBound(0), array.Length); } - + // Reverses the elements in a range of an array. Following a call to this // method, an element in the range given by index and count // which was previously located at index i will now be located at // index index + (index + count - i - 1). // Reliability note: This may fail because it may have to box objects. // - public static void Reverse(Array array, int index, int length) { - if (array==null) + public static void Reverse(Array array, int index, int length) + { + if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); int lowerBound = array.GetLowerBound(0); if (index < lowerBound) @@ -1514,8 +1659,10 @@ namespace System { int i = index; int j = index + length - 1; Object[] objArray = array as Object[]; - if (objArray!=null) { - while (i < j) { + if (objArray != null) + { + while (i < j) + { Object temp = objArray[i]; objArray[i] = objArray[j]; objArray[j] = temp; @@ -1523,8 +1670,10 @@ namespace System { j--; } } - else { - while (i < j) { + else + { + while (i < j) + { Object temp = array.GetValue(i); array.SetValue(array.GetValue(j), i); array.SetValue(temp, j); @@ -1573,57 +1722,62 @@ namespace System { // other using the IComparable interface, which must be implemented // by all elements of the array. // - public static void Sort(Array array) { - if (array==null) + public static void Sort(Array array) + { + if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); Contract.EndContractBlock(); Sort(array, null, array.GetLowerBound(0), array.Length, null); } - + // Sorts the elements of two arrays based on the keys in the first array. // Elements in the keys array specify the sort keys for // corresponding elements in the items array. The sort compares the // keys to each other using the IComparable interface, which must be // implemented by all elements of the keys array. // - public static void Sort(Array keys, Array items) { - if (keys==null) + public static void Sort(Array keys, Array items) + { + if (keys == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys); Contract.EndContractBlock(); Sort(keys, items, keys.GetLowerBound(0), keys.Length, null); } - + // Sorts the elements in a section of an array. The sort compares the // elements to each other using the IComparable interface, which // must be implemented by all elements in the given section of the array. // - public static void Sort(Array array, int index, int length) { + public static void Sort(Array array, int index, int length) + { Sort(array, null, index, length, null); } - + // Sorts the elements in a section of two arrays based on the keys in the // first array. Elements in the keys array specify the sort keys for // corresponding elements in the items array. The sort compares the // keys to each other using the IComparable interface, which must be // implemented by all elements of the keys array. // - public static void Sort(Array keys, Array items, int index, int length) { + public static void Sort(Array keys, Array items, int index, int length) + { Sort(keys, items, index, length, null); } - + // Sorts the elements of an array. The sort compares the elements to each // other using the given IComparer interface. If comparer is // null, the elements are compared to each other using the // IComparable interface, which in that case must be implemented by // all elements of the array. // - public static void Sort(Array array, IComparer comparer) { - if (array==null) + public static void Sort(Array array, IComparer comparer) + { + if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); Contract.EndContractBlock(); Sort(array, null, array.GetLowerBound(0), array.Length, comparer); } - + // Sorts the elements of two arrays based on the keys in the first array. // Elements in the keys array specify the sort keys for // corresponding elements in the items array. The sort compares the @@ -1632,23 +1786,25 @@ namespace System { // the IComparable interface, which in that case must be implemented // by all elements of the keys array. // - public static void Sort(Array keys, Array items, IComparer comparer) { - if (keys==null) + public static void Sort(Array keys, Array items, IComparer comparer) + { + if (keys == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys); Contract.EndContractBlock(); Sort(keys, items, keys.GetLowerBound(0), keys.Length, comparer); } - + // Sorts the elements in a section of an array. The sort compares the // elements to each other using the given IComparer interface. If // comparer is null, the elements are compared to each other using // the IComparable interface, which in that case must be implemented // by all elements in the given section of the array. // - public static void Sort(Array array, int index, int length, IComparer comparer) { + public static void Sort(Array array, int index, int length, IComparer comparer) + { Sort(array, null, index, length, comparer); } - + // Sorts the elements in a section of two arrays based on the keys in the // first array. Elements in the keys array specify the sort keys for // corresponding elements in the items array. The sort compares the @@ -1657,8 +1813,9 @@ namespace System { // the IComparable interface, which in that case must be implemented // by all elements of the given section of the keys array. // - public static void Sort(Array keys, Array items, int index, int length, IComparer comparer) { - if (keys==null) + public static void Sort(Array keys, Array items, int index, int length, IComparer comparer) + { + if (keys == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys); if (keys.Rank != 1 || (items != null && items.Rank != 1)) ThrowHelper.ThrowRankException(ExceptionResource.Rank_MultiDimNotSupported); @@ -1674,9 +1831,11 @@ namespace System { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); Contract.EndContractBlock(); - - if (length > 1) { - if (comparer == Comparer.Default || comparer == null) { + + if (length > 1) + { + if (comparer == Comparer.Default || comparer == null) + { bool r = TrySZSort(keys, items, index, index + length - 1); if (r) return; @@ -1686,58 +1845,67 @@ namespace System { Object[] objItems = null; if (objKeys != null) objItems = items as Object[]; - if (objKeys != null && (items==null || objItems != null)) { + if (objKeys != null && (items == null || objItems != null)) + { SorterObjectArray sorter = new SorterObjectArray(objKeys, objItems, comparer); sorter.Sort(index, length); } - else { + else + { SorterGenericArray sorter = new SorterGenericArray(keys, items, comparer); sorter.Sort(index, length); } } } - + [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool TrySZSort(Array keys, Array items, int left, int right); - public static void Sort<T>(T[] array) { - if (array==null) + public static void Sort<T>(T[] array) + { + if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); Contract.EndContractBlock(); Sort<T>(array, 0, array.Length, null); } - public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items) { - if (keys==null) + public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items) + { + if (keys == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys); Contract.EndContractBlock(); Sort<TKey, TValue>(keys, items, 0, keys.Length, null); } - public static void Sort<T>(T[] array, int index, int length) { + public static void Sort<T>(T[] array, int index, int length) + { Sort<T>(array, index, length, null); } - public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items, int index, int length) { + public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items, int index, int length) + { Sort<TKey, TValue>(keys, items, index, length, null); } - public static void Sort<T>(T[] array, System.Collections.Generic.IComparer<T> comparer) { + public static void Sort<T>(T[] array, System.Collections.Generic.IComparer<T> comparer) + { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); Contract.EndContractBlock(); Sort<T>(array, 0, array.Length, comparer); } - public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items, System.Collections.Generic.IComparer<TKey> comparer) { - if (keys==null) + public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items, System.Collections.Generic.IComparer<TKey> comparer) + { + if (keys == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys); Contract.EndContractBlock(); Sort<TKey, TValue>(keys, items, 0, keys.Length, comparer); } - public static void Sort<T>(T[] array, int index, int length, System.Collections.Generic.IComparer<T> comparer) { - if (array==null) + public static void Sort<T>(T[] array, int index, int length, System.Collections.Generic.IComparer<T> comparer) + { + if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); if (index < 0) ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); @@ -1747,19 +1915,23 @@ namespace System { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); Contract.EndContractBlock(); - if (length > 1) { - if ( comparer == null || comparer == Comparer<T>.Default ) { - if(TrySZSort(array, null, index, index + length - 1)) { + if (length > 1) + { + if (comparer == null || comparer == Comparer<T>.Default) + { + if (TrySZSort(array, null, index, index + length - 1)) + { return; } } - ArraySortHelper<T>.Default.Sort(array, index, length, comparer); + ArraySortHelper<T>.Default.Sort(array, index, length, comparer); } } - public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items, int index, int length, System.Collections.Generic.IComparer<TKey> comparer) { - if (keys==null) + public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items, int index, int length, System.Collections.Generic.IComparer<TKey> comparer) + { + if (keys == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys); if (index < 0) ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); @@ -1769,13 +1941,16 @@ namespace System { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); Contract.EndContractBlock(); - if (length > 1) { - if ( comparer == null || comparer == Comparer<TKey>.Default ) { - if(TrySZSort(keys, items, index, index + length - 1)) { + if (length > 1) + { + if (comparer == null || comparer == Comparer<TKey>.Default) + { + if (TrySZSort(keys, items, index, index + length - 1)) + { return; } } - + if (items == null) { Sort<TKey>(keys, index, length, comparer); @@ -1786,12 +1961,15 @@ namespace System { } } - public static void Sort<T>(T[] array, Comparison<T> comparison) { - if( array == null) { + public static void Sort<T>(T[] array, Comparison<T> comparison) + { + if (array == null) + { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - if( comparison == null) { + if (comparison == null) + { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparison); } Contract.EndContractBlock(); @@ -1799,18 +1977,23 @@ namespace System { ArraySortHelper<T>.Sort(array, 0, array.Length, comparison); } - public static bool TrueForAll<T>(T[] array, Predicate<T> match) { - if( array == null) { + public static bool TrueForAll<T>(T[] array, Predicate<T> match) + { + if (array == null) + { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - if( match == null) { + if (match == null) + { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } Contract.EndContractBlock(); - for(int i = 0 ; i < array.Length; i++) { - if( !match(array[i])) { + for (int i = 0; i < array.Length; i++) + { + if (!match(array[i])) + { return false; } } @@ -1823,15 +2006,16 @@ namespace System { { private Object[] keys; private Object[] items; - private IComparer comparer; - - internal SorterObjectArray(Object[] keys, Object[] items, IComparer comparer) { + private IComparer comparer; + + internal SorterObjectArray(Object[] keys, Object[] items, IComparer comparer) + { if (comparer == null) comparer = Comparer.Default; this.keys = keys; this.items = items; this.comparer = comparer; } - + internal void SwapIfGreaterWithItems(int a, int b) { if (a != b) @@ -1907,9 +2091,9 @@ namespace System { } if (partitionSize == 3) { - SwapIfGreaterWithItems(lo, hi-1); + SwapIfGreaterWithItems(lo, hi - 1); SwapIfGreaterWithItems(lo, hi); - SwapIfGreaterWithItems(hi-1, hi); + SwapIfGreaterWithItems(hi - 1, hi); return; } @@ -1948,7 +2132,7 @@ namespace System { while (comparer.Compare(keys[++left], pivot) < 0) ; while (comparer.Compare(pivot, keys[--right]) < 0) ; - if(left >= right) + if (left >= right) break; Swap(left, right); @@ -1989,7 +2173,7 @@ namespace System { if (!(comparer.Compare(d, keys[lo + child - 1]) < 0)) break; keys[lo + i - 1] = keys[lo + child - 1]; - if(items != null) + if (items != null) items[lo + i - 1] = items[lo + child - 1]; i = child; } @@ -2010,17 +2194,17 @@ namespace System { while (j >= lo && comparer.Compare(t, keys[j]) < 0) { keys[j + 1] = keys[j]; - if(items != null) + if (items != null) items[j + 1] = items[j]; j--; } keys[j + 1] = t; - if(items != null) + if (items != null) items[j + 1] = ti; } } } - + // Private value used by the Sort methods for instances of Array. // This is slower than the one for Object[], since we can't use the JIT helpers // to access the elements. We must use GetValue & SetValue. @@ -2062,8 +2246,8 @@ namespace System { Object t1 = keys.GetValue(i); keys.SetValue(keys.GetValue(j), i); keys.SetValue(t1, j); - - if(items != null) + + if (items != null) { Object t2 = items.GetValue(i); items.SetValue(items.GetValue(j), i); @@ -2113,9 +2297,9 @@ namespace System { } if (partitionSize == 3) { - SwapIfGreaterWithItems(lo, hi-1); + SwapIfGreaterWithItems(lo, hi - 1); SwapIfGreaterWithItems(lo, hi); - SwapIfGreaterWithItems(hi-1, hi); + SwapIfGreaterWithItems(hi - 1, hi); return; } @@ -2148,7 +2332,7 @@ namespace System { Object pivot = keys.GetValue(mid); Swap(mid, hi - 1); int left = lo, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below. - + while (left < right) { while (comparer.Compare(keys.GetValue(++left), pivot) < 0) ; @@ -2183,7 +2367,7 @@ namespace System { private void DownHeap(int i, int n, int lo) { Object d = keys.GetValue(lo + i - 1); - Object dt = (items != null)? items.GetValue(lo + i - 1) : null; + Object dt = (items != null) ? items.GetValue(lo + i - 1) : null; int child; while (i <= n / 2) { @@ -2197,12 +2381,12 @@ namespace System { break; keys.SetValue(keys.GetValue(lo + child - 1), lo + i - 1); - if(items != null) + if (items != null) items.SetValue(items.GetValue(lo + child - 1), lo + i - 1); i = child; } keys.SetValue(d, lo + i - 1); - if(items != null) + if (items != null) items.SetValue(dt, lo + i - 1); } @@ -2214,30 +2398,32 @@ namespace System { { j = i; t = keys.GetValue(i + 1); - dt = (items != null)? items.GetValue(i + 1) : null; + dt = (items != null) ? items.GetValue(i + 1) : null; while (j >= lo && comparer.Compare(t, keys.GetValue(j)) < 0) { keys.SetValue(keys.GetValue(j), j + 1); - if(items != null) + if (items != null) items.SetValue(items.GetValue(j), j + 1); j--; } keys.SetValue(t, j + 1); - if(items != null) + if (items != null) items.SetValue(dt, j + 1); } } } - [Serializable] private sealed class SZArrayEnumerator : IEnumerator, ICloneable + [Serializable] + private sealed class SZArrayEnumerator : IEnumerator, ICloneable { private Array _array; private int _index; private int _endIndex; // cache array length, since it's a little slow. - internal SZArrayEnumerator(Array array) { + internal SZArrayEnumerator(Array array) + { 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; @@ -2249,28 +2435,34 @@ namespace System { return MemberwiseClone(); } - public bool MoveNext() { - if (_index < _endIndex) { + public bool MoveNext() + { + if (_index < _endIndex) + { _index++; return (_index < _endIndex); } return false; } - - public Object Current { - get { + + public Object Current + { + get + { if (_index < 0) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumNotStarted(); if (_index >= _endIndex) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumEnded(); return _array.GetValue(_index); } } - - public void Reset() { + + public void Reset() + { _index = -1; } } - - [Serializable] private sealed class ArrayEnumerator : IEnumerator, ICloneable + + [Serializable] + private sealed class ArrayEnumerator : IEnumerator, ICloneable { private Array array; private int index; @@ -2279,23 +2471,26 @@ namespace System { private int[] _indices; // The current position in a multidim array private bool _complete; - internal ArrayEnumerator(Array array, int index, int count) { + internal ArrayEnumerator(Array array, int index, int count) + { this.array = array; this.index = index - 1; startIndex = index; endIndex = index + count; _indices = new int[array.Rank]; int checkForZero = 1; // Check for dimensions of size 0. - for(int i=0; i<array.Rank; i++) { + for (int i = 0; i < array.Rank; i++) + { _indices[i] = array.GetLowerBound(i); checkForZero *= array.GetLength(i); } // To make MoveNext simpler, decrement least significant index. - _indices[_indices.Length-1]--; + _indices[_indices.Length - 1]--; _complete = (checkForZero == 0); } - private void IncArray() { + private void IncArray() + { // This method advances us to the next valid array index, // handling all the multiple dimension & bounds correctly. // Think of it like an odometer in your car - we start with @@ -2306,16 +2501,19 @@ namespace System { // has rolled over it's upper bound, we're done. // int rank = array.Rank; - _indices[rank-1]++; - for(int dim=rank-1; dim>=0; dim--) { - if (_indices[dim] > array.GetUpperBound(dim)) { - if (dim==0) { + _indices[rank - 1]++; + for (int dim = rank - 1; dim >= 0; dim--) + { + if (_indices[dim] > array.GetUpperBound(dim)) + { + if (dim == 0) + { _complete = true; break; } - for(int j=dim; j<rank; j++) + for (int j = dim; j < rank; j++) _indices[j] = array.GetLowerBound(j); - _indices[dim-1]++; + _indices[dim - 1]++; } } } @@ -2325,8 +2523,10 @@ namespace System { return MemberwiseClone(); } - public bool MoveNext() { - if (_complete) { + public bool MoveNext() + { + if (_complete) + { index = endIndex; return false; } @@ -2334,25 +2534,29 @@ namespace System { IncArray(); return !_complete; } - - public Object Current { - get { + + public Object Current + { + get + { if (index < startIndex) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumNotStarted(); if (_complete) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumEnded(); return array.GetValue(_indices); } } - - public void Reset() { + + public void Reset() + { index = startIndex - 1; int checkForZero = 1; - for(int i=0; i<array.Rank; i++) { + for (int i = 0; i < array.Rank; i++) + { _indices[i] = array.GetLowerBound(i); checkForZero *= array.GetLength(i); } _complete = (checkForZero == 0); // To make MoveNext simpler, decrement least significant index. - _indices[_indices.Length-1]--; + _indices[_indices.Length - 1]--; } } @@ -2393,16 +2597,19 @@ namespace System { // array that is castable to "T[]" (i.e. for primitivs and valuetypes, it will be exactly // "T[]" - for orefs, it may be a "U[]" where U derives from T.) //---------------------------------------------------------------------------------------- - sealed class SZArrayHelper { + internal sealed class SZArrayHelper + { // It is never legal to instantiate this class. - private SZArrayHelper() { + private SZArrayHelper() + { Debug.Assert(false, "Hey! How'd I get here?"); } // ----------------------------------------------------------- // ------- Implement IEnumerable<T> interface methods -------- // ----------------------------------------------------------- - internal IEnumerator<T> GetEnumerator<T>() { + internal IEnumerator<T> GetEnumerator<T>() + { //! Warning: "this" is an array, not an SZArrayHelper. See comments above //! or you may introduce a security hole! T[] _this = JitHelpers.UnsafeCast<T[]>(this); @@ -2413,7 +2620,8 @@ namespace System { // ----------------------------------------------------------- // ------- Implement ICollection<T> interface methods -------- // ----------------------------------------------------------- - void CopyTo<T>(T[] array, int index) { + private void CopyTo<T>(T[] array, int index) + { //! Warning: "this" is an array, not an SZArrayHelper. See comments above //! or you may introduce a security hole! @@ -2421,7 +2629,8 @@ namespace System { Array.Copy(_this, 0, array, index, _this.Length); } - internal int get_Count<T>() { + internal int get_Count<T>() + { //! Warning: "this" is an array, not an SZArrayHelper. See comments above //! or you may introduce a security hole! T[] _this = JitHelpers.UnsafeCast<T[]>(this); @@ -2431,70 +2640,82 @@ namespace System { // ----------------------------------------------------------- // ---------- Implement IList<T> interface methods ----------- // ----------------------------------------------------------- - internal T get_Item<T>(int index) { + internal T get_Item<T>(int index) + { //! Warning: "this" is an array, not an SZArrayHelper. See comments above //! or you may introduce a security hole! T[] _this = JitHelpers.UnsafeCast<T[]>(this); - if ((uint)index >= (uint)_this.Length) { + if ((uint)index >= (uint)_this.Length) + { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } return _this[index]; } - internal void set_Item<T>(int index, T value) { + internal void set_Item<T>(int index, T value) + { //! Warning: "this" is an array, not an SZArrayHelper. See comments above //! or you may introduce a security hole! T[] _this = JitHelpers.UnsafeCast<T[]>(this); - if ((uint)index >= (uint)_this.Length) { + if ((uint)index >= (uint)_this.Length) + { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } _this[index] = value; } - void Add<T>(T value) { + private void Add<T>(T value) + { // Not meaningful for arrays. ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_FixedSizeCollection); } - bool Contains<T>(T value) { + private bool Contains<T>(T value) + { //! Warning: "this" is an array, not an SZArrayHelper. See comments above //! or you may introduce a security hole! T[] _this = JitHelpers.UnsafeCast<T[]>(this); return Array.IndexOf(_this, value, 0, _this.Length) >= 0; } - - bool get_IsReadOnly<T>() { - return true; + + private bool get_IsReadOnly<T>() + { + return true; } - - void Clear<T>() { + + private void Clear<T>() + { //! Warning: "this" is an array, not an SZArrayHelper. See comments above //! or you may introduce a security hole! - ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); + ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } - int IndexOf<T>(T value) { + private int IndexOf<T>(T value) + { //! Warning: "this" is an array, not an SZArrayHelper. See comments above //! or you may introduce a security hole! T[] _this = JitHelpers.UnsafeCast<T[]>(this); return Array.IndexOf(_this, value, 0, _this.Length); } - - void Insert<T>(int index, T value) { + + private void Insert<T>(int index, T value) + { // Not meaningful for arrays ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_FixedSizeCollection); } - bool Remove<T>(T value) { + private bool Remove<T>(T value) + { // Not meaningful for arrays ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_FixedSizeCollection); return default(bool); } - void RemoveAt<T>(int index) { + private void RemoveAt<T>(int index) + { // Not meaningful for arrays ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_FixedSizeCollection); } @@ -2502,7 +2723,9 @@ namespace System { // This is a normal generic Enumerator for SZ arrays. It doesn't have any of the "this" stuff // that SZArrayHelper does. // - [Serializable] private sealed class SZGenericArrayEnumerator<T> : IEnumerator<T> { + [Serializable] + private sealed class SZGenericArrayEnumerator<T> : IEnumerator<T> + { private T[] _array; private int _index; private int _endIndex; // cache array length, since it's a little slow. @@ -2510,37 +2733,45 @@ namespace System { // Passing -1 for endIndex so that MoveNext always returns false without mutating _index internal static readonly SZGenericArrayEnumerator<T> Empty = new SZGenericArrayEnumerator<T>(null, -1); - internal SZGenericArrayEnumerator(T[] array, int endIndex) { + internal SZGenericArrayEnumerator(T[] array, int endIndex) + { // We allow passing null array in case of 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; } - - public bool MoveNext() { - if (_index < _endIndex) { + + public bool MoveNext() + { + if (_index < _endIndex) + { _index++; return (_index < _endIndex); } return false; } - - public T Current { - get { + + public T Current + { + get + { if (_index < 0) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumNotStarted(); if (_index >= _endIndex) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumEnded(); return _array[_index]; } } - - object IEnumerator.Current { - get { + + object IEnumerator.Current + { + get + { return Current; } } - void IEnumerator.Reset() { + void IEnumerator.Reset() + { _index = -1; } @@ -2551,8 +2782,3 @@ namespace System { } } -// Useful in number of places that return an empty byte array to avoid unnecessary memory allocation. -internal static class EmptyArray<T> -{ - public static readonly T[] Value = new T[0]; -} diff --git a/src/mscorlib/src/System/ArraySegment.cs b/src/mscorlib/src/System/ArraySegment.cs index 03556e492a..a18590d5d8 100644 --- a/src/mscorlib/src/System/ArraySegment.cs +++ b/src/mscorlib/src/System/ArraySegment.cs @@ -15,6 +15,7 @@ using System.Collections; using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.Contracts; namespace System @@ -27,6 +28,10 @@ namespace System [Serializable] public struct ArraySegment<T> : IList<T>, IReadOnlyList<T> { + // Do not replace the array allocation with Array.Empty. We don't want to have the overhead of + // instantiating another generic type in addition to ArraySegment<T> for new type parameters. + public static ArraySegment<T> Empty { get; } = new ArraySegment<T>(new T[0]); + private readonly T[] _array; private readonly int _offset; private readonly int _count; @@ -45,8 +50,9 @@ namespace System public ArraySegment(T[] array, int offset, int count) { // Validate arguments, check is minimal instructions with reduced branching for inlinable fast-path + // Negative values discovered though conversion to high values when converted to unsigned // Failure should be rare and location determination and message is delegated to failure functions - if (array == null || (offset | count) < 0 || (array.Length - offset < count)) + if (array == null || (uint)offset > (uint)array.Length || (uint)count > (uint)(array.Length - offset)) ThrowHelper.ThrowArraySegmentCtorValidationFailedExceptions(array, offset, count); Contract.EndContractBlock(); @@ -55,62 +61,37 @@ namespace System _count = count; } - public T[] Array - { - get - { - Debug.Assert( (null == _array && 0 == _offset && 0 == _count) - || (null != _array && _offset >= 0 && _count >= 0 && _offset + _count <= _array.Length), - "ArraySegment is invalid"); + public T[] Array => _array; - return _array; - } - } + public int Offset => _offset; - public int Offset + public int Count => _count; + + public T this[int index] { get { - // Since copying value types is not atomic & callers cannot atomically - // read all three fields, we cannot guarantee that Offset is within - // the bounds of Array. That is our intent, but let's not specify - // it as a postcondition - force callers to re-verify this themselves - // after reading each field out of an ArraySegment into their stack. - Contract.Ensures(Contract.Result<int>() >= 0); - - Debug.Assert( (null == _array && 0 == _offset && 0 == _count) - || (null != _array && _offset >= 0 && _count >= 0 && _offset + _count <= _array.Length), - "ArraySegment is invalid"); - - return _offset; - } - } + if ((uint)index >= (uint)_count) + { + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); + } - public int Count - { - get + return _array[_offset + index]; + } + set { - // Since copying value types is not atomic & callers cannot atomically - // read all three fields, we cannot guarantee that Count is within - // the bounds of Array. That's our intent, but let's not specify - // it as a postcondition - force callers to re-verify this themselves - // after reading each field out of an ArraySegment into their stack. - Contract.Ensures(Contract.Result<int>() >= 0); - - Debug.Assert( (null == _array && 0 == _offset && 0 == _count) - || (null != _array && _offset >= 0 && _count >= 0 && _offset + _count <= _array.Length), - "ArraySegment is invalid"); - - return _count; + if ((uint)index >= (uint)_count) + { + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); + } + + _array[_offset + index] = value; } } public Enumerator GetEnumerator() { - if (_array == null) - ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_NullArray); - Contract.EndContractBlock(); - + ThrowInvalidOperationIfDefault(); return new Enumerator(this); } @@ -120,17 +101,38 @@ namespace System { return 0; } - + int hash = 5381; hash = System.Numerics.Hashing.HashHelpers.Combine(hash, _offset); hash = System.Numerics.Hashing.HashHelpers.Combine(hash, _count); - + // The array hash is expected to be an evenly-distributed mixture of bits, // so rather than adding the cost of another rotation we just xor it. hash ^= _array.GetHashCode(); return hash; } + public void CopyTo(T[] destination) => CopyTo(destination, 0); + + public void CopyTo(T[] destination, int destinationIndex) + { + ThrowInvalidOperationIfDefault(); + System.Array.Copy(_array, _offset, destination, destinationIndex, _count); + } + + public void CopyTo(ArraySegment<T> destination) + { + ThrowInvalidOperationIfDefault(); + destination.ThrowInvalidOperationIfDefault(); + + if (_count > destination._count) + { + ThrowHelper.ThrowArgumentException_DestinationTooShort(); + } + + System.Array.Copy(_array, _offset, destination._array, destination._offset, _count); + } + public override bool Equals(Object obj) { if (obj is ArraySegment<T>) @@ -138,30 +140,69 @@ namespace System else return false; } - + public bool Equals(ArraySegment<T> obj) { return obj._array == _array && obj._offset == _offset && obj._count == _count; } - + + public ArraySegment<T> Slice(int index) + { + ThrowInvalidOperationIfDefault(); + + if ((uint)index > (uint)_count) + { + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); + } + + return new ArraySegment<T>(_array, _offset + index, _count - index); + } + + public ArraySegment<T> Slice(int index, int count) + { + ThrowInvalidOperationIfDefault(); + + if ((uint)index > (uint)_count || (uint)count > (uint)(_count - index)) + { + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); + } + + return new ArraySegment<T>(_array, _offset + index, count); + } + + public T[] ToArray() + { + ThrowInvalidOperationIfDefault(); + + if (_count == 0) + { + return Empty._array; + } + + var array = new T[_count]; + System.Array.Copy(_array, _offset, array, 0, _count); + return array; + } + public static bool operator ==(ArraySegment<T> a, ArraySegment<T> b) { return a.Equals(b); } - + public static bool operator !=(ArraySegment<T> a, ArraySegment<T> b) { return !(a == b); } + public static implicit operator ArraySegment<T>(T[] array) => new ArraySegment<T>(array); + #region IList<T> T IList<T>.this[int index] { get { - if (_array == null) - ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_NullArray); - if (index < 0 || index >= _count) + ThrowInvalidOperationIfDefault(); + if (index < 0 || index >= _count) ThrowHelper.ThrowArgumentOutOfRange_IndexException(); Contract.EndContractBlock(); @@ -170,8 +211,7 @@ namespace System set { - if (_array == null) - ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_NullArray); + ThrowInvalidOperationIfDefault(); if (index < 0 || index >= _count) ThrowHelper.ThrowArgumentOutOfRange_IndexException(); Contract.EndContractBlock(); @@ -182,9 +222,7 @@ namespace System int IList<T>.IndexOf(T item) { - if (_array == null) - ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_NullArray); - Contract.EndContractBlock(); + ThrowInvalidOperationIfDefault(); int index = System.Array.IndexOf<T>(_array, item, _offset, _count); @@ -210,8 +248,7 @@ namespace System { get { - if (_array == null) - ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_NullArray); + ThrowInvalidOperationIfDefault(); if (index < 0 || index >= _count) ThrowHelper.ThrowArgumentOutOfRange_IndexException(); Contract.EndContractBlock(); @@ -244,9 +281,7 @@ namespace System bool ICollection<T>.Contains(T item) { - if (_array == null) - ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_NullArray); - Contract.EndContractBlock(); + ThrowInvalidOperationIfDefault(); int index = System.Array.IndexOf<T>(_array, item, _offset, _count); @@ -256,15 +291,6 @@ namespace System return index >= 0; } - void ICollection<T>.CopyTo(T[] array, int arrayIndex) - { - if (_array == null) - ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_NullArray); - Contract.EndContractBlock(); - - System.Array.Copy(_array, _offset, array, arrayIndex, _count); - } - bool ICollection<T>.Remove(T item) { ThrowHelper.ThrowNotSupportedException(); @@ -282,6 +308,14 @@ namespace System IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); #endregion + private void ThrowInvalidOperationIfDefault() + { + if (_array == null) + { + ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_NullArray); + } + } + [Serializable] public struct Enumerator : IEnumerator<T> { diff --git a/src/mscorlib/src/System/ArrayTypeMismatchException.cs b/src/mscorlib/src/System/ArrayTypeMismatchException.cs deleted file mode 100644 index 3e941fdf8e..0000000000 --- a/src/mscorlib/src/System/ArrayTypeMismatchException.cs +++ /dev/null @@ -1,51 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -/*============================================================================= -** -** -** -** Purpose: The arrays are of different primitive types. -** -** -=============================================================================*/ - -using System.Runtime.Serialization; - -namespace System -{ - // The ArrayMismatchException is thrown when an attempt to store - // an object of the wrong type within an array occurs. - // - [Serializable] - public class ArrayTypeMismatchException : SystemException - { - // Creates a new ArrayMismatchException with its message string set to - // the empty string, its HRESULT set to COR_E_ARRAYTYPEMISMATCH, - // and its ExceptionInfo reference set to null. - public ArrayTypeMismatchException() - : base(SR.Arg_ArrayTypeMismatchException) - { - HResult = __HResults.COR_E_ARRAYTYPEMISMATCH; - } - - // Creates a new ArrayMismatchException with its message string set to - // message, its HRESULT set to COR_E_ARRAYTYPEMISMATCH, - // and its ExceptionInfo reference set to null. - // - public ArrayTypeMismatchException(String message) - : base(message) - { - HResult = __HResults.COR_E_ARRAYTYPEMISMATCH; - } - - public ArrayTypeMismatchException(String message, Exception innerException) - : base(message, innerException) - { - HResult = __HResults.COR_E_ARRAYTYPEMISMATCH; - } - - protected ArrayTypeMismatchException(SerializationInfo info, StreamingContext context) : base(info, context) { } - } -} diff --git a/src/mscorlib/src/System/AsyncCallback.cs b/src/mscorlib/src/System/AsyncCallback.cs deleted file mode 100644 index 5c49535cff..0000000000 --- a/src/mscorlib/src/System/AsyncCallback.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -/*============================================================ -** -** Interface: AsyncCallbackDelegate -** -** Purpose: Type of callback for async operations -** -===========================================================*/ - -namespace System -{ - [Serializable] - public delegate void AsyncCallback(IAsyncResult ar); -} diff --git a/src/mscorlib/src/System/Attribute.cs b/src/mscorlib/src/System/Attribute.cs index b44e13f959..baa9a71638 100644 --- a/src/mscorlib/src/System/Attribute.cs +++ b/src/mscorlib/src/System/Attribute.cs @@ -3,19 +3,20 @@ // See the LICENSE file in the project root for more information. -namespace System { - - using System; - using System.Reflection; - using System.Collections.Generic; - using System.Runtime.InteropServices; - using System.Globalization; - using System.Diagnostics; - using System.Diagnostics.Contracts; - using System.Security; +using System; +using System.Reflection; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Globalization; +using System.Diagnostics; +using System.Diagnostics.Contracts; +using System.Security; + +namespace System +{ [Serializable] - [AttributeUsageAttribute(AttributeTargets.All, Inherited = true, AllowMultiple=false)] + [AttributeUsageAttribute(AttributeTargets.All, Inherited = true, AllowMultiple = false)] public abstract class Attribute { #region Private Statics @@ -42,7 +43,7 @@ namespace System { //if this is an index we need to get the parameter types to help disambiguate Type[] indexParamTypes = GetIndexParameterTypes(element); - + PropertyInfo baseProp = GetParentDefinition(element, indexParamTypes); while (baseProp != null) @@ -61,12 +62,12 @@ namespace System { // walk up the hierarchy chain if (element.IsDefined(attributeType, inherit)) return true; - + if (inherit) { AttributeUsageAttribute usage = InternalGetAttributeUsage(attributeType); - if (!usage.Inherited) + if (!usage.Inherited) return false; //if this is an index we need to get the parameter types to help disambiguate @@ -92,9 +93,9 @@ namespace System { // for the current property get the base class of the getter and the setter, they might be different // note that this only works for RuntimeMethodInfo - MethodInfo propAccessor = property.GetGetMethod(true); + MethodInfo propAccessor = property.GetGetMethod(true); - if (propAccessor == null) + if (propAccessor == null) propAccessor = property.GetSetMethod(true); RuntimeMethodInfo rtPropAccessor = propAccessor as RuntimeMethodInfo; @@ -166,25 +167,25 @@ namespace System { if (rtAdd != null) { rtAdd = rtAdd.GetParentDefinition(); - if (rtAdd != null) + if (rtAdd != null) return rtAdd.DeclaringType.GetEvent(ev.Name); } return null; } - private static bool InternalIsDefined (EventInfo element, Type attributeType, bool inherit) + private static bool InternalIsDefined(EventInfo element, Type attributeType, bool inherit) { Contract.Requires(element != null); // walk up the hierarchy chain if (element.IsDefined(attributeType, inherit)) return true; - + if (inherit) { AttributeUsageAttribute usage = InternalGetAttributeUsage(attributeType); - if (!usage.Inherited) + if (!usage.Inherited) return false; EventInfo baseEvent = GetParentDefinition(element); @@ -244,14 +245,14 @@ namespace System { // class inherits from and return the respective ParameterInfo attributes List<Type> disAllowMultiple = new List<Type>(); - Object [] objAttr; + Object[] objAttr; if (type == null) type = typeof(Attribute); - objAttr = param.GetCustomAttributes(type, false); - - for (int i =0;i < objAttr.Length;i++) + objAttr = param.GetCustomAttributes(type, false); + + for (int i = 0; i < objAttr.Length; i++) { Type objType = objAttr[i].GetType(); AttributeUsageAttribute attribUsage = InternalGetAttributeUsage(objType); @@ -260,26 +261,26 @@ namespace System { } // Get all the attributes that have Attribute as the base class - Attribute [] ret = null; - if (objAttr.Length == 0) - ret = CreateAttributeArrayHelper(type,0); - else + Attribute[] ret = null; + if (objAttr.Length == 0) + ret = CreateAttributeArrayHelper(type, 0); + else ret = (Attribute[])objAttr; - + if (param.Member.DeclaringType == null) // This is an interface so we are done. return ret; - - if (!inherit) + + if (!inherit) return ret; ParameterInfo baseParam = GetParentDefinition(param); while (baseParam != null) { - objAttr = baseParam.GetCustomAttributes(type, false); - + objAttr = baseParam.GetCustomAttributes(type, false); + int count = 0; - for (int i =0;i < objAttr.Length;i++) + for (int i = 0; i < objAttr.Length; i++) { Type objType = objAttr[i].GetType(); AttributeUsageAttribute attribUsage = InternalGetAttributeUsage(objType); @@ -295,10 +296,10 @@ namespace System { } // Get all the attributes that have Attribute as the base class - Attribute [] attributes = CreateAttributeArrayHelper(type,count); - + Attribute[] attributes = CreateAttributeArrayHelper(type, count); + count = 0; - for (int i =0;i < objAttr.Length;i++) + for (int i = 0; i < objAttr.Length; i++) { if (objAttr[i] != null) { @@ -306,18 +307,18 @@ namespace System { count++; } } - - Attribute [] temp = ret; - ret = CreateAttributeArrayHelper(type,temp.Length + count); - Array.Copy(temp,ret,temp.Length); - + + Attribute[] temp = ret; + ret = CreateAttributeArrayHelper(type, temp.Length + count); + Array.Copy(temp, ret, temp.Length); + int offset = temp.Length; - for (int i =0;i < attributes.Length;i++) + for (int i = 0; i < attributes.Length; i++) ret[offset + i] = attributes[i]; baseParam = GetParentDefinition(baseParam); - } + } return ret; } @@ -335,7 +336,7 @@ namespace System { if (param.IsDefined(type, false)) return true; - + if (param.Member.DeclaringType == null || !inherit) // This is an interface so we are done. return false; @@ -343,9 +344,9 @@ namespace System { while (baseParam != null) { - Object[] objAttr = baseParam.GetCustomAttributes(type, false); - - for (int i =0; i < objAttr.Length; i++) + Object[] objAttr = baseParam.GetCustomAttributes(type, false); + + for (int i = 0; i < objAttr.Length; i++) { Type objType = objAttr[i].GetType(); AttributeUsageAttribute attribUsage = InternalGetAttributeUsage(objType); @@ -355,7 +356,7 @@ namespace System { } baseParam = GetParentDefinition(baseParam); - } + } return false; } @@ -363,15 +364,15 @@ namespace System { #endregion #region Utility - private static void CopyToArrayList(List<Attribute> attributeList,Attribute[] attributes,Dictionary<Type, AttributeUsageAttribute> types) + private static void CopyToArrayList(List<Attribute> attributeList, Attribute[] attributes, Dictionary<Type, AttributeUsageAttribute> types) { - for (int i = 0; i < attributes.Length; i++) + for (int i = 0; i < attributes.Length; i++) { attributeList.Add(attributes[i]); Type attrType = attributes[i].GetType(); - if (!types.ContainsKey(attrType)) + if (!types.ContainsKey(attrType)) types[attrType] = InternalGetAttributeUsage(attrType); } } @@ -393,21 +394,21 @@ namespace System { return Array.Empty<Type>(); } - private static void AddAttributesToList(List<Attribute> attributeList, Attribute[] attributes, Dictionary<Type, AttributeUsageAttribute> types) + private static void AddAttributesToList(List<Attribute> attributeList, Attribute[] attributes, Dictionary<Type, AttributeUsageAttribute> types) { - for (int i = 0; i < attributes.Length; i++) + for (int i = 0; i < attributes.Length; i++) { Type attrType = attributes[i].GetType(); AttributeUsageAttribute usage = null; types.TryGetValue(attrType, out usage); - if (usage == null) + if (usage == null) { // the type has never been seen before if it's inheritable add it to the list usage = InternalGetAttributeUsage(attrType); types[attrType] = usage; - if (usage.Inherited) + if (usage.Inherited) attributeList.Add(attributes[i]); } else if (usage.Inherited && usage.AllowMultiple) @@ -421,7 +422,7 @@ namespace System { private static AttributeUsageAttribute InternalGetAttributeUsage(Type type) { // Check if the custom attributes is Inheritable - Object [] obj = type.GetCustomAttributes(typeof(AttributeUsageAttribute), false); + Object[] obj = type.GetCustomAttributes(typeof(AttributeUsageAttribute), false); if (obj.Length == 1) return (AttributeUsageAttribute)obj[0]; @@ -430,7 +431,7 @@ namespace System { return AttributeUsageAttribute.Default; throw new FormatException( - Environment.GetResourceString("Format_AttributeUsage", type)); + SR.Format(SR.Format_AttributeUsage, type)); } private static Attribute[] CreateAttributeArrayHelper(Type elementType, int elementCount) @@ -448,7 +449,7 @@ namespace System { { return GetCustomAttributes(element, type, true); } - + public static Attribute[] GetCustomAttributes(MemberInfo element, Type type, bool inherit) { if (element == null) @@ -456,17 +457,17 @@ namespace System { if (type == null) throw new ArgumentNullException(nameof(type)); - + if (!type.IsSubclassOf(typeof(Attribute)) && type != typeof(Attribute)) - throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass")); + throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass); Contract.EndContractBlock(); switch (element.MemberType) { - case MemberTypes.Property: + case MemberTypes.Property: return InternalGetCustomAttributes((PropertyInfo)element, type, inherit); - case MemberTypes.Event: + case MemberTypes.Event: return InternalGetCustomAttributes((EventInfo)element, type, inherit); default: @@ -487,17 +488,17 @@ namespace System { switch (element.MemberType) { - case MemberTypes.Property: + case MemberTypes.Property: return InternalGetCustomAttributes((PropertyInfo)element, typeof(Attribute), inherit); - case MemberTypes.Event: + case MemberTypes.Event: return InternalGetCustomAttributes((EventInfo)element, typeof(Attribute), inherit); default: return element.GetCustomAttributes(typeof(Attribute), inherit) as Attribute[]; } } - + public static bool IsDefined(MemberInfo element, Type attributeType) { return IsDefined(element, attributeType, true); @@ -511,23 +512,22 @@ namespace System { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); - + if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute)) - throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass")); + throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass); Contract.EndContractBlock(); - switch(element.MemberType) + switch (element.MemberType) { - case MemberTypes.Property: + case MemberTypes.Property: return InternalIsDefined((PropertyInfo)element, attributeType, inherit); - case MemberTypes.Event: + case MemberTypes.Event: return InternalIsDefined((EventInfo)element, attributeType, inherit); default: return element.IsDefined(attributeType, inherit); } - } public static Attribute GetCustomAttribute(MemberInfo element, Type attributeType) @@ -545,7 +545,7 @@ namespace System { if (attrib.Length == 1) return attrib[0]; - throw new AmbiguousMatchException(Environment.GetResourceString("RFLCT.AmbigCust")); + throw new AmbiguousMatchException(SR.RFLCT_AmbigCust); } #endregion @@ -555,7 +555,7 @@ namespace System { { return GetCustomAttributes(element, true); } - + public static Attribute[] GetCustomAttributes(ParameterInfo element, Type attributeType) { return (Attribute[])GetCustomAttributes(element, attributeType, true); @@ -568,17 +568,17 @@ namespace System { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); - + if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute)) - throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass")); + throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass); if (element.Member == null) - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidParameterInfo"), nameof(element)); + throw new ArgumentException(SR.Argument_InvalidParameterInfo, nameof(element)); Contract.EndContractBlock(); MemberInfo member = element.Member; - if (member.MemberType == MemberTypes.Method && inherit) + if (member.MemberType == MemberTypes.Method && inherit) return InternalParamGetCustomAttributes(element, attributeType, inherit) as Attribute[]; return element.GetCustomAttributes(attributeType, inherit) as Attribute[]; @@ -590,14 +590,14 @@ namespace System { throw new ArgumentNullException(nameof(element)); if (element.Member == null) - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidParameterInfo"), nameof(element)); + throw new ArgumentException(SR.Argument_InvalidParameterInfo, nameof(element)); Contract.EndContractBlock(); MemberInfo member = element.Member; - if (member.MemberType == MemberTypes.Method && inherit) + if (member.MemberType == MemberTypes.Method && inherit) return InternalParamGetCustomAttributes(element, null, inherit) as Attribute[]; - + return element.GetCustomAttributes(typeof(Attribute), inherit) as Attribute[]; } @@ -614,14 +614,14 @@ namespace System { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); - + if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute)) - throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass")); + throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass); Contract.EndContractBlock(); MemberInfo member = element.Member; - switch(member.MemberType) + switch (member.MemberType) { case MemberTypes.Method: // We need to climb up the member hierarchy return InternalParamIsDefined(element, attributeType, inherit); @@ -632,9 +632,9 @@ namespace System { case MemberTypes.Property: return element.IsDefined(attributeType, false); - default: + default: Debug.Assert(false, "Invalid type for ParameterInfo member in Attribute class"); - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidParamInfo")); + throw new ArgumentException(SR.Argument_InvalidParamInfo); } } @@ -658,7 +658,7 @@ namespace System { if (attrib.Length == 1) return attrib[0]; - throw new AmbiguousMatchException(Environment.GetResourceString("RFLCT.AmbigCust")); + throw new AmbiguousMatchException(SR.RFLCT_AmbigCust); } #endregion @@ -666,7 +666,7 @@ namespace System { #region Module public static Attribute[] GetCustomAttributes(Module element, Type attributeType) { - return GetCustomAttributes (element, attributeType, true); + return GetCustomAttributes(element, attributeType, true); } public static Attribute[] GetCustomAttributes(Module element) @@ -692,7 +692,7 @@ namespace System { throw new ArgumentNullException(nameof(attributeType)); if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute)) - throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass")); + throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass); Contract.EndContractBlock(); return (Attribute[])element.GetCustomAttributes(attributeType, inherit); @@ -713,10 +713,10 @@ namespace System { throw new ArgumentNullException(nameof(attributeType)); if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute)) - throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass")); + throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass); Contract.EndContractBlock(); - return element.IsDefined(attributeType,false); + return element.IsDefined(attributeType, false); } public static Attribute GetCustomAttribute(Module element, Type attributeType) @@ -728,7 +728,7 @@ namespace System { { // Returns an Attribute of base class/inteface attributeType on the Module or null if none exists. // throws an AmbiguousMatchException if there are more than one defined. - Attribute[] attrib = GetCustomAttributes(element,attributeType,inherit); + Attribute[] attrib = GetCustomAttributes(element, attributeType, inherit); if (attrib == null || attrib.Length == 0) return null; @@ -736,7 +736,7 @@ namespace System { if (attrib.Length == 1) return attrib[0]; - throw new AmbiguousMatchException(Environment.GetResourceString("RFLCT.AmbigCust")); + throw new AmbiguousMatchException(SR.RFLCT_AmbigCust); } #endregion @@ -756,7 +756,7 @@ namespace System { throw new ArgumentNullException(nameof(attributeType)); if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute)) - throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass")); + throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass); Contract.EndContractBlock(); return (Attribute[])element.GetCustomAttributes(attributeType, inherit); @@ -776,12 +776,12 @@ namespace System { return (Attribute[])element.GetCustomAttributes(typeof(Attribute), inherit); } - public static bool IsDefined (Assembly element, Type attributeType) + public static bool IsDefined(Assembly element, Type attributeType) { - return IsDefined (element, attributeType, true); + return IsDefined(element, attributeType, true); } - public static bool IsDefined (Assembly element, Type attributeType, bool inherit) + public static bool IsDefined(Assembly element, Type attributeType, bool inherit) { // Returns true is a custom attribute subclass of attributeType class/interface with no inheritance walk if (element == null) @@ -791,7 +791,7 @@ namespace System { throw new ArgumentNullException(nameof(attributeType)); if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute)) - throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass")); + throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass); Contract.EndContractBlock(); return element.IsDefined(attributeType, false); @@ -799,14 +799,14 @@ namespace System { public static Attribute GetCustomAttribute(Assembly element, Type attributeType) { - return GetCustomAttribute (element, attributeType, true); + return GetCustomAttribute(element, attributeType, true); } public static Attribute GetCustomAttribute(Assembly element, Type attributeType, bool inherit) { // Returns an Attribute of base class/inteface attributeType on the Assembly or null if none exists. // throws an AmbiguousMatchException if there are more than one defined. - Attribute[] attrib = GetCustomAttributes(element,attributeType,inherit); + Attribute[] attrib = GetCustomAttributes(element, attributeType, inherit); if (attrib == null || attrib.Length == 0) return null; @@ -814,7 +814,7 @@ namespace System { if (attrib.Length == 1) return attrib[0]; - throw new AmbiguousMatchException(Environment.GetResourceString("RFLCT.AmbigCust")); + throw new AmbiguousMatchException(SR.RFLCT_AmbigCust); } #endregion @@ -945,7 +945,7 @@ namespace System { #region Public Virtual Members public virtual Object TypeId { get { return GetType(); } } - + public virtual bool Match(Object obj) { return Equals(obj); } #endregion diff --git a/src/mscorlib/src/System/AttributeTargets.cs b/src/mscorlib/src/System/AttributeTargets.cs deleted file mode 100644 index fdfa4ab730..0000000000 --- a/src/mscorlib/src/System/AttributeTargets.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// - -namespace System -{ - // Enum used to indicate all the elements of the - // VOS it is valid to attach this element to. - [Flags] - [Serializable] - public enum AttributeTargets - { - Assembly = 0x0001, - Module = 0x0002, - Class = 0x0004, - Struct = 0x0008, - Enum = 0x0010, - Constructor = 0x0020, - Method = 0x0040, - Property = 0x0080, - Field = 0x0100, - Event = 0x0200, - Interface = 0x0400, - Parameter = 0x0800, - Delegate = 0x1000, - ReturnValue = 0x2000, - GenericParameter = 0x4000, - - All = Assembly | Module | Class | Struct | Enum | Constructor | - Method | Property | Field | Event | Interface | Parameter | - Delegate | ReturnValue | GenericParameter - } -} diff --git a/src/mscorlib/src/System/AttributeUsageAttribute.cs b/src/mscorlib/src/System/AttributeUsageAttribute.cs deleted file mode 100644 index 33f7fd805e..0000000000 --- a/src/mscorlib/src/System/AttributeUsageAttribute.cs +++ /dev/null @@ -1,56 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -/*============================================================ -** -** -** -** Purpose: The class denotes how to specify the usage of an attribute -** -** -===========================================================*/ -namespace System { - - using System.Reflection; - /* By default, attributes are inherited and multiple attributes are not allowed */ -[Serializable] - [AttributeUsage(AttributeTargets.Class, Inherited = true)] - public sealed class AttributeUsageAttribute : Attribute - { - internal AttributeTargets m_attributeTarget = AttributeTargets.All; // Defaults to all - internal bool m_allowMultiple = false; // Defaults to false - internal bool m_inherited = true; // Defaults to true - - internal static AttributeUsageAttribute Default = new AttributeUsageAttribute(AttributeTargets.All); - - //Constructors - public AttributeUsageAttribute(AttributeTargets validOn) { - m_attributeTarget = validOn; - } - internal AttributeUsageAttribute(AttributeTargets validOn, bool allowMultiple, bool inherited) { - m_attributeTarget = validOn; - m_allowMultiple = allowMultiple; - m_inherited = inherited; - } - - - //Properties - public AttributeTargets ValidOn - { - get{ return m_attributeTarget; } - } - - public bool AllowMultiple - { - get { return m_allowMultiple; } - set { m_allowMultiple = value; } - } - - public bool Inherited - { - get { return m_inherited; } - set { m_inherited = value; } - } - } -} diff --git a/src/mscorlib/src/System/BCLDebug.cs b/src/mscorlib/src/System/BCLDebug.cs index 7556b85789..67f7c9a0f7 100644 --- a/src/mscorlib/src/System/BCLDebug.cs +++ b/src/mscorlib/src/System/BCLDebug.cs @@ -11,8 +11,8 @@ ** ============================================================*/ -namespace System { - +namespace System +{ using System.IO; using System.Text; using System.Runtime.Remoting; @@ -24,28 +24,32 @@ namespace System { using System.Diagnostics.Contracts; [Serializable] - internal enum LogLevel { - Trace = 0, + internal enum LogLevel + { + Trace = 0, Status = 20, - Warning= 40, - Error = 50, - Panic = 100, + Warning = 40, + Error = 50, + Panic = 100, } - internal struct SwitchStructure { + internal struct SwitchStructure + { internal String name; - internal int value; - - internal SwitchStructure (String n, int v) { + internal int value; + + internal SwitchStructure(String n, int v) + { name = n; value = v; } } - + // Only statics, does not need to be marked with the serializable attribute - internal static class BCLDebug { - internal static volatile bool m_registryChecked=false; + internal static class BCLDebug + { + internal static volatile bool m_registryChecked = false; internal static volatile bool m_loggingNotEnabled = false; internal static bool m_perfWarnings; internal static bool m_correctnessWarnings; @@ -54,7 +58,7 @@ namespace System { internal static volatile bool m_domainUnloadAdded; #endif - static readonly SwitchStructure[] switches = { + private static readonly SwitchStructure[] switches = { new SwitchStructure("NLS", 0x00000001), new SwitchStructure("SER", 0x00000002), new SwitchStructure("DYNIL",0x00000004), @@ -64,14 +68,14 @@ namespace System { new SwitchStructure("REMOTINGCHANNELS",0x00000040), new SwitchStructure("CACHE",0x00000080), new SwitchStructure("RESMGRFILEFORMAT", 0x00000100), // .resources files - new SwitchStructure("PERF", 0x00000200), - new SwitchStructure("CORRECTNESS", 0x00000400), - new SwitchStructure("MEMORYFAILPOINT", 0x00000800), + new SwitchStructure("PERF", 0x00000200), + new SwitchStructure("CORRECTNESS", 0x00000400), + new SwitchStructure("MEMORYFAILPOINT", 0x00000800), new SwitchStructure("DATETIME", 0x00001000), // System.DateTime managed tracing new SwitchStructure("INTEROP", 0x00002000), // Interop tracing }; - static readonly LogLevel[] levelConversions = { + private static readonly LogLevel[] levelConversions = { LogLevel.Panic, LogLevel.Error, LogLevel.Error, @@ -89,24 +93,28 @@ namespace System { #if _DEBUG internal static void WaitForFinalizers(Object sender, EventArgs e) { - if (!m_registryChecked) { + if (!m_registryChecked) + { CheckRegistry(); } - if (m_correctnessWarnings) { + if (m_correctnessWarnings) + { GC.GetTotalMemory(true); GC.WaitForPendingFinalizers(); } } #endif [Conditional("_DEBUG")] - static public void Assert(bool condition) { + static public void Assert(bool condition) + { #if _DEBUG Assert(condition, "Assert failed."); #endif } [Conditional("_DEBUG")] - static public void Assert(bool condition, String message) { + static public void Assert(bool condition, String message) + { #if _DEBUG // Speed up debug builds marginally by avoiding the garbage from // concatinating "BCL Assert: " and the message. @@ -114,13 +122,15 @@ namespace System { System.Diagnostics.Assert.Check(condition, "BCL Assert", message); #endif } - + [Pure] [Conditional("_LOGGING")] - static public void Log(String message) { + static public void Log(String message) + { if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize()) return; - if (!m_registryChecked) { + if (!m_registryChecked) + { CheckRegistry(); } System.Diagnostics.Log.Trace(message); @@ -129,23 +139,29 @@ namespace System { [Pure] [Conditional("_LOGGING")] - static public void Log(String switchName, String message) { + static public void Log(String switchName, String message) + { if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize()) return; - if (!m_registryChecked) { + if (!m_registryChecked) + { CheckRegistry(); } - try { + try + { LogSwitch ls; ls = LogSwitch.GetSwitch(switchName); - if (ls!=null) { - System.Diagnostics.Log.Trace(ls,message); - System.Diagnostics.Log.Trace(ls,Environment.NewLine); + if (ls != null) + { + System.Diagnostics.Log.Trace(ls, message); + System.Diagnostics.Log.Trace(ls, Environment.NewLine); } - } catch { + } + catch + { System.Diagnostics.Log.Trace("Exception thrown in logging." + Environment.NewLine); - System.Diagnostics.Log.Trace("Switch was: " + ((switchName==null)?"<null>":switchName) + Environment.NewLine); - System.Diagnostics.Log.Trace("Message was: " + ((message==null)?"<null>":message) + Environment.NewLine); + System.Diagnostics.Log.Trace("Switch was: " + ((switchName == null) ? "<null>" : switchName) + Environment.NewLine); + System.Diagnostics.Log.Trace("Message was: " + ((message == null) ? "<null>" : message) + Environment.NewLine); } } @@ -156,38 +172,46 @@ namespace System { [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern static int GetRegistryLoggingValues(out bool loggingEnabled, out bool logToConsole, out int logLevel, out bool perfWarnings, out bool correctnessWarnings, out bool safeHandleStackTraces); - private static void CheckRegistry() { + private static void CheckRegistry() + { if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize()) return; - if (m_registryChecked) { + if (m_registryChecked) + { return; } - + m_registryChecked = true; bool loggingEnabled; bool logToConsole; - int logLevel; - int facilityValue; + int logLevel; + int facilityValue; facilityValue = GetRegistryLoggingValues(out loggingEnabled, out logToConsole, out logLevel, out m_perfWarnings, out m_correctnessWarnings, out m_safeHandleStackTraces); // Note we can get into some recursive situations where we call // ourseves recursively through the .cctor. That's why we have the // check for levelConversions == null. - if (!loggingEnabled) { + if (!loggingEnabled) + { m_loggingNotEnabled = true; } - if (loggingEnabled && levelConversions!=null) { - try { + if (loggingEnabled && levelConversions != null) + { + try + { //The values returned for the logging levels in the registry don't map nicely onto the //values which we support internally (which are an approximation of the ones that //the System.Diagnostics namespace uses) so we have a quick map. - Assert(logLevel>=0 && logLevel<=10, "logLevel>=0 && logLevel<=10"); + Assert(logLevel >= 0 && logLevel <= 10, "logLevel>=0 && logLevel<=10"); logLevel = (int)levelConversions[logLevel]; - - if (facilityValue>0) { - for (int i=0; i<switches.Length; i++) { - if ((switches[i].value & facilityValue)!=0) { + + if (facilityValue > 0) + { + for (int i = 0; i < switches.Length; i++) + { + if ((switches[i].value & facilityValue) != 0) + { LogSwitch L = new LogSwitch(switches[i].name, switches[i].name, System.Diagnostics.Log.GlobalSwitch); L.MinimumLevel = (LoggingLevels)logLevel; } @@ -195,65 +219,80 @@ namespace System { System.Diagnostics.Log.GlobalSwitch.MinimumLevel = (LoggingLevels)logLevel; System.Diagnostics.Log.IsConsoleEnabled = logToConsole; } - - } catch { + } + catch + { //Silently eat any exceptions. } } } - internal static bool CheckEnabled(String switchName) { + internal static bool CheckEnabled(String switchName) + { if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize()) return false; if (!m_registryChecked) CheckRegistry(); LogSwitch logSwitch = LogSwitch.GetSwitch(switchName); - if (logSwitch==null) { + if (logSwitch == null) + { return false; } - return ((int)logSwitch.MinimumLevel<=(int)LogLevel.Trace); + return ((int)logSwitch.MinimumLevel <= (int)LogLevel.Trace); } - private static bool CheckEnabled(String switchName, LogLevel level, out LogSwitch logSwitch) { + private static bool CheckEnabled(String switchName, LogLevel level, out LogSwitch logSwitch) + { if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize()) { logSwitch = null; return false; } logSwitch = LogSwitch.GetSwitch(switchName); - if (logSwitch==null) { + if (logSwitch == null) + { return false; } - return ((int)logSwitch.MinimumLevel<=(int)level); + return ((int)logSwitch.MinimumLevel <= (int)level); } [Pure] [Conditional("_LOGGING")] - public static void Log(String switchName, LogLevel level, params Object[]messages) { + public static void Log(String switchName, LogLevel level, params Object[] messages) + { if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize()) return; //Add code to check if logging is enabled in the registry. LogSwitch logSwitch; - if (!m_registryChecked) { + if (!m_registryChecked) + { CheckRegistry(); } - if (!CheckEnabled(switchName, level, out logSwitch)) { + if (!CheckEnabled(switchName, level, out logSwitch)) + { return; } StringBuilder sb = StringBuilderCache.Acquire(); - for (int i=0; i<messages.Length; i++) { + for (int i = 0; i < messages.Length; i++) + { String s; - try { - if (messages[i]==null) { + try + { + if (messages[i] == null) + { s = "<null>"; - } else { + } + else + { s = messages[i].ToString(); } - } catch { + } + catch + { s = "<unable to convert>"; } sb.Append(s); @@ -263,13 +302,16 @@ namespace System { [Pure] [Conditional("_LOGGING")] - public static void Trace(String switchName, String format, params Object[] messages) { - if (m_loggingNotEnabled) { + public static void Trace(String switchName, String format, params Object[] messages) + { + if (m_loggingNotEnabled) + { return; } LogSwitch logSwitch; - if (!CheckEnabled(switchName, LogLevel.Trace, out logSwitch)) { + if (!CheckEnabled(switchName, LogLevel.Trace, out logSwitch)) + { return; } @@ -292,8 +334,9 @@ namespace System { if (!m_perfWarnings) return; - if (!expr) { - Log("PERF", "BCL Perf Warning: "+msg); + if (!expr) + { + Log("PERF", "BCL Perf Warning: " + msg); } System.Diagnostics.Assert.Check(expr, "BCL Perf Warning: Your perf may be less than perfect because...", msg); } @@ -313,13 +356,15 @@ namespace System { if (!m_correctnessWarnings) return; - if (!m_domainUnloadAdded) { + if (!m_domainUnloadAdded) + { m_domainUnloadAdded = true; AppDomain.CurrentDomain.DomainUnload += new EventHandler(WaitForFinalizers); } - if (!expr) { - Log("CORRECTNESS", "BCL Correctness Warning: "+msg); + if (!expr) + { + Log("CORRECTNESS", "BCL Correctness Warning: " + msg); } System.Diagnostics.Assert.Check(expr, "BCL Correctness Warning: Your program may not work because...", msg); #endif @@ -327,8 +372,10 @@ namespace System { // Whether SafeHandles include a stack trace showing where they // were allocated. Only useful in checked & debug builds. - internal static bool SafeHandleStackTracesEnabled { - get { + internal static bool SafeHandleStackTracesEnabled + { + get + { #if _DEBUG if (!m_registryChecked) CheckRegistry(); diff --git a/src/mscorlib/src/System/BadImageFormatException.cs b/src/mscorlib/src/System/BadImageFormatException.cs index 51a6c40771..42005cccce 100644 --- a/src/mscorlib/src/System/BadImageFormatException.cs +++ b/src/mscorlib/src/System/BadImageFormatException.cs @@ -11,8 +11,8 @@ ** ===========================================================*/ -namespace System { - +namespace System +{ using System; using System.Runtime.Serialization; using FileLoadException = System.IO.FileLoadException; @@ -20,41 +20,46 @@ namespace System { using System.Globalization; [Serializable] - public class BadImageFormatException : SystemException { - + public class BadImageFormatException : SystemException + { private String _fileName; // The name of the corrupt PE file. private String _fusionLog; // fusion log (when applicable) - public BadImageFormatException() - : base(Environment.GetResourceString("Arg_BadImageFormatException")) { - SetErrorCode(__HResults.COR_E_BADIMAGEFORMAT); + public BadImageFormatException() + : base(SR.Arg_BadImageFormatException) + { + HResult = __HResults.COR_E_BADIMAGEFORMAT; } - - public BadImageFormatException(String message) - : base(message) { - SetErrorCode(__HResults.COR_E_BADIMAGEFORMAT); + + public BadImageFormatException(String message) + : base(message) + { + HResult = __HResults.COR_E_BADIMAGEFORMAT; } - - public BadImageFormatException(String message, Exception inner) - : base(message, inner) { - SetErrorCode(__HResults.COR_E_BADIMAGEFORMAT); + + public BadImageFormatException(String message, Exception inner) + : base(message, inner) + { + HResult = __HResults.COR_E_BADIMAGEFORMAT; } public BadImageFormatException(String message, String fileName) : base(message) { - SetErrorCode(__HResults.COR_E_BADIMAGEFORMAT); + HResult = __HResults.COR_E_BADIMAGEFORMAT; _fileName = fileName; } - public BadImageFormatException(String message, String fileName, Exception inner) - : base(message, inner) { - SetErrorCode(__HResults.COR_E_BADIMAGEFORMAT); + public BadImageFormatException(String message, String fileName, Exception inner) + : base(message, inner) + { + HResult = __HResults.COR_E_BADIMAGEFORMAT; _fileName = fileName; } public override String Message { - get { + get + { SetMessageField(); return _message; } @@ -62,17 +67,19 @@ namespace System { private void SetMessageField() { - if (_message == null) { + if (_message == null) + { if ((_fileName == null) && (HResult == System.__HResults.COR_E_EXCEPTION)) - _message = Environment.GetResourceString("Arg_BadImageFormatException"); + _message = SR.Arg_BadImageFormatException; else _message = FileLoadException.FormatFileLoadExceptionMessage(_fileName, HResult); } } - public String FileName { + public String FileName + { get { return _fileName; } } @@ -81,8 +88,8 @@ namespace System { String s = GetType().FullName + ": " + Message; if (_fileName != null && _fileName.Length != 0) - s += Environment.NewLine + Environment.GetResourceString("IO.FileName_Name", _fileName); - + s += Environment.NewLine + SR.Format(SR.IO_FileName_Name, _fileName); + if (InnerException != null) s = s + " ---> " + InnerException.ToString(); @@ -90,23 +97,23 @@ namespace System { s += Environment.NewLine + StackTrace; try { - if(FusionLog!=null) + if (FusionLog != null) { - if (s==null) - s=" "; - s+=Environment.NewLine; - s+=Environment.NewLine; - s+=FusionLog; + if (s == null) + s = " "; + s += Environment.NewLine; + s += Environment.NewLine; + s += FusionLog; } } - catch(SecurityException) + catch (SecurityException) { - } return s; } - protected BadImageFormatException(SerializationInfo info, StreamingContext context) : base(info, context) { + protected BadImageFormatException(SerializationInfo info, StreamingContext context) : base(info, context) + { // Base class constructor will check info != null. _fileName = info.GetString("BadImageFormat_FileName"); @@ -114,7 +121,7 @@ namespace System { { _fusionLog = info.GetString("BadImageFormat_FusionLog"); } - catch + catch { _fusionLog = null; } @@ -123,19 +130,21 @@ namespace System { private BadImageFormatException(String fileName, String fusionLog, int hResult) : base(null) { - SetErrorCode(hResult); + HResult = hResult; _fileName = fileName; - _fusionLog=fusionLog; + _fusionLog = fusionLog; SetMessageField(); } - public String FusionLog { + public String FusionLog + { #pragma warning disable CS0618 // Type or member is obsolete #pragma warning restore CS0618 // Type or member is obsolete get { return _fusionLog; } } - public override void GetObjectData(SerializationInfo info, StreamingContext context) { + public override void GetObjectData(SerializationInfo info, StreamingContext context) + { // Serialize data for our base classes. base will verify info != null. base.GetObjectData(info, context); diff --git a/src/mscorlib/src/System/BitConverter.cs b/src/mscorlib/src/System/BitConverter.cs index 07af5a8178..a17a067bec 100644 --- a/src/mscorlib/src/System/BitConverter.cs +++ b/src/mscorlib/src/System/BitConverter.cs @@ -2,31 +2,19 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -/*============================================================ -** -** -** -** Purpose: Allows developers to view the base data types as -** an arbitrary array of bits. -** -** -===========================================================*/ -namespace System { - - using System; - using System.Runtime.CompilerServices; - using System.Diagnostics; - using System.Diagnostics.Contracts; - using System.Security; +using System.Diagnostics; +using System.Diagnostics.Contracts; +using System.Runtime.CompilerServices; +using System.Security; +namespace System +{ // The BitConverter class contains methods for // converting an array of bytes to one of the base data // types, as well as for converting a base data type to an // array of bytes. - // - // Only statics, does not need to be marked with the serializable attribute - public static class BitConverter { - + public static class BitConverter + { // This field indicates the "endianess" of the architecture. // The value is set to true if the architecture is // little endian; false if it is big endian. @@ -36,378 +24,299 @@ namespace System { public static readonly bool IsLittleEndian = true; #endif - // Converts a byte into an array of bytes with length one. - public static byte[] GetBytes(bool value) { + // Converts a Boolean into an array of bytes with length one. + public static byte[] GetBytes(bool value) + { Contract.Ensures(Contract.Result<byte[]>() != null); Contract.Ensures(Contract.Result<byte[]>().Length == 1); byte[] r = new byte[1]; - r[0] = (value ? (byte)Boolean.True : (byte)Boolean.False ); + r[0] = (value ? (byte)1 : (byte)0); return r; } - + // Converts a char into an array of bytes with length two. public static byte[] GetBytes(char value) { Contract.Ensures(Contract.Result<byte[]>() != null); - Contract.Ensures(Contract.Result<byte[]>().Length == 2); + Contract.Ensures(Contract.Result<byte[]>().Length == sizeof(char)); - return GetBytes((short)value); + byte[] bytes = new byte[sizeof(char)]; + Unsafe.As<byte, char>(ref bytes[0]) = value; + return bytes; } - + // Converts a short into an array of bytes with length // two. - public unsafe static byte[] GetBytes(short value) + public static byte[] GetBytes(short value) { Contract.Ensures(Contract.Result<byte[]>() != null); - Contract.Ensures(Contract.Result<byte[]>().Length == 2); + Contract.Ensures(Contract.Result<byte[]>().Length == sizeof(short)); - byte[] bytes = new byte[2]; - fixed(byte* b = &bytes[0]) - *((short*)b) = value; + byte[] bytes = new byte[sizeof(short)]; + Unsafe.As<byte, short>(ref bytes[0]) = value; return bytes; } // Converts an int into an array of bytes with length // four. - public unsafe static byte[] GetBytes(int value) + public static byte[] GetBytes(int value) { Contract.Ensures(Contract.Result<byte[]>() != null); - Contract.Ensures(Contract.Result<byte[]>().Length == 4); + Contract.Ensures(Contract.Result<byte[]>().Length == sizeof(int)); - byte[] bytes = new byte[4]; - fixed(byte* b = &bytes[0]) - *((int*)b) = value; + byte[] bytes = new byte[sizeof(int)]; + Unsafe.As<byte, int>(ref bytes[0]) = value; return bytes; } - + // Converts a long into an array of bytes with length // eight. - public unsafe static byte[] GetBytes(long value) + public static byte[] GetBytes(long value) { Contract.Ensures(Contract.Result<byte[]>() != null); - Contract.Ensures(Contract.Result<byte[]>().Length == 8); + Contract.Ensures(Contract.Result<byte[]>().Length == sizeof(long)); - byte[] bytes = new byte[8]; - fixed(byte* b = &bytes[0]) - *((long*)b) = value; + byte[] bytes = new byte[sizeof(long)]; + Unsafe.As<byte, long>(ref bytes[0]) = value; return bytes; } - + // Converts an ushort into an array of bytes with // length two. [CLSCompliant(false)] - public static byte[] GetBytes(ushort value) { + public static byte[] GetBytes(ushort value) + { Contract.Ensures(Contract.Result<byte[]>() != null); - Contract.Ensures(Contract.Result<byte[]>().Length == 2); + Contract.Ensures(Contract.Result<byte[]>().Length == sizeof(ushort)); - return GetBytes((short)value); + byte[] bytes = new byte[sizeof(ushort)]; + Unsafe.As<byte, ushort>(ref bytes[0]) = value; + return bytes; } - + // Converts an uint into an array of bytes with // length four. [CLSCompliant(false)] - public static byte[] GetBytes(uint value) { + public static byte[] GetBytes(uint value) + { Contract.Ensures(Contract.Result<byte[]>() != null); - Contract.Ensures(Contract.Result<byte[]>().Length == 4); + Contract.Ensures(Contract.Result<byte[]>().Length == sizeof(uint)); - return GetBytes((int)value); + byte[] bytes = new byte[sizeof(uint)]; + Unsafe.As<byte, uint>(ref bytes[0]) = value; + return bytes; } - + // Converts an unsigned long into an array of bytes with // length eight. [CLSCompliant(false)] - public static byte[] GetBytes(ulong value) { + public static byte[] GetBytes(ulong value) + { Contract.Ensures(Contract.Result<byte[]>() != null); - Contract.Ensures(Contract.Result<byte[]>().Length == 8); + Contract.Ensures(Contract.Result<byte[]>().Length == sizeof(ulong)); - return GetBytes((long)value); + byte[] bytes = new byte[sizeof(ulong)]; + Unsafe.As<byte, ulong>(ref bytes[0]) = value; + return bytes; } - + // Converts a float into an array of bytes with length // four. - public unsafe static byte[] GetBytes(float value) + public static byte[] GetBytes(float value) { Contract.Ensures(Contract.Result<byte[]>() != null); - Contract.Ensures(Contract.Result<byte[]>().Length == 4); + Contract.Ensures(Contract.Result<byte[]>().Length == sizeof(float)); - return GetBytes(*(int*)&value); + byte[] bytes = new byte[sizeof(float)]; + Unsafe.As<byte, float>(ref bytes[0]) = value; + return bytes; } - + // Converts a double into an array of bytes with length // eight. - public unsafe static byte[] GetBytes(double value) + public static byte[] GetBytes(double value) { Contract.Ensures(Contract.Result<byte[]>() != null); - Contract.Ensures(Contract.Result<byte[]>().Length == 8); + Contract.Ensures(Contract.Result<byte[]>().Length == sizeof(double)); - return GetBytes(*(long*)&value); + byte[] bytes = new byte[sizeof(double)]; + Unsafe.As<byte, double>(ref bytes[0]) = value; + return bytes; } // Converts an array of bytes into a char. - public static char ToChar(byte[] value, int startIndex) + public static char ToChar(byte[] value, int startIndex) => unchecked((char)ReadInt16(value, startIndex)); + + private static short ReadInt16(byte[] value, int startIndex) { - if (value == null) { + if (value == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); - } - - if ((uint)startIndex >= value.Length) { - ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); - } - - if (startIndex > value.Length - 2) { - ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); - } + if (unchecked((uint)startIndex) >= unchecked((uint)value.Length)) + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); + if (startIndex > value.Length - sizeof(short)) + ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall, ExceptionArgument.value); Contract.EndContractBlock(); - return (char)ToInt16(value, startIndex); + return Unsafe.ReadUnaligned<short>(ref value[startIndex]); } - - // Converts an array of bytes into a short. - public static unsafe short ToInt16(byte[] value, int startIndex) { - if( value == null) { + + private static int ReadInt32(byte[] value, int startIndex) + { + if (value == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); - } - - if ((uint) startIndex >= value.Length) { - ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); - } - - if (startIndex > value.Length -2) { - ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); - } + if (unchecked((uint)startIndex) >= unchecked((uint)value.Length)) + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); + if (startIndex > value.Length - sizeof(int)) + ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall, ExceptionArgument.value); Contract.EndContractBlock(); - fixed( byte * pbyte = &value[startIndex]) { - if( startIndex % 2 == 0) { // data is aligned - return *((short *) pbyte); - } - else { - if( IsLittleEndian) { - return (short)((*pbyte) | (*(pbyte + 1) << 8)) ; - } - else { - return (short)((*pbyte << 8) | (*(pbyte + 1))); - } - } - } - + return Unsafe.ReadUnaligned<int>(ref value[startIndex]); } - - // Converts an array of bytes into an int. - public static unsafe int ToInt32 (byte[] value, int startIndex) { - if( value == null) { + + private static long ReadInt64(byte[] value, int startIndex) + { + if (value == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); - } - - if ((uint) startIndex >= value.Length) { - ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); - } - - if (startIndex > value.Length -4) { - ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); - } + if (unchecked((uint)startIndex) >= unchecked((uint)value.Length)) + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); + if (startIndex > value.Length - sizeof(long)) + ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall, ExceptionArgument.value); Contract.EndContractBlock(); - fixed( byte * pbyte = &value[startIndex]) { - if( startIndex % 4 == 0) { // data is aligned - return *((int *) pbyte); - } - else { - if( IsLittleEndian) { - return (*pbyte) | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24); - } - else { - return (*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3)); - } - } - } + return Unsafe.ReadUnaligned<long>(ref value[startIndex]); } - + + // Converts an array of bytes into a short. + public static short ToInt16(byte[] value, int startIndex) => ReadInt16(value, startIndex); + + // Converts an array of bytes into an int. + public static int ToInt32(byte[] value, int startIndex) => ReadInt32(value, startIndex); + // Converts an array of bytes into a long. - public static unsafe long ToInt64 (byte[] value, int startIndex) { - if (value == null) { - ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); - } - - if ((uint) startIndex >= value.Length) { - ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); - } - - if (startIndex > value.Length -8) { - ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); - } - Contract.EndContractBlock(); + public static long ToInt64(byte[] value, int startIndex) => ReadInt64(value, startIndex); - fixed( byte * pbyte = &value[startIndex]) { - if( startIndex % 8 == 0) { // data is aligned - return *((long *) pbyte); - } - else { - if( IsLittleEndian) { - int i1 = (*pbyte) | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24); - int i2 = (*(pbyte+4)) | (*(pbyte + 5) << 8) | (*(pbyte + 6) << 16) | (*(pbyte + 7) << 24); - return (uint)i1 | ((long)i2 << 32); - } - else { - int i1 = (*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3)); - int i2 = (*(pbyte+4) << 24) | (*(pbyte + 5) << 16) | (*(pbyte + 6) << 8) | (*(pbyte + 7)); - return (uint)i2 | ((long)i1 << 32); - } - } - } - } - - // Converts an array of bytes into an ushort. // [CLSCompliant(false)] - public static ushort ToUInt16(byte[] value, int startIndex) - { - if (value == null) - ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); - if ((uint)startIndex >= value.Length) - ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); - if (startIndex > value.Length - 2) - ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); - Contract.EndContractBlock(); + public static ushort ToUInt16(byte[] value, int startIndex) => unchecked((ushort)ReadInt16(value, startIndex)); - return (ushort)ToInt16(value, startIndex); - } - // Converts an array of bytes into an uint. // [CLSCompliant(false)] - public static uint ToUInt32(byte[] value, int startIndex) - { - if (value == null) - ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); - if ((uint)startIndex >= value.Length) - ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); - if (startIndex > value.Length - 4) - ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); - Contract.EndContractBlock(); + public static uint ToUInt32(byte[] value, int startIndex) => unchecked((uint)ReadInt32(value, startIndex)); - return (uint)ToInt32(value, startIndex); - } - // Converts an array of bytes into an unsigned long. // [CLSCompliant(false)] - public static ulong ToUInt64(byte[] value, int startIndex) - { - if (value == null) - ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); - if ((uint)startIndex >= value.Length) - ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); - if (startIndex > value.Length - 8) - ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); - Contract.EndContractBlock(); + public static ulong ToUInt64(byte[] value, int startIndex) => unchecked((ulong)ReadInt64(value, startIndex)); - return (ulong)ToInt64(value, startIndex); - } - // Converts an array of bytes into a float. - unsafe public static float ToSingle (byte[] value, int startIndex) + public static unsafe float ToSingle(byte[] value, int startIndex) { - if (value == null) - ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); - if ((uint)startIndex >= value.Length) - ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); - if (startIndex > value.Length - 4) - ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); - Contract.EndContractBlock(); - - int val = ToInt32(value, startIndex); + int val = ReadInt32(value, startIndex); return *(float*)&val; } - + // Converts an array of bytes into a double. - unsafe public static double ToDouble (byte[] value, int startIndex) + public static unsafe double ToDouble(byte[] value, int startIndex) { - if (value == null) - ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); - if ((uint)startIndex >= value.Length) - ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); - if (startIndex > value.Length - 8) - ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); - Contract.EndContractBlock(); - - long val = ToInt64(value, startIndex); + long val = ReadInt64(value, startIndex); return *(double*)&val; } - - private static char GetHexValue(int i) { - Debug.Assert( i >=0 && i <16, "i is out of range."); - if (i<10) { + + private static char GetHexValue(int i) + { + Debug.Assert(i >= 0 && i < 16, "i is out of range."); + if (i < 10) + { return (char)(i + '0'); } - + return (char)(i - 10 + 'A'); } // Converts an array of bytes into a String. - public static String ToString (byte[] value, int startIndex, int length) { - if (value == null) { - throw new ArgumentNullException(nameof(value)); - } - - if (startIndex < 0 || startIndex >= value.Length && startIndex > 0) { // Don't throw for a 0 length array. - throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_StartIndex")); - } - - if (length < 0) { - throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive")); - } - - if (startIndex > value.Length - length) { - throw new ArgumentException(Environment.GetResourceString("Arg_ArrayPlusOffTooSmall")); - } + public static string ToString(byte[] value, int startIndex, int length) + { + if (value == null) + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); + if (startIndex < 0 || startIndex >= value.Length && startIndex > 0) + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);; + if (length < 0) + throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_GenericPositive); + if (startIndex > value.Length - length) + ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall, ExceptionArgument.value); Contract.EndContractBlock(); - if (length == 0) { + if (length == 0) + { return string.Empty; } - if (length > (Int32.MaxValue / 3)) { + if (length > (int.MaxValue / 3)) + { // (Int32.MaxValue / 3) == 715,827,882 Bytes == 699 MB - throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_LengthTooLarge", (Int32.MaxValue / 3))); + throw new ArgumentOutOfRangeException(nameof(length), SR.Format(SR.ArgumentOutOfRange_LengthTooLarge, (int.MaxValue / 3))); } int chArrayLength = length * 3; - - char[] chArray = new char[chArrayLength]; - int i = 0; - int index = startIndex; - for (i = 0; i < chArrayLength; i += 3) { - byte b = value[index++]; - chArray[i]= GetHexValue(b/16); - chArray[i+1] = GetHexValue(b%16); - chArray[i+2] = '-'; + const int StackLimit = 512; // arbitrary limit to switch from stack to heap allocation + unsafe + { + if (chArrayLength < StackLimit) + { + char* chArrayPtr = stackalloc char[chArrayLength]; + return ToString(value, startIndex, length, chArrayPtr, chArrayLength); + } + else + { + char[] chArray = new char[chArrayLength]; + fixed (char* chArrayPtr = &chArray[0]) + return ToString(value, startIndex, length, chArrayPtr, chArrayLength); + } + } + } + + private static unsafe string ToString(byte[] value, int startIndex, int length, char* chArray, int chArrayLength) + { + Debug.Assert(length > 0); + Debug.Assert(chArrayLength == length * 3); + + char* p = chArray; + int endIndex = startIndex + length; + for (int i = startIndex; i < endIndex; i++) + { + byte b = value[i]; + *p++ = GetHexValue(b >> 4); + *p++ = GetHexValue(b & 0xF); + *p++ = '-'; } // We don't need the last '-' character - return new String(chArray, 0, chArray.Length - 1); + return new string(chArray, 0, chArrayLength - 1); } - + // Converts an array of bytes into a String. - public static String ToString(byte [] value) { + public static string ToString(byte[] value) + { if (value == null) - throw new ArgumentNullException(nameof(value)); - Contract.Ensures(Contract.Result<String>() != null); + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); + Contract.Ensures(Contract.Result<string>() != null); Contract.EndContractBlock(); return ToString(value, 0, value.Length); } - + // Converts an array of bytes into a String. - public static String ToString (byte [] value, int startIndex) { + public static string ToString(byte[] value, int startIndex) + { if (value == null) - throw new ArgumentNullException(nameof(value)); - Contract.Ensures(Contract.Result<String>() != null); + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); + Contract.Ensures(Contract.Result<string>() != null); Contract.EndContractBlock(); return ToString(value, startIndex, value.Length - startIndex); } - + /*==================================ToBoolean=================================== **Action: Convert an array of bytes to a boolean value. We treat this array ** as if the first 4 bytes were an Int4 an operate on this value. @@ -417,31 +326,36 @@ namespace System { **Exceptions: See ToInt4. ==============================================================================*/ // Converts an array of bytes into a boolean. - public static bool ToBoolean(byte[] value, int startIndex) { - if (value==null) - throw new ArgumentNullException(nameof(value)); + public static bool ToBoolean(byte[] value, int startIndex) + { + if (value == null) + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); if (startIndex < 0) - throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);; if (startIndex > value.Length - 1) - throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index")); + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);; // differs from other overloads, which throw base ArgumentException Contract.EndContractBlock(); - - return (value[startIndex]==0)?false:true; + + return value[startIndex] != 0; } - public static unsafe long DoubleToInt64Bits(double value) { - return *((long *)&value); + public static unsafe long DoubleToInt64Bits(double value) + { + return *((long*)&value); } - public static unsafe double Int64BitsToDouble(long value) { + public static unsafe double Int64BitsToDouble(long value) + { return *((double*)&value); } - public static unsafe int SingleToInt32Bits(float value) { + public static unsafe int SingleToInt32Bits(float value) + { return *((int*)&value); } - public static unsafe float Int32BitsToSingle(int value) { + public static unsafe float Int32BitsToSingle(int value) + { return *((float*)&value); } } diff --git a/src/mscorlib/src/System/Boolean.cs b/src/mscorlib/src/System/Boolean.cs index c085b0a020..fe25e22920 100644 --- a/src/mscorlib/src/System/Boolean.cs +++ b/src/mscorlib/src/System/Boolean.cs @@ -11,105 +11,113 @@ ** ** ===========================================================*/ -namespace System { - - using System; - using System.Globalization; - using System.Diagnostics.Contracts; + +using System; +using System.Globalization; +using System.Diagnostics.Contracts; + +namespace System +{ // The Boolean class provides the // object representation of the boolean primitive type. [Serializable] - public struct Boolean : IComparable, IConvertible, IComparable<Boolean>, IEquatable<Boolean> + public struct Boolean : IComparable, IConvertible, IComparable<Boolean>, IEquatable<Boolean> { - - // - // Member Variables - // - private bool m_value; - - // The true value. - // - internal const int True = 1; - - // The false value. - // - internal const int False = 0; - - - // - // Internal Constants are real consts for performance. - // - - // The internal string representation of true. - // - internal const String TrueLiteral = "True"; - - // The internal string representation of false. - // - internal const String FalseLiteral = "False"; - - - // - // Public Constants - // - - // The public string representation of true. - // - public static readonly String TrueString = TrueLiteral; - - // The public string representation of false. - // - public static readonly String FalseString = FalseLiteral; - - // - // Overriden Instance Methods - // - /*=================================GetHashCode================================== - **Args: None - **Returns: 1 or 0 depending on whether this instance represents true or false. - **Exceptions: None - **Overriden From: Value - ==============================================================================*/ - // Provides a hash code for this instance. - public override int GetHashCode() { - return (m_value)?True:False; - } - - /*===================================ToString=================================== - **Args: None - **Returns: "True" or "False" depending on the state of the boolean. - **Exceptions: None. - ==============================================================================*/ - // Converts the boolean value of this instance to a String. - public override String ToString() { - if (false == m_value) { - return FalseLiteral; + // + // Member Variables + // + private bool m_value; + + // The true value. + // + internal const int True = 1; + + // The false value. + // + internal const int False = 0; + + + // + // Internal Constants are real consts for performance. + // + + // The internal string representation of true. + // + internal const String TrueLiteral = "True"; + + // The internal string representation of false. + // + internal const String FalseLiteral = "False"; + + + // + // Public Constants + // + + // The public string representation of true. + // + public static readonly String TrueString = TrueLiteral; + + // The public string representation of false. + // + public static readonly String FalseString = FalseLiteral; + + // + // Overriden Instance Methods + // + /*=================================GetHashCode================================== + **Args: None + **Returns: 1 or 0 depending on whether this instance represents true or false. + **Exceptions: None + **Overriden From: Value + ==============================================================================*/ + // Provides a hash code for this instance. + public override int GetHashCode() + { + return (m_value) ? True : False; } - return TrueLiteral; - } - public String ToString(IFormatProvider provider) { - if (false == m_value) { - return FalseLiteral; + /*===================================ToString=================================== + **Args: None + **Returns: "True" or "False" depending on the state of the boolean. + **Exceptions: None. + ==============================================================================*/ + // Converts the boolean value of this instance to a String. + public override String ToString() + { + if (false == m_value) + { + return FalseLiteral; + } + return TrueLiteral; } - return TrueLiteral; - } - - // Determines whether two Boolean objects are equal. - public override bool Equals (Object obj) { - //If it's not a boolean, we're definitely not equal - if (!(obj is Boolean)) { - return false; + + public String ToString(IFormatProvider provider) + { + if (false == m_value) + { + return FalseLiteral; + } + return TrueLiteral; } - - return (m_value==((Boolean)obj).m_value); - } - [System.Runtime.Versioning.NonVersionable] - public bool Equals(Boolean obj) - { - return m_value == obj; - } + // Determines whether two Boolean objects are equal. + public override bool Equals(Object obj) + { + //If it's not a boolean, we're definitely not equal + if (!(obj is Boolean)) + { + return false; + } + + return (m_value == ((Boolean)obj).m_value); + } + + [System.Runtime.Versioning.NonVersionable] + public bool Equals(Boolean obj) + { + return m_value == obj; + } // Compares this object to another object, returning an integer that // indicates the relationship. For booleans, false sorts before true. @@ -118,63 +126,80 @@ namespace System { // // Returns a value less than zero if this object // - public int CompareTo(Object obj) { - if (obj==null) { + public int CompareTo(Object obj) + { + if (obj == null) + { return 1; } - if (!(obj is Boolean)) { - throw new ArgumentException (Environment.GetResourceString("Arg_MustBeBoolean")); + if (!(obj is Boolean)) + { + throw new ArgumentException(SR.Arg_MustBeBoolean); } - - if (m_value==((Boolean)obj).m_value) { + + if (m_value == ((Boolean)obj).m_value) + { return 0; - } else if (m_value==false) { + } + else if (m_value == false) + { return -1; } return 1; } - public int CompareTo(Boolean value) { - if (m_value==value) { + public int CompareTo(Boolean value) + { + if (m_value == value) + { return 0; - } else if (m_value==false) { + } + else if (m_value == false) + { return -1; } - return 1; + return 1; } - + // // Static Methods // - + // Determines whether a String represents true or false. // - public static Boolean Parse (String value) { - if (value==null) throw new ArgumentNullException(nameof(value)); + public static Boolean Parse(String value) + { + if (value == null) throw new ArgumentNullException(nameof(value)); Contract.EndContractBlock(); Boolean result = false; - if (!TryParse(value, out result)) { - throw new FormatException(Environment.GetResourceString("Format_BadBoolean")); + if (!TryParse(value, out result)) + { + throw new FormatException(SR.Format_BadBoolean); } - else { + else + { return result; } } // Determines whether a String represents true or false. // - public static Boolean TryParse (String value, out Boolean result) { + public static Boolean TryParse(String value, out Boolean result) + { result = false; - if (value==null) { + if (value == null) + { return false; } // For perf reasons, let's first see if they're equal, then do the // trim to get rid of white space, and check again. - if (TrueLiteral.Equals(value, StringComparison.OrdinalIgnoreCase)) { + if (TrueLiteral.Equals(value, StringComparison.OrdinalIgnoreCase)) + { result = true; return true; } - if (FalseLiteral.Equals(value,StringComparison.OrdinalIgnoreCase)) { + if (FalseLiteral.Equals(value, StringComparison.OrdinalIgnoreCase)) + { result = false; return true; } @@ -182,122 +207,130 @@ namespace System { // Special case: Trim whitespace as well as null characters. value = TrimWhiteSpaceAndNull(value); - if (TrueLiteral.Equals(value, StringComparison.OrdinalIgnoreCase)) { + if (TrueLiteral.Equals(value, StringComparison.OrdinalIgnoreCase)) + { result = true; return true; } - - if (FalseLiteral.Equals(value,StringComparison.OrdinalIgnoreCase)) { + + if (FalseLiteral.Equals(value, StringComparison.OrdinalIgnoreCase)) + { result = false; return true; } - + return false; } - private static String TrimWhiteSpaceAndNull(String value) { + private static String TrimWhiteSpaceAndNull(String value) + { int start = 0; - int end = value.Length-1; - char nullChar = (char) 0x0000; + int end = value.Length - 1; + char nullChar = (char)0x0000; - while (start < value.Length) { - if (!Char.IsWhiteSpace(value[start]) && value[start] != nullChar) { + while (start < value.Length) + { + if (!Char.IsWhiteSpace(value[start]) && value[start] != nullChar) + { break; } start++; } - while (end >= start) { - if (!Char.IsWhiteSpace(value[end]) && value[end] != nullChar) { + while (end >= start) + { + if (!Char.IsWhiteSpace(value[end]) && value[end] != nullChar) + { break; } - end--; + end--; } return value.Substring(start, end - start + 1); - } + } // // IConvertible implementation // - - public TypeCode GetTypeCode() { + + public TypeCode GetTypeCode() + { return TypeCode.Boolean; } - /// <internalonly/> - bool IConvertible.ToBoolean(IFormatProvider provider) { + bool IConvertible.ToBoolean(IFormatProvider provider) + { return m_value; } - /// <internalonly/> - char IConvertible.ToChar(IFormatProvider provider) { - throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Boolean", "Char")); + char IConvertible.ToChar(IFormatProvider provider) + { + throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Boolean", "Char")); } - /// <internalonly/> - sbyte IConvertible.ToSByte(IFormatProvider provider) { + sbyte IConvertible.ToSByte(IFormatProvider provider) + { return Convert.ToSByte(m_value); } - /// <internalonly/> - byte IConvertible.ToByte(IFormatProvider provider) { + byte IConvertible.ToByte(IFormatProvider provider) + { return Convert.ToByte(m_value); } - /// <internalonly/> - short IConvertible.ToInt16(IFormatProvider provider) { + short IConvertible.ToInt16(IFormatProvider provider) + { return Convert.ToInt16(m_value); } - /// <internalonly/> - ushort IConvertible.ToUInt16(IFormatProvider provider) { + ushort IConvertible.ToUInt16(IFormatProvider provider) + { return Convert.ToUInt16(m_value); } - /// <internalonly/> - int IConvertible.ToInt32(IFormatProvider provider) { + int IConvertible.ToInt32(IFormatProvider provider) + { return Convert.ToInt32(m_value); } - /// <internalonly/> - uint IConvertible.ToUInt32(IFormatProvider provider) { + uint IConvertible.ToUInt32(IFormatProvider provider) + { return Convert.ToUInt32(m_value); } - /// <internalonly/> - long IConvertible.ToInt64(IFormatProvider provider) { + long IConvertible.ToInt64(IFormatProvider provider) + { return Convert.ToInt64(m_value); } - /// <internalonly/> - ulong IConvertible.ToUInt64(IFormatProvider provider) { + ulong IConvertible.ToUInt64(IFormatProvider provider) + { return Convert.ToUInt64(m_value); } - /// <internalonly/> - float IConvertible.ToSingle(IFormatProvider provider) { + float IConvertible.ToSingle(IFormatProvider provider) + { return Convert.ToSingle(m_value); } - /// <internalonly/> - double IConvertible.ToDouble(IFormatProvider provider) { + double IConvertible.ToDouble(IFormatProvider provider) + { return Convert.ToDouble(m_value); } - /// <internalonly/> - Decimal IConvertible.ToDecimal(IFormatProvider provider) { + Decimal IConvertible.ToDecimal(IFormatProvider provider) + { return Convert.ToDecimal(m_value); } - /// <internalonly/> - DateTime IConvertible.ToDateTime(IFormatProvider provider) { - throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Boolean", "DateTime")); + DateTime IConvertible.ToDateTime(IFormatProvider provider) + { + throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Boolean", "DateTime")); } - /// <internalonly/> - Object IConvertible.ToType(Type type, IFormatProvider provider) { + Object IConvertible.ToType(Type type, IFormatProvider provider) + { return Convert.DefaultToType((IConvertible)this, type, provider); } } diff --git a/src/mscorlib/src/System/Buffer.cs b/src/mscorlib/src/System/Buffer.cs index 662b240b34..92b938df8c 100644 --- a/src/mscorlib/src/System/Buffer.cs +++ b/src/mscorlib/src/System/Buffer.cs @@ -2,10 +2,14 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System { - +#if AMD64 || (BIT32 && !ARM) +#define HAS_CUSTOM_BLOCKS +#endif + +namespace System +{ //Only contains static methods. Does not require serialization - + using System; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; @@ -57,7 +61,7 @@ namespace System { if (count == 0) return -1; else if (*pByte == value) - return (int) (pByte - src); + return (int)(pByte - src); count--; pByte++; @@ -87,7 +91,7 @@ namespace System { if (t1 != 0) { // We've found a match for value, figure out which position it's in. - int foundIndex = (int) (pByte - src); + int foundIndex = (int)(pByte - src); if (pByte[0] == value) return foundIndex; else if (pByte[1] == value) @@ -100,14 +104,13 @@ namespace System { count -= 4; pByte += 4; - } // Catch any bytes that might be left at the tail of the buffer while (count > 0) { if (*pByte == value) - return (int) (pByte - src); + return (int)(pByte - src); count--; pByte++; @@ -116,7 +119,7 @@ namespace System { // If we don't have a match return -1; return -1; } - + // Returns a bool to indicate if the array is of primitive data types // or not. [MethodImplAttribute(MethodImplOptions.InternalCall)] @@ -139,7 +142,7 @@ namespace System { // Is it of primitive types? if (!IsPrimitiveTypeArray(array)) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBePrimArray"), nameof(array)); + throw new ArgumentException(SR.Arg_MustBePrimArray, nameof(array)); // Is the index in valid range of the array? if (index < 0 || index >= _ByteLength(array)) @@ -165,7 +168,7 @@ namespace System { // Is it of primitive types? if (!IsPrimitiveTypeArray(array)) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBePrimArray"), nameof(array)); + throw new ArgumentException(SR.Arg_MustBePrimArray, nameof(array)); // Is the index in valid range of the array? if (index < 0 || index >= _ByteLength(array)) @@ -175,7 +178,7 @@ namespace System { _SetByte(array, index, value); } - + // Gets a particular byte out of the array. The array must be an // array of primitives. // @@ -193,38 +196,41 @@ namespace System { // Is it of primitive types? if (!IsPrimitiveTypeArray(array)) - throw new ArgumentException(Environment.GetResourceString("Arg_MustBePrimArray"), nameof(array)); + throw new ArgumentException(SR.Arg_MustBePrimArray, nameof(array)); return _ByteLength(array); } internal unsafe static void ZeroMemory(byte* src, long len) { - while(len-- > 0) + while (len-- > 0) *(src + len) = 0; } - internal unsafe static void Memcpy(byte[] dest, int destIndex, byte* src, int srcIndex, int len) { - Debug.Assert( (srcIndex >= 0) && (destIndex >= 0) && (len >= 0), "Index and length must be non-negative!"); + internal unsafe static void Memcpy(byte[] dest, int destIndex, byte* src, int srcIndex, int len) + { + 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) + if (len == 0) return; - fixed(byte* pDest = dest) { + fixed (byte* pDest = dest) + { Memcpy(pDest + destIndex, src + srcIndex, len); } } internal unsafe static void Memcpy(byte* pDest, int destIndex, byte[] src, int srcIndex, int len) { - Debug.Assert( (srcIndex >= 0) && (destIndex >= 0) && (len >= 0), "Index and length must be non-negative!"); + 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) + if (len == 0) return; - fixed(byte* pSrc = src) { + fixed (byte* pSrc = src) + { Memcpy(pDest + destIndex, pSrc + srcIndex, len); } } @@ -244,7 +250,8 @@ namespace System { internal unsafe static extern void Memcpy(byte* dest, byte* src, int len); #else // ARM [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - internal unsafe static void Memcpy(byte* dest, byte* src, int len) { + internal unsafe static void Memcpy(byte* dest, byte* src, int len) + { Debug.Assert(len >= 0, "Negative length in memcopy!"); Memmove(dest, src, (uint)len); } @@ -253,327 +260,175 @@ namespace System { // This method has different signature for x64 and other platforms and is done for performance reasons. internal unsafe static void Memmove(byte* dest, byte* src, nuint len) { - // P/Invoke into the native version when the buffers are overlapping and the copy needs to be performed backwards - // This check can produce false positives for lengths greater than Int32.MaxInt. It is fine because we want to use PInvoke path for the large lengths anyway. +#if AMD64 || (BIT32 && !ARM) + const nuint CopyThreshold = 2048; +#else + const nuint CopyThreshold = 512; +#endif // AMD64 || (BIT32 && !ARM) - if ((nuint)dest - (nuint)src < len) goto PInvoke; + // P/Invoke into the native version when the buffers are overlapping. - // This is portable version of memcpy. It mirrors what the hand optimized assembly versions of memcpy typically do. - // - // Ideally, we would just use the cpblk IL instruction here. Unfortunately, cpblk IL instruction is not as efficient as - // possible yet and so we have this implementation here for now. + if (((nuint)dest - (nuint)src < len) || ((nuint)src - (nuint)dest < len)) goto PInvoke; - // Note: It's important that this switch handles lengths at least up to 22. - // See notes below near the main loop for why. + byte* srcEnd = src + len; + byte* destEnd = dest + len; - // The switch will be very fast since it can be implemented using a jump - // table in assembly. See http://stackoverflow.com/a/449297/4077294 for more info. + if (len <= 16) goto MCPY02; + if (len > 64) goto MCPY05; - switch (len) - { - case 0: - return; - case 1: - *dest = *src; - return; - case 2: - *(short*)dest = *(short*)src; - return; - case 3: - *(short*)dest = *(short*)src; - *(dest + 2) = *(src + 2); - return; - case 4: - *(int*)dest = *(int*)src; - return; - case 5: - *(int*)dest = *(int*)src; - *(dest + 4) = *(src + 4); - return; - case 6: - *(int*)dest = *(int*)src; - *(short*)(dest + 4) = *(short*)(src + 4); - return; - case 7: - *(int*)dest = *(int*)src; - *(short*)(dest + 4) = *(short*)(src + 4); - *(dest + 6) = *(src + 6); - return; - case 8: -#if BIT64 - *(long*)dest = *(long*)src; -#else - *(int*)dest = *(int*)src; - *(int*)(dest + 4) = *(int*)(src + 4); -#endif - return; - case 9: -#if BIT64 - *(long*)dest = *(long*)src; -#else - *(int*)dest = *(int*)src; - *(int*)(dest + 4) = *(int*)(src + 4); -#endif - *(dest + 8) = *(src + 8); - return; - case 10: -#if BIT64 - *(long*)dest = *(long*)src; -#else - *(int*)dest = *(int*)src; - *(int*)(dest + 4) = *(int*)(src + 4); -#endif - *(short*)(dest + 8) = *(short*)(src + 8); - return; - case 11: -#if BIT64 - *(long*)dest = *(long*)src; -#else - *(int*)dest = *(int*)src; - *(int*)(dest + 4) = *(int*)(src + 4); -#endif - *(short*)(dest + 8) = *(short*)(src + 8); - *(dest + 10) = *(src + 10); - return; - case 12: -#if BIT64 - *(long*)dest = *(long*)src; -#else - *(int*)dest = *(int*)src; - *(int*)(dest + 4) = *(int*)(src + 4); -#endif - *(int*)(dest + 8) = *(int*)(src + 8); - return; - case 13: -#if BIT64 - *(long*)dest = *(long*)src; -#else - *(int*)dest = *(int*)src; - *(int*)(dest + 4) = *(int*)(src + 4); -#endif - *(int*)(dest + 8) = *(int*)(src + 8); - *(dest + 12) = *(src + 12); - return; - case 14: -#if BIT64 - *(long*)dest = *(long*)src; -#else - *(int*)dest = *(int*)src; - *(int*)(dest + 4) = *(int*)(src + 4); -#endif - *(int*)(dest + 8) = *(int*)(src + 8); - *(short*)(dest + 12) = *(short*)(src + 12); - return; - case 15: -#if BIT64 - *(long*)dest = *(long*)src; -#else - *(int*)dest = *(int*)src; - *(int*)(dest + 4) = *(int*)(src + 4); -#endif - *(int*)(dest + 8) = *(int*)(src + 8); - *(short*)(dest + 12) = *(short*)(src + 12); - *(dest + 14) = *(src + 14); - return; - case 16: -#if BIT64 - *(long*)dest = *(long*)src; - *(long*)(dest + 8) = *(long*)(src + 8); -#else - *(int*)dest = *(int*)src; - *(int*)(dest + 4) = *(int*)(src + 4); - *(int*)(dest + 8) = *(int*)(src + 8); - *(int*)(dest + 12) = *(int*)(src + 12); -#endif - return; - case 17: -#if BIT64 - *(long*)dest = *(long*)src; - *(long*)(dest + 8) = *(long*)(src + 8); -#else - *(int*)dest = *(int*)src; - *(int*)(dest + 4) = *(int*)(src + 4); - *(int*)(dest + 8) = *(int*)(src + 8); - *(int*)(dest + 12) = *(int*)(src + 12); -#endif - *(dest + 16) = *(src + 16); - return; - case 18: -#if BIT64 - *(long*)dest = *(long*)src; - *(long*)(dest + 8) = *(long*)(src + 8); + MCPY00: + // Copy bytes which are multiples of 16 and leave the remainder for MCPY01 to handle. + Debug.Assert(len > 16 && len <= 64); +#if HAS_CUSTOM_BLOCKS + *(Block16*)dest = *(Block16*)src; // [0,16] +#elif BIT64 + *(long*)dest = *(long*)src; + *(long*)(dest + 8) = *(long*)(src + 8); // [0,16] #else - *(int*)dest = *(int*)src; - *(int*)(dest + 4) = *(int*)(src + 4); - *(int*)(dest + 8) = *(int*)(src + 8); - *(int*)(dest + 12) = *(int*)(src + 12); + *(int*)dest = *(int*)src; + *(int*)(dest + 4) = *(int*)(src + 4); + *(int*)(dest + 8) = *(int*)(src + 8); + *(int*)(dest + 12) = *(int*)(src + 12); // [0,16] #endif - *(short*)(dest + 16) = *(short*)(src + 16); - return; - case 19: -#if BIT64 - *(long*)dest = *(long*)src; - *(long*)(dest + 8) = *(long*)(src + 8); + if (len <= 32) goto MCPY01; +#if HAS_CUSTOM_BLOCKS + *(Block16*)(dest + 16) = *(Block16*)(src + 16); // [0,32] +#elif BIT64 + *(long*)(dest + 16) = *(long*)(src + 16); + *(long*)(dest + 24) = *(long*)(src + 24); // [0,32] #else - *(int*)dest = *(int*)src; - *(int*)(dest + 4) = *(int*)(src + 4); - *(int*)(dest + 8) = *(int*)(src + 8); - *(int*)(dest + 12) = *(int*)(src + 12); + *(int*)(dest + 16) = *(int*)(src + 16); + *(int*)(dest + 20) = *(int*)(src + 20); + *(int*)(dest + 24) = *(int*)(src + 24); + *(int*)(dest + 28) = *(int*)(src + 28); // [0,32] #endif - *(short*)(dest + 16) = *(short*)(src + 16); - *(dest + 18) = *(src + 18); - return; - case 20: -#if BIT64 - *(long*)dest = *(long*)src; - *(long*)(dest + 8) = *(long*)(src + 8); + if (len <= 48) goto MCPY01; +#if HAS_CUSTOM_BLOCKS + *(Block16*)(dest + 32) = *(Block16*)(src + 32); // [0,48] +#elif BIT64 + *(long*)(dest + 32) = *(long*)(src + 32); + *(long*)(dest + 40) = *(long*)(src + 40); // [0,48] #else - *(int*)dest = *(int*)src; - *(int*)(dest + 4) = *(int*)(src + 4); - *(int*)(dest + 8) = *(int*)(src + 8); - *(int*)(dest + 12) = *(int*)(src + 12); + *(int*)(dest + 32) = *(int*)(src + 32); + *(int*)(dest + 36) = *(int*)(src + 36); + *(int*)(dest + 40) = *(int*)(src + 40); + *(int*)(dest + 44) = *(int*)(src + 44); // [0,48] #endif - *(int*)(dest + 16) = *(int*)(src + 16); - return; - case 21: -#if BIT64 - *(long*)dest = *(long*)src; - *(long*)(dest + 8) = *(long*)(src + 8); + + MCPY01: + // Unconditionally copy the last 16 bytes using destEnd and srcEnd and return. + Debug.Assert(len > 16 && len <= 64); +#if HAS_CUSTOM_BLOCKS + *(Block16*)(destEnd - 16) = *(Block16*)(srcEnd - 16); +#elif BIT64 + *(long*)(destEnd - 16) = *(long*)(srcEnd - 16); + *(long*)(destEnd - 8) = *(long*)(srcEnd - 8); #else - *(int*)dest = *(int*)src; - *(int*)(dest + 4) = *(int*)(src + 4); - *(int*)(dest + 8) = *(int*)(src + 8); - *(int*)(dest + 12) = *(int*)(src + 12); + *(int*)(destEnd - 16) = *(int*)(srcEnd - 16); + *(int*)(destEnd - 12) = *(int*)(srcEnd - 12); + *(int*)(destEnd - 8) = *(int*)(srcEnd - 8); + *(int*)(destEnd - 4) = *(int*)(srcEnd - 4); #endif - *(int*)(dest + 16) = *(int*)(src + 16); - *(dest + 20) = *(src + 20); - return; - case 22: + return; + + MCPY02: + // Copy the first 8 bytes and then unconditionally copy the last 8 bytes and return. + if ((len & 24) == 0) goto MCPY03; + Debug.Assert(len >= 8 && len <= 16); #if BIT64 - *(long*)dest = *(long*)src; - *(long*)(dest + 8) = *(long*)(src + 8); + *(long*)dest = *(long*)src; + *(long*)(destEnd - 8) = *(long*)(srcEnd - 8); #else - *(int*)dest = *(int*)src; - *(int*)(dest + 4) = *(int*)(src + 4); - *(int*)(dest + 8) = *(int*)(src + 8); - *(int*)(dest + 12) = *(int*)(src + 12); + *(int*)dest = *(int*)src; + *(int*)(dest + 4) = *(int*)(src + 4); + *(int*)(destEnd - 8) = *(int*)(srcEnd - 8); + *(int*)(destEnd - 4) = *(int*)(srcEnd - 4); #endif - *(int*)(dest + 16) = *(int*)(src + 16); - *(short*)(dest + 20) = *(short*)(src + 20); - return; - } - - // P/Invoke into the native version for large lengths - if (len >= 512) goto PInvoke; - - nuint i = 0; // byte offset at which we're copying + return; - if (((int)dest & 3) != 0) - { - if (((int)dest & 1) != 0) - { - *(dest + i) = *(src + i); - i += 1; - if (((int)dest & 2) != 0) - goto IntAligned; - } - *(short*)(dest + i) = *(short*)(src + i); - i += 2; - } + MCPY03: + // Copy the first 4 bytes and then unconditionally copy the last 4 bytes and return. + if ((len & 4) == 0) goto MCPY04; + Debug.Assert(len >= 4 && len < 8); + *(int*)dest = *(int*)src; + *(int*)(destEnd - 4) = *(int*)(srcEnd - 4); + return; - IntAligned: + MCPY04: + // Copy the first byte. For pending bytes, do an unconditionally copy of the last 2 bytes and return. + Debug.Assert(len < 4); + if (len == 0) return; + *dest = *src; + if ((len & 2) == 0) return; + *(short*)(destEnd - 2) = *(short*)(srcEnd - 2); + return; -#if BIT64 - // On 64-bit IntPtr.Size == 8, so we want to advance to the next 8-aligned address. If - // (int)dest % 8 is 0, 5, 6, or 7, we will already have advanced by 0, 3, 2, or 1 - // bytes to the next aligned address (respectively), so do nothing. On the other hand, - // if it is 1, 2, 3, or 4 we will want to copy-and-advance another 4 bytes until - // we're aligned. - // The thing 1, 2, 3, and 4 have in common that the others don't is that if you - // subtract one from them, their 3rd lsb will not be set. Hence, the below check. - - if ((((int)dest - 1) & 4) == 0) + MCPY05: + // PInvoke to the native version when the copy length exceeds the threshold. + if (len > CopyThreshold) { - *(int*)(dest + i) = *(int*)(src + i); - i += 4; + goto PInvoke; } -#endif // BIT64 - - nuint end = len - 16; - len -= i; // lower 4 bits of len represent how many bytes are left *after* the unrolled loop - - // 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. - 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 - // a dependency on the writes. - nuint counter; - - do - { - counter = i + 16; - // This loop looks very costly since there appear to be a bunch of temporary values - // being created with the adds, but the jit (for x86 anyways) will convert each of - // these to use memory addressing operands. - - // So the only cost is a bit of code size, which is made up for by the fact that - // we save on writes to dest/src. - -#if BIT64 - *(long*)(dest + i) = *(long*)(src + i); - *(long*)(dest + i + 8) = *(long*)(src + i + 8); + // Copy 64-bytes at a time until the remainder is less than 64. + // If remainder is greater than 16 bytes, then jump to MCPY00. Otherwise, unconditionally copy the last 16 bytes and return. + Debug.Assert(len > 64 && len <= CopyThreshold); + nuint n = len >> 6; + + MCPY06: +#if HAS_CUSTOM_BLOCKS + *(Block64*)dest = *(Block64*)src; +#elif BIT64 + *(long*)dest = *(long*)src; + *(long*)(dest + 8) = *(long*)(src + 8); + *(long*)(dest + 16) = *(long*)(src + 16); + *(long*)(dest + 24) = *(long*)(src + 24); + *(long*)(dest + 32) = *(long*)(src + 32); + *(long*)(dest + 40) = *(long*)(src + 40); + *(long*)(dest + 48) = *(long*)(src + 48); + *(long*)(dest + 56) = *(long*)(src + 56); #else - *(int*)(dest + i) = *(int*)(src + i); - *(int*)(dest + i + 4) = *(int*)(src + i + 4); - *(int*)(dest + i + 8) = *(int*)(src + i + 8); - *(int*)(dest + i + 12) = *(int*)(src + i + 12); + *(int*)dest = *(int*)src; + *(int*)(dest + 4) = *(int*)(src + 4); + *(int*)(dest + 8) = *(int*)(src + 8); + *(int*)(dest + 12) = *(int*)(src + 12); + *(int*)(dest + 16) = *(int*)(src + 16); + *(int*)(dest + 20) = *(int*)(src + 20); + *(int*)(dest + 24) = *(int*)(src + 24); + *(int*)(dest + 28) = *(int*)(src + 28); + *(int*)(dest + 32) = *(int*)(src + 32); + *(int*)(dest + 36) = *(int*)(src + 36); + *(int*)(dest + 40) = *(int*)(src + 40); + *(int*)(dest + 44) = *(int*)(src + 44); + *(int*)(dest + 48) = *(int*)(src + 48); + *(int*)(dest + 52) = *(int*)(src + 52); + *(int*)(dest + 56) = *(int*)(src + 56); + *(int*)(dest + 60) = *(int*)(src + 60); #endif - - i = counter; - - // See notes above for why this wasn't used instead - // i += 16; - } - while (counter <= end); - - if ((len & 8) != 0) - { -#if BIT64 - *(long*)(dest + i) = *(long*)(src + i); + dest += 64; + src += 64; + n--; + if (n != 0) goto MCPY06; + + len %= 64; + if (len > 16) goto MCPY00; +#if HAS_CUSTOM_BLOCKS + *(Block16*)(destEnd - 16) = *(Block16*)(srcEnd - 16); +#elif BIT64 + *(long*)(destEnd - 16) = *(long*)(srcEnd - 16); + *(long*)(destEnd - 8) = *(long*)(srcEnd - 8); #else - *(int*)(dest + i) = *(int*)(src + i); - *(int*)(dest + i + 4) = *(int*)(src + i + 4); + *(int*)(destEnd - 16) = *(int*)(srcEnd - 16); + *(int*)(destEnd - 12) = *(int*)(srcEnd - 12); + *(int*)(destEnd - 8) = *(int*)(srcEnd - 8); + *(int*)(destEnd - 4) = *(int*)(srcEnd - 4); #endif - i += 8; - } - if ((len & 4) != 0) - { - *(int*)(dest + i) = *(int*)(src + i); - i += 4; - } - if ((len & 2) != 0) - { - *(short*)(dest + i) = *(short*)(src + i); - i += 2; - } - if ((len & 1) != 0) - { - *(dest + i) = *(src + i); - // We're not using i after this, so not needed - // i += 1; - } - return; PInvoke: _Memmove(dest, src, len); - } - + // Non-inlinable wrapper around the QCall that avoids poluting the fast path // with P/Invoke prolog/epilog. [MethodImplAttribute(MethodImplOptions.NoInlining)] @@ -616,5 +471,13 @@ namespace System { Memmove((byte*)destination, (byte*)source, checked((uint)sourceBytesToCopy)); #endif // BIT64 } + +#if HAS_CUSTOM_BLOCKS + [StructLayout(LayoutKind.Sequential, Size = 16)] + private struct Block16 { } + + [StructLayout(LayoutKind.Sequential, Size = 64)] + private struct Block64 { } +#endif // HAS_CUSTOM_BLOCKS } } diff --git a/src/mscorlib/src/System/Buffers/ArrayPoolEventSource.cs b/src/mscorlib/src/System/Buffers/ArrayPoolEventSource.cs new file mode 100644 index 0000000000..9482744144 --- /dev/null +++ b/src/mscorlib/src/System/Buffers/ArrayPoolEventSource.cs @@ -0,0 +1,78 @@ +// Licensed to the .NET Foundation under one or more agreements. +// 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.Tracing; + +namespace System.Buffers +{ + [EventSource(Name = "System.Buffers.ArrayPoolEventSource")] + internal sealed class ArrayPoolEventSource : EventSource + { + internal readonly static ArrayPoolEventSource Log = new ArrayPoolEventSource(); + + /// <summary>The reason for a BufferAllocated event.</summary> + internal enum BufferAllocatedReason : int + { + /// <summary>The pool is allocating a buffer to be pooled in a bucket.</summary> + Pooled, + /// <summary>The requested buffer size was too large to be pooled.</summary> + OverMaximumSize, + /// <summary>The pool has already allocated for pooling as many buffers of a particular size as it's allowed.</summary> + PoolExhausted + } + + /// <summary> + /// Event for when a buffer is rented. This is invoked once for every successful call to Rent, + /// regardless of whether a buffer is allocated or a buffer is taken from the pool. In a + /// perfect situation where all rented buffers are returned, we expect to see the number + /// of BufferRented events exactly match the number of BuferReturned events, with the number + /// of BufferAllocated events being less than or equal to those numbers (ideally significantly + /// less than). + /// </summary> + [Event(1, Level = EventLevel.Verbose)] + internal unsafe void BufferRented(int bufferId, int bufferSize, int poolId, int bucketId) + { + EventData* payload = stackalloc EventData[4]; + payload[0].Size = sizeof(int); + payload[0].DataPointer = ((IntPtr)(&bufferId)); + payload[1].Size = sizeof(int); + payload[1].DataPointer = ((IntPtr)(&bufferSize)); + payload[2].Size = sizeof(int); + payload[2].DataPointer = ((IntPtr)(&poolId)); + payload[3].Size = sizeof(int); + payload[3].DataPointer = ((IntPtr)(&bucketId)); + WriteEventCore(1, 4, payload); + } + + /// <summary> + /// Event for when a buffer is allocated by the pool. In an ideal situation, the number + /// of BufferAllocated events is significantly smaller than the number of BufferRented and + /// BufferReturned events. + /// </summary> + [Event(2, Level = EventLevel.Informational)] + internal unsafe void BufferAllocated(int bufferId, int bufferSize, int poolId, int bucketId, BufferAllocatedReason reason) + { + EventData* payload = stackalloc EventData[5]; + payload[0].Size = sizeof(int); + payload[0].DataPointer = ((IntPtr)(&bufferId)); + payload[1].Size = sizeof(int); + payload[1].DataPointer = ((IntPtr)(&bufferSize)); + payload[2].Size = sizeof(int); + payload[2].DataPointer = ((IntPtr)(&poolId)); + payload[3].Size = sizeof(int); + payload[3].DataPointer = ((IntPtr)(&bucketId)); + payload[4].Size = sizeof(BufferAllocatedReason); + payload[4].DataPointer = ((IntPtr)(&reason)); + WriteEventCore(2, 5, payload); + } + + /// <summary> + /// Event raised when a buffer is returned to the pool. This event is raised regardless of whether + /// the returned buffer is stored or dropped. In an ideal situation, the number of BufferReturned + /// events exactly matches the number of BufferRented events. + /// </summary> + [Event(3, Level = EventLevel.Verbose)] + internal void BufferReturned(int bufferId, int bufferSize, int poolId) => WriteEvent(3, bufferId, bufferSize, poolId); + } +} diff --git a/src/mscorlib/src/System/Byte.cs b/src/mscorlib/src/System/Byte.cs index 666fdda75b..27fdcd7a64 100644 --- a/src/mscorlib/src/System/Byte.cs +++ b/src/mscorlib/src/System/Byte.cs @@ -12,54 +12,61 @@ ** ===========================================================*/ -namespace System { - - using System; - using System.Globalization; - using System.Runtime.InteropServices; - using System.Diagnostics.Contracts; +using System; +using System.Globalization; +using System.Runtime.InteropServices; +using System.Diagnostics.Contracts; + +namespace System +{ // The Byte class extends the Value class and // provides object representation of the byte primitive type. // -[Serializable] -[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)] + [Serializable] + [System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)] public struct Byte : IComparable, IFormattable, IConvertible - , IComparable<Byte>, IEquatable<Byte> + , IComparable<Byte>, IEquatable<Byte> { private byte m_value; - + // The maximum value that a Byte may represent: 255. public const byte MaxValue = (byte)0xFF; - + // The minimum value that a Byte may represent: 0. public const byte MinValue = 0; - - + + // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type byte, this method throws an ArgumentException. // - public int CompareTo(Object value) { - if (value == null) { + public int CompareTo(Object value) + { + if (value == null) + { return 1; } - if (!(value is Byte)) { - throw new ArgumentException(Environment.GetResourceString("Arg_MustBeByte")); + if (!(value is Byte)) + { + throw new ArgumentException(SR.Arg_MustBeByte); } - + return m_value - (((Byte)value).m_value); } - public int CompareTo(Byte value) { + public int CompareTo(Byte value) + { return m_value - value; } - + // Determines whether two Byte objects are equal. - public override bool Equals(Object obj) { - if (!(obj is Byte)) { + public override bool Equals(Object obj) + { + if (!(obj is Byte)) + { return false; } return m_value == ((Byte)obj).m_value; @@ -72,176 +79,194 @@ namespace System { } // Gets a hash code for this instance. - public override int GetHashCode() { + public override int GetHashCode() + { return m_value; } - + [Pure] - public static byte Parse(String s) { + public static byte Parse(String s) + { return Parse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } - + [Pure] - public static byte Parse(String s, NumberStyles style) { + public static byte Parse(String s, NumberStyles style) + { NumberFormatInfo.ValidateParseStyleInteger(style); return Parse(s, style, NumberFormatInfo.CurrentInfo); } [Pure] - public static byte Parse(String s, IFormatProvider provider) { + public static byte Parse(String s, IFormatProvider provider) + { return Parse(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); } - + // Parses an unsigned byte from a String in the given style. If // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. [Pure] - public static byte Parse(String s, NumberStyles style, IFormatProvider provider) { + public static byte Parse(String s, NumberStyles style, IFormatProvider provider) + { NumberFormatInfo.ValidateParseStyleInteger(style); return Parse(s, style, NumberFormatInfo.GetInstance(provider)); } - - private static byte Parse(String s, NumberStyles style, NumberFormatInfo info) { + + private static byte Parse(String s, NumberStyles style, NumberFormatInfo info) + { int i = 0; - try { + try + { i = Number.ParseInt32(s, style, info); } - catch(OverflowException e) { - throw new OverflowException(Environment.GetResourceString("Overflow_Byte"), e); + catch (OverflowException e) + { + throw new OverflowException(SR.Overflow_Byte, e); } - if (i < MinValue || i > MaxValue) throw new OverflowException(Environment.GetResourceString("Overflow_Byte")); + if (i < MinValue || i > MaxValue) throw new OverflowException(SR.Overflow_Byte); return (byte)i; } - public static bool TryParse(String s, out Byte result) { + public static bool TryParse(String s, out Byte result) + { return TryParse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } - public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out Byte result) { + public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out Byte result) + { NumberFormatInfo.ValidateParseStyleInteger(style); return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result); } - - private static bool TryParse(String s, NumberStyles style, NumberFormatInfo info, out Byte result) { + + private static bool TryParse(String s, NumberStyles style, NumberFormatInfo info, out Byte result) + { result = 0; int i; - if (!Number.TryParseInt32(s, style, info, out i)) { + if (!Number.TryParseInt32(s, style, info, out i)) + { return false; } - if (i < MinValue || i > MaxValue) { + if (i < MinValue || i > MaxValue) + { return false; } - result = (byte) i; + result = (byte)i; return true; } [Pure] - public override String ToString() { + public override String ToString() + { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatInt32(m_value, null, NumberFormatInfo.CurrentInfo); } [Pure] - public String ToString(String format) { + public String ToString(String format) + { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatInt32(m_value, format, NumberFormatInfo.CurrentInfo); } [Pure] - public String ToString(IFormatProvider provider) { + public String ToString(IFormatProvider provider) + { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatInt32(m_value, null, NumberFormatInfo.GetInstance(provider)); } [Pure] - public String ToString(String format, IFormatProvider provider) { + public String ToString(String format, IFormatProvider provider) + { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatInt32(m_value, format, NumberFormatInfo.GetInstance(provider)); } - + // // IConvertible implementation // [Pure] - public TypeCode GetTypeCode() { + public TypeCode GetTypeCode() + { return TypeCode.Byte; } - /// <internalonly/> - bool IConvertible.ToBoolean(IFormatProvider provider) { + bool IConvertible.ToBoolean(IFormatProvider provider) + { return Convert.ToBoolean(m_value); } - /// <internalonly/> - char IConvertible.ToChar(IFormatProvider provider) { + char IConvertible.ToChar(IFormatProvider provider) + { return Convert.ToChar(m_value); } - /// <internalonly/> - sbyte IConvertible.ToSByte(IFormatProvider provider) { + sbyte IConvertible.ToSByte(IFormatProvider provider) + { return Convert.ToSByte(m_value); } - /// <internalonly/> - byte IConvertible.ToByte(IFormatProvider provider) { + byte IConvertible.ToByte(IFormatProvider provider) + { return m_value; } - /// <internalonly/> - short IConvertible.ToInt16(IFormatProvider provider) { + short IConvertible.ToInt16(IFormatProvider provider) + { return Convert.ToInt16(m_value); } - /// <internalonly/> - ushort IConvertible.ToUInt16(IFormatProvider provider) { + ushort IConvertible.ToUInt16(IFormatProvider provider) + { return Convert.ToUInt16(m_value); } - /// <internalonly/> - int IConvertible.ToInt32(IFormatProvider provider) { + int IConvertible.ToInt32(IFormatProvider provider) + { return Convert.ToInt32(m_value); } - /// <internalonly/> - uint IConvertible.ToUInt32(IFormatProvider provider) { + uint IConvertible.ToUInt32(IFormatProvider provider) + { return Convert.ToUInt32(m_value); } - /// <internalonly/> - long IConvertible.ToInt64(IFormatProvider provider) { + long IConvertible.ToInt64(IFormatProvider provider) + { return Convert.ToInt64(m_value); } - /// <internalonly/> - ulong IConvertible.ToUInt64(IFormatProvider provider) { + ulong IConvertible.ToUInt64(IFormatProvider provider) + { return Convert.ToUInt64(m_value); } - /// <internalonly/> - float IConvertible.ToSingle(IFormatProvider provider) { + float IConvertible.ToSingle(IFormatProvider provider) + { return Convert.ToSingle(m_value); } - /// <internalonly/> - double IConvertible.ToDouble(IFormatProvider provider) { + double IConvertible.ToDouble(IFormatProvider provider) + { return Convert.ToDouble(m_value); } - /// <internalonly/> - Decimal IConvertible.ToDecimal(IFormatProvider provider) { + Decimal IConvertible.ToDecimal(IFormatProvider provider) + { return Convert.ToDecimal(m_value); } - /// <internalonly/> - DateTime IConvertible.ToDateTime(IFormatProvider provider) { - throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Byte", "DateTime")); + DateTime IConvertible.ToDateTime(IFormatProvider provider) + { + throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Byte", "DateTime")); } - /// <internalonly/> - Object IConvertible.ToType(Type type, IFormatProvider provider) { + Object IConvertible.ToType(Type type, IFormatProvider provider) + { return Convert.DefaultToType((IConvertible)this, type, provider); } } diff --git a/src/mscorlib/src/System/CLRConfig.cs b/src/mscorlib/src/System/CLRConfig.cs index 16c610b82b..d97922f9b9 100644 --- a/src/mscorlib/src/System/CLRConfig.cs +++ b/src/mscorlib/src/System/CLRConfig.cs @@ -7,8 +7,23 @@ using System.Runtime.Versioning; using System.Runtime.InteropServices; using System.Security; -namespace System { +namespace System +{ + // CLRConfig is mainly reading the config switch values. this is used when we cannot use the AppContext class + // one example, is using the context switch in the globalization code which require to read the switch very + // early even before the appdomain get initialized. + // In general AppContext should be used instead of CLRConfig if there is no reason prevent that. + internal class CLRConfig + { + internal static bool GetBoolValue(string switchName) + { + return GetConfigBoolValue(switchName); + } + [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] + [SuppressUnmanagedCodeSecurity] + private extern static bool GetConfigBoolValue(string configSwitchName); + } } // namespace System // file CLRConfig diff --git a/src/mscorlib/src/System/CLSCompliantAttribute.cs b/src/mscorlib/src/System/CLSCompliantAttribute.cs deleted file mode 100644 index e03600d132..0000000000 --- a/src/mscorlib/src/System/CLSCompliantAttribute.cs +++ /dev/null @@ -1,34 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -/*============================================================================= -** -** -** -** Purpose: Container for assemblies. -** -** -=============================================================================*/ - -namespace System -{ - [Serializable] - [AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = false)] - public sealed class CLSCompliantAttribute : Attribute - { - private bool _compliant; - - public CLSCompliantAttribute(bool isCompliant) - { - _compliant = isCompliant; - } - public bool IsCompliant - { - get - { - return _compliant; - } - } - } -} diff --git a/src/mscorlib/src/System/Char.cs b/src/mscorlib/src/System/Char.cs deleted file mode 100644 index 7fe1c08715..0000000000 --- a/src/mscorlib/src/System/Char.cs +++ /dev/null @@ -1,1000 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -/*============================================================ -** -** -** -** Purpose: This is the value class representing a Unicode character -** Char methods until we create this functionality. -** -** -===========================================================*/ -namespace System { - - using System; - using System.Globalization; - using System.Runtime; - using System.Runtime.InteropServices; - using System.Runtime.CompilerServices; - using System.Diagnostics; - using System.Diagnostics.Contracts; - -[Serializable] -[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)] public struct Char : IComparable, IConvertible - , IComparable<Char>, IEquatable<Char> - { - // - // Member Variables - // - internal char m_value; - - // - // Public Constants - // - // The maximum character value. - public const char MaxValue = (char) 0xFFFF; - // The minimum character value. - public const char MinValue = (char) 0x00; - - // Unicode category values from Unicode U+0000 ~ U+00FF. Store them in byte[] array to save space. - private readonly static byte[] categoryForLatin1 = { - (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0000 - 0007 - (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0008 - 000F - (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0010 - 0017 - (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0018 - 001F - (byte)UnicodeCategory.SpaceSeparator, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, // 0020 - 0027 - (byte)UnicodeCategory.OpenPunctuation, (byte)UnicodeCategory.ClosePunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.DashPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, // 0028 - 002F - (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, // 0030 - 0037 - (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.OtherPunctuation, // 0038 - 003F - (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 0040 - 0047 - (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 0048 - 004F - (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 0050 - 0057 - (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.OpenPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.ClosePunctuation, (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.ConnectorPunctuation, // 0058 - 005F - (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 0060 - 0067 - (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 0068 - 006F - (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 0070 - 0077 - (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.OpenPunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.ClosePunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.Control, // 0078 - 007F - (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0080 - 0087 - (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0088 - 008F - (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0090 - 0097 - (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0098 - 009F - (byte)UnicodeCategory.SpaceSeparator, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.OtherSymbol, // 00A0 - 00A7 - (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.InitialQuotePunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.DashPunctuation, (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.ModifierSymbol, // 00A8 - 00AF - (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.OtherPunctuation, // 00B0 - 00B7 - (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.FinalQuotePunctuation, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.OtherPunctuation, // 00B8 - 00BF - (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 00C0 - 00C7 - (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 00C8 - 00CF - (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.MathSymbol, // 00D0 - 00D7 - (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 00D8 - 00DF - (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 00E0 - 00E7 - (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 00E8 - 00EF - (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.MathSymbol, // 00F0 - 00F7 - (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 00F8 - 00FF - }; - - // Return true for all characters below or equal U+00ff, which is ASCII + Latin-1 Supplement. - private static bool IsLatin1(char ch) { - return (ch <= '\x00ff'); - } - - // Return true for all characters below or equal U+007f, which is ASCII. - private static bool IsAscii(char ch) { - return (ch <= '\x007f'); - } - - // Return the Unicode category for Unicode character <= 0x00ff. - private static UnicodeCategory GetLatin1UnicodeCategory(char ch) { - Debug.Assert(IsLatin1(ch), "Char.GetLatin1UnicodeCategory(): ch should be <= 007f"); - return (UnicodeCategory)(categoryForLatin1[(int)ch]); - } - - // - // Private Constants - // - - // - // Overriden Instance Methods - // - - // Calculate a hashcode for a 2 byte Unicode character. - public override int GetHashCode() { - return (int)m_value | ((int)m_value << 16); - } - - // Used for comparing two boxed Char objects. - // - public override bool Equals(Object obj) { - if (!(obj is Char)) { - return false; - } - return (m_value==((Char)obj).m_value); - } - - [System.Runtime.Versioning.NonVersionable] - public bool Equals(Char obj) - { - return m_value == obj; - } - - // Compares this object to another object, returning an integer that - // indicates the relationship. - // Returns a value less than zero if this object - // null is considered to be less than any instance. - // If object is not of type Char, this method throws an ArgumentException. - // - [Pure] - public int CompareTo(Object value) { - if (value==null) { - return 1; - } - if (!(value is Char)) { - throw new ArgumentException (Environment.GetResourceString("Arg_MustBeChar")); - } - - return (m_value-((Char)value).m_value); - } - - [Pure] - public int CompareTo(Char value) { - return (m_value-value); - } - - // Overrides System.Object.ToString. - [Pure] - public override String ToString() { - Contract.Ensures(Contract.Result<String>() != null); - return Char.ToString(m_value); - } - - [Pure] - public String ToString(IFormatProvider provider) { - Contract.Ensures(Contract.Result<String>() != null); - return Char.ToString(m_value); - } - - // - // Formatting Methods - // - - /*===================================ToString=================================== - **This static methods takes a character and returns the String representation of it. - ==============================================================================*/ - // Provides a string representation of a character. - [Pure] - public static string ToString(char c) => string.CreateFromChar(c); - - public static char Parse(String s) { - if (s==null) { - throw new ArgumentNullException(nameof(s)); - } - Contract.EndContractBlock(); - - if (s.Length!=1) { - throw new FormatException(Environment.GetResourceString("Format_NeedSingleChar")); - } - return s[0]; - } - - public static bool TryParse(String s, out Char result) { - result = '\0'; - if (s == null) { - return false; - } - if (s.Length != 1) { - return false; - } - result = s[0]; - return true; - } - - // - // Static Methods - // - /*=================================ISDIGIT====================================== - **A wrapper for Char. Returns a boolean indicating whether ** - **character c is considered to be a digit. ** - ==============================================================================*/ - // Determines whether a character is a digit. - [Pure] - public static bool IsDigit(char c) { - if (IsLatin1(c)) { - return (c >= '0' && c <= '9'); - } - return (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.DecimalDigitNumber); - } - - - /*=================================CheckLetter===================================== - ** Check if the specified UnicodeCategory belongs to the letter categories. - ==============================================================================*/ - internal static bool CheckLetter(UnicodeCategory uc) { - switch(uc) { - case (UnicodeCategory.UppercaseLetter): - case (UnicodeCategory.LowercaseLetter): - case (UnicodeCategory.TitlecaseLetter): - case (UnicodeCategory.ModifierLetter): - case (UnicodeCategory.OtherLetter): - return (true); - } - return (false); - } - - /*=================================ISLETTER===================================== - **A wrapper for Char. Returns a boolean indicating whether ** - **character c is considered to be a letter. ** - ==============================================================================*/ - // Determines whether a character is a letter. - [Pure] - public static bool IsLetter(char c) { - if (IsLatin1(c)) { - if (IsAscii(c)) { - c |=(char)0x20; - return ((c >= 'a' && c <= 'z')); - } - return (CheckLetter(GetLatin1UnicodeCategory(c))); - } - return (CheckLetter(CharUnicodeInfo.GetUnicodeCategory(c))); - } - - private static bool IsWhiteSpaceLatin1(char c) { - - // There are characters which belong to UnicodeCategory.Control but are considered as white spaces. - // We use code point comparisons for these characters here as a temporary fix. - - // U+0009 = <control> HORIZONTAL TAB - // U+000a = <control> LINE FEED - // U+000b = <control> VERTICAL TAB - // U+000c = <contorl> FORM FEED - // U+000d = <control> CARRIAGE RETURN - // U+0085 = <control> NEXT LINE - // U+00a0 = NO-BREAK SPACE - if ((c == ' ') || (c >= '\x0009' && c <= '\x000d') || c == '\x00a0' || c == '\x0085') { - return (true); - } - return (false); - } - - /*===============================ISWHITESPACE=================================== - **A wrapper for Char. Returns a boolean indicating whether ** - **character c is considered to be a whitespace character. ** - ==============================================================================*/ - // Determines whether a character is whitespace. - [Pure] - public static bool IsWhiteSpace(char c) { - - if (IsLatin1(c)) { - return (IsWhiteSpaceLatin1(c)); - } - return CharUnicodeInfo.IsWhiteSpace(c); - } - - - /*===================================IsUpper==================================== - **Arguments: c -- the characater to be checked. - **Returns: True if c is an uppercase character. - ==============================================================================*/ - // Determines whether a character is upper-case. - [Pure] - public static bool IsUpper(char c) { - if (IsLatin1(c)) { - if (IsAscii(c)) { - return (c >= 'A' && c <= 'Z'); - } - return (GetLatin1UnicodeCategory(c)== UnicodeCategory.UppercaseLetter); - } - return (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.UppercaseLetter); - } - - /*===================================IsLower==================================== - **Arguments: c -- the characater to be checked. - **Returns: True if c is an lowercase character. - ==============================================================================*/ - // Determines whether a character is lower-case. - [Pure] - public static bool IsLower(char c) { - if (IsLatin1(c)) { - if (IsAscii(c)) { - return (c >= 'a' && c <= 'z'); - } - return (GetLatin1UnicodeCategory(c)== UnicodeCategory.LowercaseLetter); - } - return (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.LowercaseLetter); - } - - internal static bool CheckPunctuation(UnicodeCategory uc) - { - switch (uc) { - case UnicodeCategory.ConnectorPunctuation: - case UnicodeCategory.DashPunctuation: - case UnicodeCategory.OpenPunctuation: - case UnicodeCategory.ClosePunctuation: - case UnicodeCategory.InitialQuotePunctuation: - case UnicodeCategory.FinalQuotePunctuation: - case UnicodeCategory.OtherPunctuation: - return (true); - } - return (false); - } - - - /*================================IsPunctuation================================= - **Arguments: c -- the characater to be checked. - **Returns: True if c is an punctuation mark - ==============================================================================*/ - // Determines whether a character is a punctuation mark. - [Pure] - public static bool IsPunctuation(char c){ - if (IsLatin1(c)) { - return (CheckPunctuation(GetLatin1UnicodeCategory(c))); - } - return (CheckPunctuation(CharUnicodeInfo.GetUnicodeCategory(c))); - } - - /*=================================CheckLetterOrDigit===================================== - ** Check if the specified UnicodeCategory belongs to the letter or digit categories. - ==============================================================================*/ - internal static bool CheckLetterOrDigit(UnicodeCategory uc) { - switch (uc) { - case UnicodeCategory.UppercaseLetter: - case UnicodeCategory.LowercaseLetter: - case UnicodeCategory.TitlecaseLetter: - case UnicodeCategory.ModifierLetter: - case UnicodeCategory.OtherLetter: - case UnicodeCategory.DecimalDigitNumber: - return (true); - } - return (false); - } - - // Determines whether a character is a letter or a digit. - [Pure] - public static bool IsLetterOrDigit(char c) { - if (IsLatin1(c)) { - return (CheckLetterOrDigit(GetLatin1UnicodeCategory(c))); - } - return (CheckLetterOrDigit(CharUnicodeInfo.GetUnicodeCategory(c))); - } - - /*===================================ToUpper==================================== - ** - ==============================================================================*/ - // Converts a character to upper-case for the specified culture. - // <;<;Not fully implemented>;>; - public static char ToUpper(char c, CultureInfo culture) { - if (culture==null) - throw new ArgumentNullException(nameof(culture)); - Contract.EndContractBlock(); - return culture.TextInfo.ToUpper(c); - } - - /*=================================TOUPPER====================================== - **A wrapper for Char.toUpperCase. Converts character c to its ** - **uppercase equivalent. If c is already an uppercase character or is not an ** - **alphabetic, nothing happens. ** - ==============================================================================*/ - // Converts a character to upper-case for the default culture. - // - public static char ToUpper(char c) { - return ToUpper(c, CultureInfo.CurrentCulture); - } - - - // Converts a character to upper-case for invariant culture. - public static char ToUpperInvariant(char c) { - return ToUpper(c, CultureInfo.InvariantCulture); - |